title,body,link,tags,view_count,is_answered,score,answer_count
Unit testing coroutines runBlockingTest: This job has not completed yet,"<p>Please find below a function using a coroutine to replace callback : </p>

<pre><code>override suspend fun signUp(authentication: Authentication): AuthenticationError {
    return suspendCancellableCoroutine {
        auth.createUserWithEmailAndPassword(authentication.email, authentication.password)
            .addOnCompleteListener(activityLifeCycleService.getActivity()) { task -&gt;
                if (task.isSuccessful) {
                    it.resume(AuthenticationError.SignUpSuccess)
                } else {
                    Log.w(this.javaClass.name, ""createUserWithEmail:failure"", task.exception)
                    it.resume(AuthenticationError.SignUpFail)
                }
            }
    }
}
</code></pre>

<p>Now I would like to unit testing this function. I am using Mockk : </p>

<pre><code>  @Test
  fun `signup() must be delegated to createUserWithEmailAndPassword()`() = runBlockingTest {

      val listener = slot&lt;OnCompleteListener&lt;AuthResult&gt;&gt;()
      val authentication = mockk&lt;Authentication&gt; {
        every { email } returns ""email""
        every { password } returns ""pswd""
      }
      val task = mockk&lt;Task&lt;AuthResult&gt;&gt; {
        every { isSuccessful } returns true
      }

      every { auth.createUserWithEmailAndPassword(""email"", ""pswd"") } returns
          mockk {
            every { addOnCompleteListener(activity, capture(listener)) } returns mockk()
          }

    service.signUp(authentication)

      listener.captured.onComplete(task)
    }
</code></pre>

<p>Unfortunately this test failed due to the following exception : <code>java.lang.IllegalStateException: This job has not completed yet</code> </p>

<p>I tried to replace <code>runBlockingTest</code> with <code>runBlocking</code> but the test seems to wait in an infinite loop.</p>

<p>Can someone help me with this UT please?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/61224047/unit-testing-coroutines-runblockingtest-this-job-has-not-completed-yet,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines', 'mockk']",33143,True,65,10
Pandas Unit Testing,"<p>I wrote a simple script of Pricing Service. I want to write now unit tests for it. How would You propose me to do that? Should i test output of every function only or something more? I read about unit tests, however, I'm not sure how to implement them correctly in my script. I will be gratefully for all advices!</p>

<p>Below You can find my code. I know it's messy and has bad complexity but for now is enough ( i will change many things in future like replace iterrows() etc.)</p>

<pre><code>import pandas as pd


def read_data():
    data = pd.read_csv(""data.csv"")
    matchings = pd.read_csv(""matchings.csv"")
    currencies = pd.read_csv(""currencies.csv"")

    return data,matchings,currencies

def write_data(filtered_data):
    filtered_data.to_csv('top_products.csv',index=False)

def conversion(data,curriencies):
    for index,row in data.iterrows():
        if row['currency'] ==  'GBP':
            data['price'][index] = row['price'] * curriencies['ratio'].loc[
                curriencies['currency'] =='GBP']
            data['currency'].loc[index] ='PLN'
            data['total_price'] = data['price'] * data['quantity']
        elif row['currency'] == 'EU':
            data['price'][index] = row['price'] * curriencies['ratio'].loc[
                curriencies['currency'] == 'EU']
            data['currency'].loc[index] ='PLN'
            data['total_price'] = data['price'] * data['quantity']
        elif row['currency'] == 'PLN':
            data['total_price'] = data['price'] * data['quantity']

    return data

def filter(data,matchings):
    data = data.sort_values(by=['matching_id','total_price'],ascending=False)
    data_copy = data.copy()
    filtered_data = pd.DataFrame(columns=['ignored_products_count'])

    for index,row in matchings.iterrows():
        data[data['matching_id'] == row['matching_id']] = data[
             data['matching_id']==row['matching_id']].iloc[
             0:row['top_priced_count']]

    filtered_data = filtered_data.reset_index(drop=True)
    filtered_data['total_price'] = data.groupby('matching_id')[
        'total_price'].sum()
    filtered_data['avg_price'] = data.groupby(['matching_id'])[
        'total_price'].mean()
    filtered_data['currency'] = data['currency']
    data = data.dropna()
    filtered_data['matching_id'] = filtered_data.index

    for index,row in filtered_data.iterrows():
        filtered_data['ignored_products_count'].loc[index] = len(data_copy[
                     data_copy['matching_id'] == row['matching_id']]) - len(
                     data[data['matching_id'] == row['matching_id']])

    filtered_data = filtered_data.reset_index(drop=True)
    filtered_data = filtered_data[['matching_id','total_price','avg_price',
                                   'currency','ignored_products_count']]
    print(filtered_data)

    return filtered_data

if __name__ == ""__main__"":

    data,matchings,currencies = read_data()
    converted_data = conversion(data,currencies)
    filtered_data = filter(converted_data,matchings)
    write_data(filtered_data)
</code></pre>
",https://stackoverflow.com/questions/61438551/pandas-unit-testing,"['python', 'pandas', 'unit-testing']",65,False,2,0
Golang Unit Testing,"<p>I am stuck on how to write tests. I have following public function. <code>GetAccountNumber()</code> has its own logic.  I would like to return a mock value for <code>GetAccountNumber()</code>. In Java, I could do <code>when(object.method()).thenReturn(""returnValue"")</code>. Is something similar available for go how can I accomplish that. I am going through bunch of go documentation but have not found anything useful yet.</p>

<pre><code>func GetConfigName() string {
    var configName string
    accountNumber := GetAccountNumber()
    switch *accountNumber {
    case ""123"":
        configName = ""test1""
    case ""456"":
        configName = ""test2""

    return configName
}
</code></pre>
",https://stackoverflow.com/questions/62351902/golang-unit-testing,"['unit-testing', 'go']",264,True,2,1
Unit Testing http.MultipartForm,"<p>I want to test my http method that takes a post request and stores the given files.</p>
<pre class=""lang-golang prettyprint-override""><code>func DownloadFiles(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(2097152) //2MB
    
    files := r.MultipartForm.File[&quot;documents&quot;] //files of type []*multipart.FileHeader
    for _, handler := range files {            //handler of type *multipart.FileHeader
        file, err := handler.Open()            //file of type multipart.File
        ... //Do something with files
    }
    w.WriteHeader(http.StatusOK)
}
</code></pre>
<p>How can i prepare a valid http.Request that features multipart-formdata and calls the function?</p>
",https://stackoverflow.com/questions/65217072/unit-testing-http-multipartform,"['unit-testing', 'http', 'go', 'post', 'multipartform-data']",46,False,2,0
Unit testing LitElement,"<p>I have been looking everywhere and can't seem to find an answer so while this question may not contain a lot of code I was hoping that there was someone here with experience in subcomponents / Lit framework that could tell me how to unit test the components that you make.</p>
<p>Right now, I have the following element.</p>
<pre><code>class SdkArticle extends LitElement {
    static get properties() {
        return {
            data: {type: Object}
        };
    }

    constructor() {
        super();
        this.data = {};
    }

    render() {
        return html `
        &lt;style&gt;
            .row {
              display: flex;
            }
            
            /* Create two equal columns that sits next to each other */
            .column {
              flex: ${100 / this.data.columnData.length}%;
              padding: 10px;
              height: 300px; /* Should be removed. Only for demonstration */
            }
            h2{
            padding-left:  10px;
            }
        &lt;/style&gt;
       
        &lt;div&gt;
          &lt;h2&gt;${this.data.title}&lt;/h2&gt;
        &lt;/div&gt;
        
        &lt;div class=&quot;row&quot;&gt;
             ${this.data.columnData.map(
            columData =&gt;
                html`
                    ${this.generateHtml(columData)}
                `,
        )}
         &lt;/div&gt;
`;
    }

    //Based on the settings we generate the extra html depending on the columns
    generateHtml(columnData) {
        switch (columnData.dataType) {
            case 'image':
                if (columnData.addon != null) {
                    if (columnData.addon !== null &amp;&amp; columnData.addon.type === 'link') {
                        return html `&lt;div class=&quot;column&quot;&gt;&lt;img src=${columnData.imageSrc}&gt;&lt;/div&gt;&lt;div&gt;&lt;sdk-button link=${columnData.addon.href}&gt;${columnData.addon.text}&lt;/sdk-button&gt;&lt;/div&gt;`;
                    }
                    else {
                        return html `&lt;div class=&quot;column&quot;&gt;&lt;img src=${columnData.imageSrc}&gt;&lt;/div&gt;`;
                    }
                }
                else {
                    return html `&lt;div class=&quot;column&quot;&gt;&lt;img src=${columnData.imageSrc}&gt;&lt;/div&gt;`;
                }
            case 'text':
                if (columnData.addon != null &amp;&amp; columnData.addon.type === 'link') {
                    return html `&lt;div class=&quot;column&quot;&gt;&lt;p&gt;${columnData.text} &lt;/p&gt;&lt;sdk-button link=${columnData.addon.href}&gt;${columnData.addon.text}&lt;/sdk-button&gt; &lt;/div&gt;`;
                } else {

                    return html `&lt;div class=&quot;column&quot;&gt;&lt;p&gt;${columnData.text} &lt;/p&gt; &lt;/div&gt;`;
                }
        }
    }
}

customElements.define('sdk-article', SdkArticle);
</code></pre>
<p>What framework do I use to test this? And how can I write a test to test my component?</p>
",https://stackoverflow.com/questions/62653739/unit-testing-litelement,"['javascript', 'unit-testing', 'web-component', 'lit-element', 'polymer-3.x']",1569,False,1,0
Strapi Unit Testing,"<p>For strapi unit testing (using mysql as a database) i have followed the official documentation, and when i am running the same with <strong>npm run test</strong> i am getting errors like below</p>
<blockquote>
<p>my-project@0.1.0 test D:\Gerrit\website_backend\TE_MCA_DMSWEBV2
jest --forceExit --detectOpenHandles</p>
</blockquote>
<p>●  process.exit called with &quot;1&quot;</p>
<pre><code>  at Strapi.stop (node_modules/strapi/lib/Strapi.js:238:13)
  at Strapi.stopWithError (node_modules/strapi/lib/Strapi.js:224:17)
  at node_modules/strapi-connector-bookshelf/lib/mount-models.js:625:14
</code></pre>
<p>RUNS  tests/app.test.js
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-project@0.1.0 test: <code>jest --forceExit --detectOpenHandles</code>
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the my-project@0.1.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.</p>
<p><strong>database.js</strong></p>
<pre><code>module.exports = ({ env }) =&gt; ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'bookshelf',
      settings: {
        client: 'mysql',
        host: env('DATABASE_HOST', '127.0.0.1'),
        port: env.int('DATABASE_PORT', 3306),
        database: env('DATABASE_NAME', 'myDB'),
        username: env('DATABASE_USERNAME', 'root'),
        password: env('DATABASE_PASSWORD', ''),
        ssl: env.bool('DATABASE_SSL', false),
      },
      options: {}
    },
  },
});
</code></pre>
<p><strong>test/database.json</strong></p>
<pre><code>{
  &quot;defaultConnection&quot;: &quot;default&quot;,
  &quot;connections&quot;: {
    &quot;default&quot;: {
      &quot;connector&quot;: &quot;bookshelf&quot;,
      &quot;settings&quot;: {
        &quot;client&quot;: &quot;mysql&quot;,
        &quot;filename&quot;: &quot;.tmp/test.db&quot;
      },
      &quot;options&quot;: {
        &quot;useNullAsDefault&quot;: true,
        &quot;pool&quot;: {
          &quot;min&quot;: 0,
          &quot;max&quot;: 15
        }
      }
    }
  }
}
</code></pre>
<p><strong>tests/app.test.js</strong></p>
<pre><code>const fs = require('fs');
const { setupStrapi } = require('./helpers/strapi');

/** this code is called once before any test is called */
beforeAll(async (done) =&gt; {
  await setupStrapi(); // singleton so it can be called many times
  done();
});

/** this code is called once before all the tested are finished */
afterAll(async (done) =&gt; {
  const dbSettings = strapi.config.get('database.connections.default.settings');

  //delete test database after all tests
  if (dbSettings &amp;&amp; dbSettings.filename) {
    const tmpDbFile = `${__dirname}/../${dbSettings.filename}`;
    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }
  }
  done();
});

it('strapi is defined', async (done) =&gt; {
  expect(strapi).toBeDefined();
  done();
});
</code></pre>
<p><strong>tests/helpers/strapi.js</strong></p>
<pre><code>const Strapi = require('strapi');
const http = require('http');

let instance;

async function setupStrapi() {
  if (!instance) {
    /** the following code in copied from `./node_modules/strapi/lib/Strapi.js` */
    await Strapi().load();
    instance = strapi; // strapi is global now
    await instance.app
      .use(instance.router.routes()) // populate KOA routes
      .use(instance.router.allowedMethods()); // populate KOA methods

    instance.server = http.createServer(instance.app.callback());
  }
  return instance;
}
module.exports = { setupStrapi };
</code></pre>
",https://stackoverflow.com/questions/62888737/strapi-unit-testing,"['javascript', 'node.js', 'unit-testing', 'strapi']",960,False,1,1
Pyspark unit testing,"<pre><code>import unittest
import warnings
from datetime import datetime

from pyspark.conf import SparkConf
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
from pyspark.sql.types import StringType, StructField, StructType, TimestampType, FloatType

from ohlcv_service.ohlc_gwa import datetime_col


class ReusedPySparkTestCase(unittest.TestCase):
    sc_values = {}

    @classmethod
    def setUpClass(cls):
        conf = (SparkConf().setMaster('local[2]')
                .setAppName(cls.__name__)
                .set('deploy.authenticate.secret', '111111'))
        cls.sc = SparkContext(conf=conf)
        cls.sc_values[cls.__name__] = cls.sc
        cls.spark = (SparkSession.builder
                     .master('local[2]')
                     .appName('local-testing-pyspark-context')
                     .getOrCreate())

    @classmethod
    def tearDownClass(cls):
        print('....calling stop tearDownClass, the content of sc_values=', cls.sc_values, '\n')
        for key, sc in cls.sc_values.items():
            print('....closing=', key, '\n')
            sc.stop()

        cls.sc_values.clear()


class TestDateTimeCol(ReusedPySparkTestCase):

    def setUp(self):
        # Ignore ResourceWarning: unclosed socket.socket!
        warnings.simplefilter(""ignore"", ResourceWarning)

    def test_datetime_col(self):
        test_data_frame = self.create_data_frame(rows=[['GWA',
                                                        '2b600c2a-782f-4ccc-a675-bbbd7d91fde4',
                                                        '02fb81fa-91cf-4eab-a07e-0df3c107fbf8',
                                                        '2019-06-01T00:00:00.000Z',
                                                        0.001243179008694,
                                                        0.001243179008694,
                                                        0.001243179008694,
                                                        0.001243179008694,
                                                        0.001243179008694]],
                                                 columns=[StructField('indexType', StringType(), False),
                                                          StructField('id', StringType(), False),
                                                          StructField('indexId', StringType(), False),
                                                          StructField('timestamp', StringType(), False),
                                                          StructField('price', FloatType(), False),
                                                          StructField('open', FloatType(), False),
                                                          StructField('high', FloatType(), False),
                                                          StructField('low', FloatType(), False),
                                                          StructField('close', FloatType(), False)])
        expected = self.create_data_frame(rows=[['GWA',
                                                 '2b600c2a-782f-4ccc-a675-bbbd7d91fde4',
                                                 '02fb81fa-91cf-4eab-a07e-0df3c107fbf8',
                                                 '2019-06-01T00:00:00.000Z',
                                                 '1559347200',
                                                 0.001243179008694,
                                                 0.001243179008694,
                                                 0.001243179008694,
                                                 0.001243179008694,
                                                 0.001243179008694]],
                                          columns=[StructField('indexType', StringType(), False),
                                                   StructField('id', StringType(), False),
                                                   StructField('indexId', StringType(), False),
                                                   StructField('timestamp', StringType(), False),
                                                   StructField('datetime', TimestampType(), True),
                                                   StructField('price', FloatType(), False),
                                                   StructField('open', FloatType(), False),
                                                   StructField('high', FloatType(), False),
                                                   StructField('low', FloatType(), False),
                                                   StructField('close', FloatType(), False)])
        print(expected)
        convert_to_datetime = datetime_col(test_data_frame)
        self.assertEqual(expected, convert_to_datetime)

    def create_data_frame(self, rows, columns):
        rdd = self.sc.parallelize(rows)
        df = self.spark.createDataFrame(rdd.collect(), test_schema(columns=columns))
        return df


def test_schema(columns):
    return StructType(columns)


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

<p><strong>Error</strong></p>

<pre><code>TimestampType can not accept object '1559347200' in type &lt;class 'str'&gt;
</code></pre>

<p><strong>datetime_col Function</strong></p>

<pre><code>def datetime_col(df):
      return df.select(""indexType"", ""id"", ""indexId"", ""timestamp"",
                     (F.col(""timestamp"").cast(TimestampType)).alias(""datetime""),
                     ""price"", ""open"", ""high"", ""low"", ""close"")
</code></pre>

<p>The datetime col functions converts the timestamp from string to timestamp format. This work properly in EMR-Zeppelin notebook, but when I try to unit test this it throws the above error. The spark and pyspark version in my local is 2.3.1. How to resolve this error. When I try to convert spark df to pandas df it converts the timestamp as +12.</p>
",https://stackoverflow.com/questions/60359624/pyspark-unit-testing,"['python', 'unit-testing', 'dataframe', 'apache-spark', 'pyspark']",1667,False,-1,1
Unit testing Angular,"<p>Can somebody tell me please how to write unit tests for the below statement?!</p>
<pre><code>localStorage.getItem('token') ? (this.isAuthenticated = true) : (this.isAuthenticated = false);
</code></pre>
<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/63881572/unit-testing-angular,"['angular', 'typescript', 'unit-testing', 'if-statement', 'conditional-statements']",50,True,-2,2
Unit testing QueueRuntimeInfo,"<p>I'm trying to write unit tests around Microsoft.Azure.ServiceBus and need to return a mock instance of Microsoft.Azure.ServiceBus.Management.QueueRuntimeInfo in my tests. QueueRuntimeInfo has an internal constructor which takes a string as a parameter. So any attempt with Moq or in code to instantiate gets QueueRuntimeInfo does not contain a constructor that takes 0 arguments. Cannot access internal constructor of QueueRuntimeInfo here.</p>

<p>Read numerous articles including: <a href=""http://www.blackwasp.co.uk/MoqInternals.aspx"" rel=""nofollow noreferrer"">http://www.blackwasp.co.uk/MoqInternals.aspx</a> and <a href=""http://www.blackwasp.co.uk/CSharpFriendAssembly.aspx"" rel=""nofollow noreferrer"">http://www.blackwasp.co.uk/CSharpFriendAssembly.aspx</a></p>

<p>But not sure if this the correct way to go and being honest not 100% sure of how to put/reference InternalsVisibleTo in my unit test which is in a .net core 2.2 solution.</p>

<p>Is it possible to be able to create an instance of this in my unit tests please? </p>
",https://stackoverflow.com/questions/61957601/unit-testing-queueruntimeinfo,"['c#', '.net-core', 'moq', 'xunit']",82,False,0,0
MVVM Unit Testing,"<p>I have developed an application in WPF using MVVM because of the added benefits of seperation and test ability. However I am trying to write some unit tests as part of this but am confused about what to test. I know how to write the unit tests, hovever am unsure of what should I be testing in the view model, which is made up of my properties for data bindings and methods for some logic.  </p>

<p>Furthermore most of my view model methods are private because they only need to be accessed from inside of the view model so they cannot be simply tested via unit tests like a public method would be. This results in being able to test very little of the view model which opposes the supposed value of MVVM in concerns to testing and from a quality POV is disadvantageous as I have to rely on manual tests to prove the functionality of my code. </p>

<p>I might be wrong and am new to using MVVM but any help would be appreciated on how to go about this. </p>
",https://stackoverflow.com/questions/62453694/mvvm-unit-testing,"['c#', 'wpf', 'unit-testing', 'mvvm']",224,True,-1,2
Unit testing without testthat,"<p>There is one things which is wondering me. I've read something about unit testing and all I read was significantly connected with testthat (package created for unit testing). But for sure there are other approaches in R to do unit testing without using testthat package. So why they are unpopular in such level that it's even hard o find article about it ? what are the main advantages of testthat package which overwhelms unit testing market ?</p>
",https://stackoverflow.com/questions/63827740/unit-testing-without-testthat,"['r', 'unit-testing']",411,True,6,1
Unit testing injectable services,"<p>I am having problems while performing a simple unit test in my NX workspace. What I am attempting to do is to 1) configure TestBed and 2) Inject service. However, even if I use scaffolded dummy service, the test still fails as the injected service is said to be <code>undefined</code></p>
<p>test.service.ts</p>
<pre><code>import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TestService {
  constructor() { }
}
</code></pre>
<p>test.service.spec.ts</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { TestService } from './test.service';

describe('TestService', () =&gt; {
  let service: TestService;
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [ TestService ]
    });
    service = TestBed.inject(TestService);
  });
  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });
});
</code></pre>
<p>Does anybody have an idea why is this happening? What exactly is the problem here?</p>
<p><strong>Edit:</strong>
Yes, I do know I can create a mock. However, the issue still seems strange to me so I would like to get to the bottom of it rather than finding a workaround.</p>
<p><strong>Edit 2:</strong>
Using <code>ng test &lt;project&gt; --test-file=&lt;filename&gt;</code> directly yields the same results are using NXCLI to perform tests</p>
<p><strong>Edit 3:</strong> I shared my code on StackBlitz as requested: <a href=""https://stackblitz.com/edit/ng-unittest-issue"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/ng-unittest-issue</a></p>
",https://stackoverflow.com/questions/63172146/unit-testing-injectable-services,"['angular', 'jestjs', 'karma-runner', 'nomachine-nx']",15275,True,5,3
Unit testing express.js routes,"<p>I am new to express and very new to unit testing. Consider the following code:</p>

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

var bookingsController = require (""../controllers/bookings"");

router
   .route('/')
   .get(bookingsController.bookings_get)
   .post(bookingsController.bookings_post)


router
   .route('/:id')
   .get(bookingsController.bookings_get_id)
   .put(bookingsController.bookings_put_id)
   .delete(bookingsController.bookings_delete_id)

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

<p>What is the right/recommended way of writing unit tests for this? I would like to be able to test, for example, that <code>router.route('/:id')</code> does not accept POST calls.</p>

<p>I know I can do this with supertest, but I believe that would be considered an integration test as supertest would start the app the run the test.</p>

<p>I've read and tried multiple node.js/express.js testing tutorials but couldn't find an answer to this. Any pointers to existing tutorials most welcome. Direct answers here, even more :)</p>
",https://stackoverflow.com/questions/61529619/unit-testing-express-js-routes,"['javascript', 'node.js', 'unit-testing', 'express']",2703,True,5,1
Unit Testing with ILoggerProvider,"<p>I have the code like this in my unit test setup:</p>

<pre><code>IServiceCollection services = new ServiceCollection();
services.AddSingleton&lt;IDependency, Dependency&gt;();
services.AddLogging();
services.RemoveAll&lt;ILoggerProvider&gt;();
services.AddSingleton&lt;ILoggerProvider, MyCustomProvider&gt;(provider =&gt;
{
    var myDependency = provider.GetService&lt;IDependency&gt;();
    return new MyCustomProvider(myDependency );
});
var serviceProvider = services.BuildServiceProvider();

var logger = serviceProvider.GetService&lt;ILogger&gt;();
</code></pre>

<p>When I run this <code>logger</code> is null.</p>

<p>The lambda for the DI factory to create <code>MyCustomProvider</code> is never called.  Nor is the constructor to <code>MyCustomProvider</code> nor the constructor of the class I made that implements <code>ILogger</code>.</p>

<p>I am guessing that I am missing a step to wire this up.  But there is a lot of conflicting documentation out there between .Net Core 1, 2 and 3.</p>

<p><strong>What do I need to do to wire up my provider the .Net Core 3 way?</strong>  (Such that I can get an <code>ILogger</code> that uses it.)</p>

<p>NOTES:</p>

<ul>
<li>I don't call <code>LoggingBuilder.AddProvider</code>.  But if you look at the <a href=""https://github.com/aspnet/Logging/blob/2d2f31968229eddb57b6ba3d34696ef366a6c71b/src/Microsoft.Extensions.Logging/LoggingBuilderExtensions.cs#L22"" rel=""nofollow noreferrer"">source code</a> for that extension, it just calls <code>AddSingleton</code>, which is what I do, but with a factory.  (Got the idea <a href=""https://stackoverflow.com/a/50991749/16241"">here</a>.)</li>
<li>Similarly <code>services.RemoveAll&lt;ILoggerProvider&gt;()</code> is the same as calling <code>ClearProviders</code>.</li>
<li>My goal is to simulate an injection of an ILogger into a class constructor.  </li>
</ul>

<p>For Example:  </p>

<pre><code>public class SomeClass
{
     public SomeClass(ILogger&lt;SomeClass&gt; logger)
     {
          // Do Stuff
     }
}
</code></pre>

<p>Somehow this is done without indicating any provider.  I would like to make it be the same in my unit test.  (Just use my custom provider.)</p>
",https://stackoverflow.com/questions/61674945/unit-testing-with-iloggerprovider,"['c#', 'asp.net-core', '.net-core', 'asp.net-core-3.1']",1161,True,4,3
unit testing VIPER protocols,"<p>After reading several posts and articles about this issue I'm still confused about how to test a method in a VIPER architecture (for example with Swift).</p>

<p>If I had this code:</p>

<p>Presenter class</p>

<pre><code>protocol InteractorToPresenterProtocol: class {

    func showInfo(info: Info)
}

class Presenter {

    private var interactor: PresenterToInteractorProtocol?

    init() {}

    func makeSomeStuffInPresenter() {

        // make some stuff 
        ...
        interactor?.makeSomeStuffInInteractor()
    }
}

extension Presenter : InteractorToPresenterProtocol {

    func showInfo(info: Info) {

       print(info)
    }    
}
</code></pre>

<p>Interactor class:</p>

<pre><code>protocol PresenterToInteractorProtocol: class {

    func makeSomeStuffInInteractor()
}

class Interactor {

    private var presenter: InteractorToPresenterProtocol?

    init() {}
}

extension Interactor : PresenterToInteractorProtocol {

    func makeSomeStuffInInteractor() {

       // make some stuff 
       ...
       presenter?.showInfo(info)
    }    
}
</code></pre>

<p>How should I test makeSomeStuffInPresenter method?</p>
",https://stackoverflow.com/questions/62398690/unit-testing-viper-protocols,"['swift', 'unit-testing', 'viper-architecture']",2817,True,4,1
Mockito unit testing RestTemplate,"<p>I am using RestTemplate <code>postForEntity</code> method to post body to an endpoint. I need help with writing test case for my code using Mockito. The return type is void but it can be changed to <code>Types</code> or <code>code</code> if needed to test. I have referred many other documentation but they are very general, I tried using them but most did not work for me as the <code>request</code> and return type are different. . Any suggestions are appreciated. Thank you </p>

<p>Here is my Java class</p>

<pre><code>    public void postJson(Set&lt;Type&gt; Types){
        try {
            String oneString = String.join("","", Types);
           Map&lt;String, String&gt; requestBody = new HashMap&lt;&gt;();
            requestBody.put(""type"", oneString);
            JSONObject jsonObject = new JSONObject(requestBody);
            HttpEntity&lt;String&gt; request = new HttpEntity&lt;String&gt;(jsonObject.toString(), null);
ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST,
                    new HttpEntity&lt;&gt;(request, getHttpHeaders()), String.class);

        } 
    }
} 
</code></pre>
",https://stackoverflow.com/questions/59780621/mockito-unit-testing-resttemplate,"['java', 'unit-testing', 'post', 'junit', 'resttemplate']",20160,True,4,4
Unit testing Mock GCS,"<p>I have a hard time to find a way to make a unit test for the <code>read</code> and <code>write</code> methods present in this class. I am trying to create a mock with the mock patch library in order to avoid calling Google Storage but I have a hard time figure out how to do it.</p>
<pre><code>from google.cloud import storage


class GCSObject(str):
    

    def __init__(self, uri=&quot;&quot;):
        self.base, self.bucket, self.path = self.parse_uri(uri)


    def parse_uri(self, uri):
        uri = uri.lstrip(&quot;gs://&quot;).replace(&quot;//&quot;, &quot;/&quot;).split(&quot;/&quot;, 1)
        if len(uri) &gt; 1:
            return (&quot;gs://&quot;, uri[0], uri[1])
        else:
            return (&quot;gs://&quot;, uri[0], &quot;&quot;)

    def read(self) -&gt; bytes:
        storage_client = storage.Client()
        bucket = storage_client.bucket(self.bucket)
        return bucket.blob(self.path).download_as_string()

    def write(self, content: bytes):
        storage_client = storage.Client()
        bucket = storage_client.get_bucket(self.bucket)
        blob = bucket.blob(self.path)
        blob.upload_from_string(content)
</code></pre>
<p><strong>What I am currently trying to do</strong></p>
<pre><code>@mock.patch(&quot;packages.pyGCP.pyGCP.gcs.storage.Client&quot;)
def test_upload(client):
    gcs_path = GCSObject(&quot;fake_path&quot;)
    reader = gcs_path.read()  
    #  confused what I should assert 
</code></pre>
",https://stackoverflow.com/questions/64672497/unit-testing-mock-gcs,"['python', 'unit-testing', 'testing', 'google-cloud-storage', 'python-mock']",8178,True,4,1
Angular Unit Testing NgOnInit,"<p>I will be very grateful if you help me to understand something. 
I have a component, which display some data. In ngOnInit() the http-service method is called to get data from server. Here is code:</p>

<pre><code>// isLogged - is get property
ngOnInit() {
  if (this.isLogged) {
    this.loadData();
 };
}

// Can't call in ngOnInit because this method is being used in other functions
loadData() {
  this.http.getData()
           .subscribe((result) =&gt; this.dataToDisplay = result);
}

get isLogged() {
    // this function checks for token in localStorage via custom token service. 
}
</code></pre>

<p>I write the test for loadData()</p>

<pre><code>it('should load data', async(() =&gt; {
   component.loadData();
   fixture.whenStable().then( () =&gt; {
       fixture.detectChanges();
       expect(component.dataToDisplay).toEqual(mockData);
   });
});
</code></pre>

<p>And it works as expected. But my question is: how I should test the ngOnInit? All that this method does is calling loadData. But how to check that if get property returns true the method is calling? I'm confused (( </p>
",https://stackoverflow.com/questions/61424357/angular-unit-testing-ngoninit,"['angular', 'unit-testing']",3899,True,2,1
Angular5csv Jasmine Unit Testing,"<p>Our Project is using Angular5Csv to create and download csv files . Is there any way to do jasmine test for download file and check the contents </p>
",https://stackoverflow.com/questions/62225234/angular5csv-jasmine-unit-testing,['angular'],71,False,2,0
Unit Testing nested methods,"<p>While I understand that when unit testing a method it is very important to mock all it's dependencies, what I still have confusion about is what happens when the method is nested? Do I mock only the dependencies of the parent method or do I mock the dependencies of the child method(s) as well or do I set expectations on the calls to the dependent object and set the exact return values so that I can perform the test that I want?</p>

<p>For instance, in the below example, if we want to unit test the method B, do we only mock <code>IHttpClientFactory</code> &amp; <code>ILogger</code> or do we  also set the method's return value to what we are actually expecting because otherwise when the test method executes it goes ahead and tries to execute methodC where it fails because the value of <code>client</code> after the line <code>var client = _clientFactory.CreateClient()</code> executes is null?</p>

<pre><code>using System.Net.Http;
...

public class classA
{
   private readonly IHttpClientFactory _clientFactory;
   private sting url = ""..."";
   private ILogger _log { get; set; }
   ...

   public classA(ILogger log, IHttpClientFactory clientFactory, ...)
   {
     _log = log;
     _clientFactory = clientFactory;
     ...
   }

   public string methodB(string inputB)
   {
      var varB = methodC(inputB);
      ...
      return ..;
   }

   public string methodC(string inputC)
   {
      ...
      var client = _clientFactory.CreateClient();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/json""));
      HttpResponseMessage httpResponseMessage = await client.PostAsync(url, new StringContent(inputC, Encoding.UTF8, ""application/json""));
      responJsonText = await httpResponseMessage.Content.ReadAsStringAsync();
      ...
      return ..;
   }

}
</code></pre>
",https://stackoverflow.com/questions/60513623/unit-testing-nested-methods,"['c#', 'unit-testing', 'mocking', 'moq']",1023,True,2,1
Unit Testing UNUserNotificationCenterDelegate Methods,"<p>I'd like to unit test some <code>UNUserNotificationCenterDelegate</code> methods, especially <code>userNotificationCenter(_, willPresent:, withCompletionHandler:)</code></p>
<p>To do that, I'd have to create an instance of <code>UNNotification</code>, but that's not really possible because it only has an <code>initWithCoder</code> initializer. What to do?</p>
<p>This is an example of what I'd like to test:</p>
<pre><code>func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -&gt; Void
) {
    completionHandler(.sound)
}
</code></pre>
",https://stackoverflow.com/questions/63512441/unit-testing-unusernotificationcenterdelegate-methods,"['swift', 'xcode', 'unit-testing', 'push-notification', 'unusernotificationcenter']",637,True,1,2
Unit testing chained constructors,"<p>When &quot;chaining&quot; constructors, should all unit tests that are run on the first constructor also be run on the second constructor (in addition to those that are unique to the second)?</p>
<p>I can see the benefit of being rigorous but trivial duplication of a large number of (simple) tests seems unnecessary. Having said that, the duplicated tests are only trivial for as long as <code>: this(a, b)</code> is present.</p>
<p>In the general case, it feels like I shouldn't be writing loads of unit tests that hinge on something trivial that will never change.</p>
<pre><code>      public MyObject(double a, double b)
      {
         // Do some minor calculations, initialise some properties
         Property1 = a * b;
         Property2 = Property1;
      }

      public MyObject(double a, double b, double c) 
         : this(a, b)
      {
         // Set more properties
         Property2 = (a * b) + c;
      }

      public double Property1
      {
         get;
      }

      public double Property2
      {
         get;
      }
</code></pre>
",https://stackoverflow.com/questions/60883669/unit-testing-chained-constructors,"['c#', 'unit-testing']",81,False,1,0
Azure ServiceBus Unit Testing,"<p>I have a method that connects to an Azure Service Bus Queue and posts messages. I need to Unit test this method. I have created a Mock Interface on the IqueueClient. I am using Moq framework for my unit test.
I am not able assert the test result.</p>
<pre><code>public class WebHookClient : IWebHookClient
{
   private readonly ILogger&lt;WebHookClient&gt; _logger;
   private readonly IQueueClient _queueClient;

public WebHookClient(IQueueClient queueClient, ILogger&lt;WebHookClient&gt; logger)
{
   _logger = logger;
   _queueClient = queueClient;
}

public async Task PostAsync(WebHookRequest webHookRequest)
{
try
   {
     var messageAsText = JsonConvert.SerializeObject(webHookRequest);

     var message = new Message(Encoding.UTF8.GetBytes(messageAsText));

     await _queueClient.SendAsync(message);
   }
   catch (Exception ex)
   {
   }
</code></pre>
<p>}</p>
<p>I need to Unit test the above method. So far I have tried the below</p>
<pre><code>    public class WebHookClientTests
{
    private readonly Mock&lt;IQueueClient&gt; _queueClient;
    private readonly IOptions&lt;WebHookOptions&gt; _options;
    private readonly Mock&lt;ILogger&lt;WebHookClient&gt;&gt; _logger;
    private readonly IWebHookClient _sut;


    public WebHookClientTests()
    {
        _queueClient = new Mock&lt;IQueueClient&gt;();
        _logger = new Mock&lt;ILogger&lt;WebHookClient&gt;&gt;();
        _sut = new WebHookClient(_queueClient.Object, _logger.Object);
    }

    [Fact]
    public async Task PostAsync_Verify_Message_Was_sent()
    {
        //Arrange
        var webHookRequest = new WebHookRequest();

        var messageAsText = JsonConvert.SerializeObject(webHookRequest);

        var message = new Message(Encoding.UTF8.GetBytes(messageAsText));

        _queueClient.Setup(x =&gt; x.SendAsync(It.IsAny&lt;Message&gt;())).Returns(Task.CompletedTask).Verifiable();

        //Act 

         await _sut.PostAsync(webHookRequest);

        //Assert

        _queueClient.Verify();

    }
</code></pre>
",https://stackoverflow.com/questions/63074491/azure-servicebus-unit-testing,"['azure', 'unit-testing', 'asp.net-core', 'moq', 'azureservicebus']",2285,True,1,1
Ionic unit testing alertcontroller,"<p>I am working for an application that uses an alert to tell the user it is using nfc. I am unit testing this app and put a spy on the alertcontroller.create method as follows:</p>
<pre><code>alertController.create = jasmine.createSpy().and.resolveTo({
    present: jasmine.createSpy()
});
</code></pre>
<p>In the unit test I want to check if it is called with the right alert options as follows:</p>
<pre><code>      expect(alertController.create).toHaveBeenCalledWith({
        header: 'NFC aan het lezen...',
        message: 'Hou de pas tegen de achterkant van de telefoon',
        buttons: [
          {
            text: 'Anuleren',
            role: 'cancel',
            handler: () =&gt; nfc.stopRead()
          }
        ]
      });
</code></pre>
<p>The problem however is that it gives an error while running the test because of the handler. How can I effectively test if the alertcontroller.create function is called with the correct values? As right now the test gives the following error:</p>
<pre><code>  Expected $[0].buttons[0].handler = Function to equal Function.
</code></pre>
<p>I want to check if the provided object is correct but the function doesn't check.</p>
",https://stackoverflow.com/questions/64749918/ionic-unit-testing-alertcontroller,"['angular', 'typescript', 'ionic-framework', 'jasmine']",632,True,1,1
Unit Testing Oracle views,"<p>I've searched for best practices, tools and libraries to test oracle db views, but did not find much. Some SQL editors have their own built-in ways, there are some libraries for SQL Server and there's <a href=""http://utplsql.org/"" rel=""nofollow noreferrer"">http://utplsql.org/</a> for PL/SQL, which seems to be the closest thing, but I'm not sure if it fits my needs.</p>
<p>Problem statement: we have tons of business logic written as SQL views. Over time this has become very hard to maintain and small changes can cause surprising regressions. (for all the usual reasons).</p>
<p>I would like something that integrates with a standard java build pipeline so that when we deploy any changes to the db objects (which we currently do with liquibase) we can run a full test suite and reduce the risk of regressions.</p>
<p>If a java solution is not possible, then a SQL or PL/SQL one might also be OK.</p>
<p>The first naïve approach I could think of would be something that</p>
<ol>
<li>creates some test tables with test data</li>
<li>mocks the view that needs to be tested, by replacing the source tables with the test ones</li>
<li>runs a &quot;select *&quot; from the view and compares it with the desired output</li>
<li>drops the test tables and the mocked view</li>
</ol>
<p>Is there any existing tool/library that does the above?
If not, is there any particular reason why the above approach would not work?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/65089635/unit-testing-oracle-views,"['java', 'sql', 'oracle', 'unit-testing', 'automated-tests']",283,False,1,0
Laravel Unit Testing - Controllers,"<p>I am quite new to Laravel and have been reading the documentation on testing, however I am not sure how I would go about Unit Testing the Controller I have posted below. Any advice on how I would go about this is much appreciated.
The controller below is the CRUD controller I created for Booking Forms. </p>

<pre><code>class BookingFormsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $bookingforms = BookingForm::orderBy('surgeryDate', 'asc')-&gt;paginate(5);
        return view('bookingforms.index')-&gt;with('bookingforms', $bookingforms);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('bookingforms.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $booking)
    {
      $this-&gt;validate($booking, [
      'requestID' =&gt; 'required',
      'patientID' =&gt; 'required',
      'patientForename' =&gt; 'required',
      'patientSurname'=&gt; 'required',
      'patientSex' =&gt; 'required',
      'patientDOB' =&gt; 'required',
      'surgeryType' =&gt; 'required',
      'surgeryDate' =&gt; 'required',
      'performingSurgeon' =&gt; 'required',
      'TheatreRoomID' =&gt; 'required',
      'patientUrgency' =&gt; 'required',
      'patientNotes' =&gt; 'required',
      'bloodGroup' =&gt; 'required'
      ]);

      // Create new Booking Form
      $bookingform = new Bookingform;
      $bookingform-&gt;requestID = $booking-&gt;input('requestID');
      $bookingform-&gt;bookingID = $booking-&gt;input('bookingID');
      $bookingform-&gt;patientID = $booking-&gt;input('patientID');
      $bookingform-&gt;patientForename = $booking-&gt;input('patientForename');
      $bookingform-&gt;patientSurname = $booking-&gt;input('patientSurname');
      $bookingform-&gt;patientSex = $booking-&gt;input('patientSex');
      $bookingform-&gt;patientDOB = $booking-&gt;input('patientDOB');
      $bookingform-&gt;surgeryType = $booking-&gt;input('surgeryType');
      $bookingform-&gt;surgeryDate = $booking-&gt;input('surgeryDate');
      $bookingform-&gt;performingSurgeon = $booking-&gt;input('performingSurgeon');
      $bookingform-&gt;TheatreRoomID = $booking-&gt;input('TheatreRoomID');
      $bookingform-&gt;patientUrgency = $booking-&gt;input('patientUrgency');
      $bookingform-&gt;patientNotes = $booking-&gt;input('patientNotes');
      $bookingform-&gt;bloodGroup = $booking-&gt;input('bloodGroup');
      $bookingform-&gt;user_id = auth()-&gt;user()-&gt;id;

      //Save Booking form

      $bookingform-&gt;save();

      //redirect
      return redirect('/bookingforms')-&gt;with('success', 'Booking Submitted');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($bookingID)
    {
        $bookingform = BookingForm::find($bookingID);
        return view('bookingforms.show')-&gt;with('bookingform', $bookingform);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($bookingID)
    {
        $bookingform = BookingForm::find($bookingID);
        //check for correct user_id
        if(auth()-&gt;user()-&gt;id !==$bookingform-&gt;user_id){
            return redirect('/bookingforms')-&gt;with('danger', 'This is not your booking, please contact the Booker.');
        }
        return view('bookingforms.edit')-&gt;with('bookingform', $bookingform);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $booking, $bookingID)
    {
      $this-&gt;validate($booking, [
      'patientID' =&gt; 'required',
      'patientForename' =&gt; 'required',
      'patientSurname'=&gt; 'required',
      'patientSex' =&gt; 'required',
      'patientDOB' =&gt; 'required',
      'surgeryType' =&gt; 'required',
      'surgeryDate' =&gt; 'required',
      'performingSurgeon' =&gt; 'required',
      'TheatreRoomID' =&gt; 'required',
      'patientUrgency' =&gt; 'required',
      'patientNotes' =&gt; 'required',
      'bloodGroup' =&gt; 'required'
      ]);

      // Create new Booking Form
      $bookingform = Bookingform::find($bookingID);
      $bookingform-&gt;bookingID = $booking-&gt;input('bookingID');
      $bookingform-&gt;patientID = $booking-&gt;input('patientID');
      $bookingform-&gt;patientForename = $booking-&gt;input('patientForename');
      $bookingform-&gt;patientSurname = $booking-&gt;input('patientSurname');
      $bookingform-&gt;patientSex = $booking-&gt;input('patientSex');
      $bookingform-&gt;patientDOB = $booking-&gt;input('patientDOB');
      $bookingform-&gt;surgeryType = $booking-&gt;input('surgeryType');
      $bookingform-&gt;surgeryDate = $booking-&gt;input('surgeryDate');
      $bookingform-&gt;performingSurgeon = $booking-&gt;input('performingSurgeon');
      $bookingform-&gt;TheatreRoomID = $booking-&gt;input('TheatreRoomID');
      $bookingform-&gt;patientUrgency = $booking-&gt;input('patientUrgency');
      $bookingform-&gt;patientNotes = $booking-&gt;input('patientNotes');
      $bookingform-&gt;bloodGroup = $booking-&gt;input('bloodGroup');
      $bookingform-&gt;user_id = auth()-&gt;user()-&gt;id;

      //Save Booking form

      $bookingform-&gt;save();

      //redirect
      return redirect('/bookingforms')-&gt;with('success', 'Booking Updated');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($bookingID)
    {
        $bookingform = Bookingform::find($bookingID);
        if(auth()-&gt;user()-&gt;id !==$bookingform-&gt;user_id){
            return redirect('/bookingforms')-&gt;with('danger', 'This is not your booking, please contact the Booker.');
        }
        $bookingform-&gt;delete();
        return redirect('/bookingforms')-&gt;with('success', 'Booking Removed');
    }
</code></pre>
",https://stackoverflow.com/questions/61480974/laravel-unit-testing-controllers,"['laravel', 'unit-testing', 'phpunit']",127,True,1,2
unit testing firebase HttpsFunctions,"<p>I am using firebase https function and am running unit tests on them. When calling the https function to be tested, the firebase documentation suggest to simply call it within my test file like this:</p>

<p><code>toBeTestesFunction()</code></p>

<p>This is my firebase https function:</p>

<p><code>export const toBeTestedFunction = https.onRequest(async (req, resp) =&gt; {
      bla bla bla
}</code></p>

<p>Now my problem is that onRequest takes a callback which in my case is asynchronous and needs to be awaited. However onRequest return the type HttpsFunction which is of type:</p>

<p><code>TriggerAnnotated &amp; ((req: Request, resp: Response) =&gt; void);</code></p>

<p>Since it does not return a promise I cannot await it. This makes the content in the function which has a callback that is asynchronous untestable. In the firebase documentation they give an exmaple which seems flawed (<a href=""https://firebase.google.com/docs/functions/unit-testing?authuser=0#test-background"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing?authuser=0#test-background</a>).</p>

<p>Any help is much appreciated
Thanks</p>
",https://stackoverflow.com/questions/60873541/unit-testing-firebase-httpsfunctions,"['firebase', 'unit-testing', 'google-cloud-functions']",68,False,1,0
Unit Testing using pytest,"<p>Define a pytest test method 'test_add_new_stock_as_dict', which adds the new stock {'iPhone Model X':50, 'Xiaomi Model Y': 2000, 'Nokia Model A':10} to the existing
inventory, and update the balance_inventory attribute. Also, check if the updated balance_inventory equals {'iPhone Model X':150, 'Xiaomi Model Y': 3000,
'Nokia Model Z':25, 'Nokia Model A':10}.</p>
<p>I wrote this code:</p>
<pre><code>def test_add_new_stock_as_dict(self):
    self.inventory({'iPhone Model X': 50, 'Xiaomi Model Y': 2000, 'Nokia Model A': 10})
    assert self.inventory.balance_inventory == {'iPhone Model X': 150, 'Xiaomi Model Y': 3000, 'Nokia Model Z': 25, 'Nokia Model A': 10}  
</code></pre>
<p>But I am getting an error:</p>
<pre><code>TypeError: 'MobileInventory' object is not callable
</code></pre>
<p>Where is my mistake, please suggest.</p>
",https://stackoverflow.com/questions/62699144/unit-testing-using-pytest,['python'],775,False,0,1
light inject - unit testing,"<p>I have an c# interface with multiple implementations &amp; each implementation is taking various dependencies object in its constructor.</p>
<p>In order to achieve DI using LightInjector on web api project, Im registering a 'Func' like below &amp; its working as expected but can't able to unit test it.</p>
<p>Any way I can write the below code in unit testable way?</p>
<pre><code> container.RegisterInstance&lt;Func&lt;IHandler, HandlerType, IHandler&gt;&gt;
        ((handler, type) =&gt;
        {
            IHandler context = null;
            switch (type)
            {
                case HandlerType.Type0:
                    context = new Type0(orderHandler, container.GetInstance&lt;IUtilityLogic&gt;());
                    break;
                case HandlerType.Type1:
                    context = new Type1(orderHandler, container.GetInstance&lt;IUtilityLogic&gt;(), container.GetInstance&lt;IShipmentLogic&gt;());
                    break;
                case HandlerType.Type2:
                    context = new Type2(orderHandler);
                    break;
                case HandlerType.Type3:
                    context = new Type3(orderHandler, container.GetInstance&lt;IUtilityLogic&gt;());
                    break;
                case HandlerType.Type4:
                    context = new Type4(orderHandler, container.GetInstance&lt;IUtilityLogic&gt;(), container.GetInstance&lt;IShipmentLogic&gt;(), container.GetInstance&lt;Func&lt;string, string, ICache&gt;&gt;());
                    break;
                default:
                    context = null;
                    break;
            }

            return context;
        });
</code></pre>
",https://stackoverflow.com/questions/64323299/light-inject-unit-testing,"['unit-testing', 'dependency-injection', 'asp.net-core-webapi', 'light-inject']",89,False,0,0
Unit Testing action hook,"<p>I want to perform unit tests on a Class, my goal is: I want to check if the plugin is activated or not by using the function: <code>is_plugin_active</code></p>

<pre><code>class WC_Custom_Variable_Products_Dependencies {
    public function __construct() {
          add_action( 'admin_init', [$this, 'check_environment']);
    }
    public function check_environment(){
          return is_plugin_active( 
                    'woocommerce-custom-variable-products/woocommerce-custom-variable-products.php' 
                 );
    }
}
</code></pre>

<p>CLass de test : </p>

<pre><code>require_once 'class-wc-custom-variable-products-dependencies.php';
class WC_Custom_Variable_Products_DependenciesTest extends WP_UnitTestCase {

    public function setUp() {
        parent::setUp();

        $this-&gt;class_instance = new WC_Custom_Variable_Products_Dependencies();
    }

    public function test_check_environment(){

        $result = $this-&gt;class_instance-&gt;check_environment();
        $this-&gt;assertTrue($result);
    }
</code></pre>

<p>The assertion return always False  .</p>

<p>My plugin is activated, and the function <code>is_plugin_active</code> returns True if I execute it from the browser: </p>

<pre><code>add_action('admin_init', function(){

     var_dump(is_plugin_active( 
                        'woocommerce-custom-variable-products/woocommerce-custom-variable-products.php' 
    ));
});
</code></pre>

<p>I think the <code>admin_init</code> hook is not executed in the test. is it true or not?</p>
",https://stackoverflow.com/questions/59674546/unit-testing-action-hook,"['wordpress', 'unit-testing', 'phpunit']",189,True,0,1
Unit Testing JMS payload,"<p>I have some code that looks like the following: </p>

<pre class=""lang-java prettyprint-override""><code>class MyClass {
    private JmsTemplate messageSender;

    public void doStuff(Domain object domainObject){
       ... //other stuff
       updateClient(domainObject);
    }
    ...
    private void updateClient(DomainObject domainObject){
        final String payload = buildMessageForObject(domainObject);
        messageSender.send(new MessageCreator() {
            public Message createMessage(Session sn) throws JMSException {
               return sn.createTextMessage(payload);
            }
        });
    }
}
</code></pre>

<p>My JMS template is autowired by the Spring framework. The logic for <code>buildMessageForObject</code> is actually inlined, but if it weren't it would be private. <strong>What I'd like to do is to make assertions against the message payload string.</strong> It would be nice if the Spring JMSTemplate API had something like <code>jmsTemplate.sendTextMessage(String text)</code> so that I could make verifications against the mocked <code>jmsTemplate</code> in my tests, but there seems to be too many layers of indirection between me and the message, and I can't see anything in the API for JMSTemplate or MessageCreator that obviously helps me restructure it to make it testable. I'm using JUnit and Mockito, but I don't know of any way that Mockito would allow me to specify the behaviour of the created <code>MessageCreator</code>.</p>

<p>Thanks in advance for any help.</p>
",https://stackoverflow.com/questions/61012548/unit-testing-jms-payload,"['java', 'testing', 'mockito', 'jms', 'spring-jms']",163,False,0,0
GAE Python Unit Testing,"<p>I have a python application that I am migrating from Python2.7 to Python 3.7. Since GAE is deprecating the appengine python module, I wanted to understand how the community is migrating the Unit Tests written using <code>testbed</code> module from appengine SDK. </p>
",https://stackoverflow.com/questions/61093797/gae-python-unit-testing,"['unit-testing', 'google-app-engine']",42,False,1,1
Unit testing in Nodejs,"<p>I have this simple hello world app, I want to write a test for it. I am new to Nodejs so want help in getting started</p>
<pre><code>const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) =&gt; {
  res.send('Hello World!')
})

app.listen(port, () =&gt; {
  console.log(`Example app listening at http://localhost:${port}`)
})
</code></pre>
",https://stackoverflow.com/questions/63554394/unit-testing-in-nodejs,"['node.js', 'unit-testing', 'npm']",33,False,0,2
Angular directive unit testing,"<p>I am having trouble with creating unit test for an Angular directive. The problem is that after setting inputEl.value and call input.dispatchEvent(new Event('input')) then fixture.detectChanges(), input value is deleted and will be an empty string (so all in all I am not even getting there to test the directive).</p>

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

<pre><code>@Component({
  template: `
  &lt;form [formGroup]=""formGroup""&gt;
    &lt;input formControlName=""datepicker""&gt;
  &lt;/form&gt;`
})
class TestComponent implements OnInit {
  formGroup!: FormGroup;

  constructor(private readonly formBuilder: FormBuilder) { }

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.formGroup = this.formBuilder.group({
      datepicker: ['']
    })
  }
}


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

it('should add 23:59:59 sec to the initial date', async () =&gt; {
    component.ngOnInit();
    fixture.detectChanges();

    const debugEl: HTMLElement = fixture.debugElement.nativeElement;
    const inputEl: HTMLInputElement | null = debugEl.querySelector('input');
    const value = 'test';

    if(inputEl) {
      inputEl.value = value;
      inputEl.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      expect(inputEl.value).toBe(value);
    }
});
</code></pre>

<p>Result:  Error: Expected '' to be 'test'.</p>

<p>What am I doing wrong here?</p>
",https://stackoverflow.com/questions/60094196/angular-directive-unit-testing,"['angular', 'unit-testing', 'karma-jasmine', 'angular-unit-test']",34,False,0,0
Sitecoe WebUtil.SessionValue Unit Testing,"<p>I am trying to unit test following code</p>

<pre><code>var test = WebUtil.GetSessionValue(""test"") as ViewResult;
</code></pre>

<p>And I have setup my test like this:</p>

<pre><code>var session = new Moq.Mock&lt;WebUtil&gt;();
session.SetUp(s =&gt; s.GetSessionValue).Returns();
</code></pre>

<p>I am having a hard time mocking WebUtil and set up value for GetSessionValue</p>
",https://stackoverflow.com/questions/60775734/sitecoe-webutil-sessionvalue-unit-testing,"['c#', 'asp.net', 'asp.net-core', 'sitecore']",145,True,0,1
Azure.Core.ResponseHeaders in unit testing,"<p>I'm trying to implement the new Azure.Storage v12 SDK and running into an issue with unit testing. Methods that call the Azure REST API return a <code>Azure.Response&lt;T&gt;</code> which contains the method <code>GetRawResponse()</code> to return an <code>Azure.Response</code>.</p>
<p>The implementation relies on using the headers found in <code>Azure.Response.Headers</code>, which is a struct of the type <a href=""https://learn.microsoft.com/en-us/dotnet/api/azure.core.responseheaders?view=azure-dotnet"" rel=""nofollow noreferrer"">Azure.Core.ResponseHeaders</a>. I can create an instance of it, but when iterating over it it throws a null reference exception.</p>
<pre class=""lang-cs prettyprint-override""><code>using Azure.Core;

var headers = new ResponseHeaders();
var headers.GetEnumerator(); //throws null reference error
</code></pre>
<p>As far as I can tell the object has no other constructors and when obtaining its members with reflection I also see no properties or fields it could iterate over.</p>
<p>Is it possible to create an instance that's capable iterating over or mocking it using Moq?</p>
",https://stackoverflow.com/questions/63017179/azure-core-responseheaders-in-unit-testing,"['c#', 'azure', 'azure-storage', 'moq']",308,True,0,1
Unit Testing - AssertionFailedError - Java,"<p>I'm having troubles understanding why this unit test is not working.
I'm creating two instances of @RegionWithActivities and I thought that it should pass the test.</p>
<pre><code>    @Test
    void testAreEqual()
    {
        RegionWithActivities regionWithActivities1 = new RegionWithActivities(4, regions);
        RegionWithActivities regionWithActivities2 = new RegionWithActivities(4, regions);

        assertEquals(regionWithActivities1, regionWithActivities2);
    }

</code></pre>
<p>The error is:</p>
<pre><code>org.opentest4j.AssertionFailedError: expected: com.luciaandres.analysis.RegionWithActivities@710726a3&lt;RegionWithActivities{numberOfActivities=4, regionIds=[4DA19B2B1328127FC062FB79F6F435A5, B66FA66DA650717E0964A4E30A716DAE, C841C0BED1CCDD643955065A696EED34, F2D04F76EA1EBD6C8E3AEDD506FBA35A]}&gt; but was: com.luciaandres.analysis.RegionWithActivities@646007f4&lt;RegionWithActivities{numberOfActivities=4, regionIds=[4DA19B2B1328127FC062FB79F6F435A5, B66FA66DA650717E0964A4E30A716DAE, C841C0BED1CCDD643955065A696EED34, F2D04F76EA1EBD6C8E3AEDD506FBA35A]}&gt;
Expected :RegionWithActivities{numberOfActivities=4, regionIds=[4DA19B2B1328127FC062FB79F6F435A5, B66FA66DA650717E0964A4E30A716DAE, C841C0BED1CCDD643955065A696EED34, F2D04F76EA1EBD6C8E3AEDD506FBA35A]}
Actual   :RegionWithActivities{numberOfActivities=4, regionIds=[4DA19B2B1328127FC062FB79F6F435A5, B66FA66DA650717E0964A4E30A716DAE, C841C0BED1CCDD643955065A696EED34, F2D04F76EA1EBD6C8E3AEDD506FBA35A]}


    at RegionWithActivitiesTest.testAreEqual(RegionWithActivitiesTest.java:29)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)

</code></pre>
<p>Could you please explain me?
Thanks!</p>
",https://stackoverflow.com/questions/63544406/unit-testing-assertionfailederror-java,"['java', 'unit-testing', 'junit']",1139,True,0,2
Unit testing a UITextField,"<p>I have a <code>UITextFieldDelegate</code> that performs some formatting as you type by implementing <code>textField(textField:shouldChangeCharactersIn:replacementString:) -&gt; Bool</code>. </p>

<p>I would like to write a few unit tests for this to check behaviour as key presses are sent, and as deletes are sent. Ideally, I'd do this by creating a <code>UITextField</code> in a test, attaching the delegate, and sending key events to it. I don't know how I should send key events to a <code>UITextField</code> programatically, though.</p>

<p>I understand I could unit test the delegate directly, but I want to test its interaction with the real <code>UITextField</code> implementation.</p>

<p>I would prefer to avoid UI tests if possible.</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/60113507/unit-testing-a-uitextfield,"['uitextfield', 'xctest', 'uitextfielddelegate']",124,False,0,0
unit testing Mail::send(),"<p>Say I'm sending an email with <code>\Illuminate\Support\Facades\Mail::send()</code>. How would I test this to see if an email had in fact been sent?</p>

<p><a href=""https://laravel.com/docs/5.8/mocking#mail-fake"" rel=""nofollow noreferrer"">https://laravel.com/docs/5.8/mocking#mail-fake</a> mentions <code>Mail::assertSent()</code> but that requires you a pass to it a <code>@param string $mailable</code> variable and idk what that variable would need to be with <code>Mail::send()</code>.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/59582713/unit-testing-mailsend,"['php', 'laravel', 'laravel-5']",56,False,0,1
unit testing with mock,"<p>I have to unit test a function (<code>SendMessageNetSkyToAgenceGrp</code>), and inside this function there is a service that I want to mock (<code>EnvoyerNotificationSms.SendMessageNetSky(signalRMessage)</code>):
Here is the code i want to test : </p>

<pre><code>public void SendMessageNetSkyToAgenceGrp(
            int agenceId,
            string message,
            string name,
            bool addAgenceLibInMsg = true,
            SignalRMessageThemeEnum theme = SignalRMessageThemeEnum.Information)
        {
            Agence agence = AgenceCoreService.GetAgenceById(agenceId);

            if (agence == null || (string.IsNullOrEmpty(agence.Libelle) &amp;&amp; addAgenceLibInMsg))
            {
                return;
            }

            string finalMessage = (message + (addAgenceLibInMsg ? agence.Libelle : """"));

            string groupName = string.Empty;

            if (theme == SignalRMessageThemeEnum.NotificationSms)
            {
                groupName = SignalRConstantes.GRP_SMSAGENCE + SignalRConstantes.SEPARATOR + agenceId;
            } 
            else
            {
                groupName = (SignalRConstantes.GRP_AGENCE + SignalRConstantes.SEPARATOR + agenceId);
            }

            SignalRMessage signalRMessage = new SignalRMessage(name, """", finalMessage, groupName, theme);

            EnvoyerNotificationSms.SendMessageNetSky(signalRMessage);
        } 
</code></pre>

<p>And here is the test code:</p>

<pre><code>[Fact(DisplayName = ""Vérifier l'appel à l'infra IEnvoyerNotificationSms"")]
        public void SendMessageNetSkyToAgenceGrp_CasNormal_ResultatOk()
        {
            // Arange            
            var envoyerNotificationSmMock = new Mock&lt;IEnvoyerNotificationSms&gt;();
            envoyerNotificationSmMock.Setup(envoyerNotifSms =&gt; envoyerNotifSms.SendMessageNetSky(It.IsAny&lt;SignalRMessage&gt;())).Verifiable();

            var SignalRCoreService = LocalIocManager.Resolve&lt;ISignalRCoreService&gt;();
            // Act 
            LocalIocManager.IocContainer.UseInstance(envoyerNotificationSmMock.Object, IfAlreadyRegistered.Replace);            
            SignalRCoreService.SendMessageNetSkyToAgenceGrp(56, ""testMessage"", ""name"", true, SignalRMessageThemeEnum.NotificationSms);

            // Assert
            envoyerNotificationSmMock.Verify(envoyerNotifSms =&gt; envoyerNotifSms.SendMessageNetSky(It.IsAny&lt;SignalRMessage&gt;()), Times.Once());
        }
</code></pre>

<p>But when I execute the test I get an error telling me that the service I want to mock is null (<code>EnvoyerNotificationSms.SendMessageNetSky(signalRMessage);</code>)
The error is : 'Object reference not set to an instance of an object.' in the line <code>EnvoyerNotificationSms.SendMessageNetSky(signalRMessage);</code> </p>

<p>How can I solve this issue?</p>
",https://stackoverflow.com/questions/62404195/unit-testing-with-mock,"['c#', 'unit-testing', 'mocking']",155,False,0,1
unit testing of subscribe,"<p>I have a component which has a get call on ngOninit</p>

<pre><code>ngOnInit(): void {
    this.setMemberRoles();
  }

  public setMemberRoles(): void {
    this.teamService.getMemberRoles().subscribe((response: ICreatedByRole) =&gt; {
      this.memberRoles = response;
    });
  }
</code></pre>

<p>I want to write test cases pf this:</p>

<pre><code>it('should set member roles in variable member roles', async(() =&gt; {
    let response: ICreatedByRole[] = [];

    spyOn(teamServiceStub, 'getMemberRoles').and.returnValue(of(response));
    component.setMemberRoles();
    fixture.detectChanges();
    expect(component.memberRoles).toEqual(response);
  }));
</code></pre>

<p>I have tried this, but it throws error </p>

<pre><code> &lt;spyOn&gt; : could not find an object to spy upon for getMemberRoles()
    Usage: spyOn(&lt;object&gt;, &lt;methodName&gt;)
</code></pre>

<p>Any idea?</p>
",https://stackoverflow.com/questions/62385936/unit-testing-of-subscribe,"['angular', 'unit-testing', 'jasmine']",20,True,0,1
Unit Testing Echo Function,"<p>To be more specific I am working on an assignment involving unit testing. These are the test cases I'm currently working on:</p>

<pre><code>#include ""c-echo.h""

#include ""gtest/gtest.h""

TEST(EchoTest, HelloWorld) {
    char* test_val[3]; test_val[0] = ""./c-echo""; test_val[1] = ""hello""; test_val[2] = ""world"";
    EXPECT_EQ(""hello world"", echo(3.test_val));
}

TEST(EchoTest, EmptyString) {
        char* test_val[1]; test_val[0] = ""./c-echo"";
        EXPECT_EQ("""", echo(1.test_val));
    }

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&amp;argc, argv);
  return RUN_ALL_TESTS();
}
</code></pre>

<p>c-echo.h program:</p>

<pre><code>#include &lt;iostream&gt;

std::string echo(int length, char** chars) {
    std::string ret = """";
    for(int i = 1; i &lt; length; i++) {
        ret += chars[i];
        if(i &lt; length - 1) {
            ret += "" "";
        }
    }
    return ret;
}
</code></pre>

<p>The assignment stated that I needed to include three additional test cases (edge cases in particular) for the echo function. However, I can't seem to think of any. I'm really new to this whole testing thing. </p>

<p>Thank You</p>
",https://stackoverflow.com/questions/60960191/unit-testing-echo-function,"['c++', 'unit-testing', 'echo']",266,False,0,0
Go Unit Testing - Boilerplate,"<p>Here is how my basic structure of Todo app looks like called 'main.go';</p>
<pre><code>package main

import (
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;log&quot;
    &quot;net/http&quot;
    &quot;github.com/gorilla/mux&quot;
)

//  Todo Struct (Model)
type Todo struct {
    Id        string `json:&quot;id&quot;`
    Task      string `json:&quot;task&quot;`
    Completed bool   `json:&quot;completed&quot;`
}

var todos []Todo

//  Get All Todos
func GetTodos(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
    json.NewEncoder(w).Encode(todos)
}

func main() {
    // Init Router
    r := mux.NewRouter()

    // Mock Data
    todos = append(todos, Todo{Id: &quot;1&quot;, Task: &quot;FirstTask&quot;, Completed: false})
    todos = append(todos, Todo{Id: &quot;2&quot;, Task: &quot;SecondTask&quot;, Completed: false})

    fmt.Println(&quot;Go dude dude go &quot;)

    r.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, &quot;Hello dudes&quot;)
    })

    r.HandleFunc(&quot;/api/todos&quot;, GetTodos).Methods(&quot;GET&quot;)

    log.Fatal(http.ListenAndServe(&quot;:8080&quot;, r))
}
</code></pre>
<p>And here is my 'main_test.go'</p>
<pre><code>package main

import (
    &quot;net/http&quot;
    &quot;net/http/httptest&quot;
    &quot;testing&quot;
)

func TestGetTodos(t *testing.T) {
    req, err := http.NewRequest(&quot;GET&quot;, &quot;/api/todos&quot;, nil)
    if err != nil {
        t.Fatal(err)
    }
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(GetTodos)
    handler.ServeHTTP(rr, req)
    if status := rr.Code; status != http.StatusOK {
        t.Errorf(&quot;handler returned wrong status code: got %v want %v&quot;,
            status, http.StatusOK)
    }

    // Check the response body is what we expect.
    expected := `[{Id: &quot;1&quot;, Task: &quot;FirstTask&quot;, Completed: false},{Id: &quot;2&quot;, Task: &quot;SecondTask&quot;, Completed: false}]`
    if rr.Body.String() != expected {
        t.Errorf(&quot;handler returned unexpected body: got %v want %v&quot;,
            rr.Body.String(), expected)
    }
}
</code></pre>
<p>Problem is in here that I keep getting the following error;</p>
<pre><code>--- FAIL: TestGetTodos (0.00s)
    main_test.go:25: handler returned unexpected body: got null
         want [{Id: &quot;1&quot;, Task: &quot;FirstTask&quot;, Completed: false},{Id: &quot;2&quot;, Task: &quot;SecondTask&quot;, Completed: false}]
FAIL
exit status 1
FAIL   ..filesPath/backend   0.213s 
</code></pre>
<p>I am definitely missing so simple but couldn't figure out.</p>
",https://stackoverflow.com/questions/63979318/go-unit-testing-boilerplate,"['unit-testing', 'go']",310,True,0,1
Xamarin.Mac - Unit Testing PdfKit,"<p>How can I run unit tests (<code>XUnit</code>, <code>NUnit</code>, <code>VSTest</code>) for a <code>Xamarin.Mac Project</code> in Visual Studio Mac?</p>
<p>I need to test code that uses <code>Foundation.PdfKit</code>.</p>
<p>I tried <code>NUnit3</code> test, but cannot create <code>NSUrl</code> for local file.</p>
<pre><code>new NSUrl(&quot;/home/xyz/Downloads/xyz.pdf&quot;, false);
</code></pre>
<p>throws an <code>ArgumentNullException</code>.</p>
",https://stackoverflow.com/questions/62934269/xamarin-mac-unit-testing-pdfkit,"['c#', 'nunit', 'xunit', 'visual-studio-mac', 'xamarin.mac']",99,False,0,0
Mediatr pattern unit testing,"<p>I'm trying to setup unit testing for my API controllers. I'm using the mediatr pattern and FakeIteasy.
I have the following code.</p>
<pre><code>public class ChannelGroupChannelsControllerTests
{
    private readonly ChannelGroupChannelsController _controller;
    private readonly IMediator _mediator;

    public ChannelGroupChannelsControllerTests()
    {
        var service = A.Fake&lt;IReadChannelGroupChannel&gt;();
        var mapper = A.Fake&lt;IMapper&gt;();

        var channelGroupChannel = new ChannelGroupChannel
        {
            Id = 1,
            ChannelGroupId = 1,
            ChannelId = 1,
            Channel = new Channel { Name = &quot;Channel Name&quot; }
        };

        _mediator = A.Fake&lt;IMediator&gt;();
        _controller = new ChannelGroupChannelsController(_mediator, mapper);

        A.CallTo(() =&gt; _mediator.Send(A&lt;GetChannelGroupChannelById&gt;._, A&lt;CancellationToken&gt;._)).Returns(channelGroupChannel);
    }


    [Fact]
    public async Task ChannelGroupChannelsController_ById()
    {
        var result = await _controller.ById(1);

        (result.Result as StatusCodeResult)?.StatusCode.Should().Be((int)HttpStatusCode.OK);
        result.Value.Should().BeOfType&lt;ChannelGroupChannelVM&gt;();
    }
}
</code></pre>
<p>Now the problem is that I keep getting NULL as a value.
I think the issue might be that GetChannelGroupChannelById has a constructor that expects the ID. But I'm not sure...</p>
<p>Does anybody know what could be wrong? I'm pretty new with the mocking stuff.</p>
<p>Kind regards</p>
",https://stackoverflow.com/questions/62712643/mediatr-pattern-unit-testing,"['c#', '.net-core-3.1', 'fakeiteasy', 'mediatr']",470,False,0,1
Unit Testing Method Arguments,"<p>I hope this is doable. I want to use <strong>Unit Testing</strong> to validate method parameters.
I want to ensure that zero is not passed through as an argument. </p>

<blockquote>
  <p>Code to Test    </p>
</blockquote>

<pre><code> public class TestParameter
 {
    public double divide(int dividend, int divisor)
    {
        double quotient = 0;

        if (divisor!=0)
        quotient= dividend / divisor;

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

<blockquote>
  <p>Unit Test</p>
</blockquote>

<pre><code>[TestClass]
public class UnitTestIntro
{
    [TestMethod]
    public void ZeroDivision()
    {
        TestParameter test = new TestParameter();
        double ans = test.divide(10, 0);
        //Assert.IsTrue();
        //I want to assert that divide does not allow 0 divisor as an argument
    }
}
</code></pre>
",https://stackoverflow.com/questions/60434731/unit-testing-method-arguments,"['c#', 'unit-testing']",2121,True,0,2
Unit testing HTTP Client,"<p>I have the following code using an HttpClient. I'm new to C# and would like to learn how to unit test my HttpClient but am not sure where to begin. Here is my code: </p>

<pre><code> protected override async Task PopulateData()
        {
            using (var client = new HttpClient())
            {
                var token = ""private token"";
                var requestUrl = api_url_here;
                var authenticatedRequestUrl = requestUrl + $""{token}"";
                var response = await client.GetAsync(authenticatedRequestUrl);
                var stringResult = await response.Content.ReadAsStringAsync();

                // do something
            }
        }
</code></pre>

<p>I've seen lots of different articles suggesting different ways to unit test but I am unsure as to how to use them properly. For example, I've seen this unit test pattern on many websites:</p>

<pre><code>  [Test]
        public async Task MockingHTTP()
        {
            var requestUri = new Uri("""");
            var expectedResponse = ""Response"";
            var mockHandler = new Mock&lt;HttpMessageHandler&gt;();

            mockHandler.Protected()
                .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(""SendAsync"", ItExpr.IsAny&lt;HttpRequestMessage&gt;(),
                ItExpr.IsAny&lt;CancellationToken&gt;())
                .ReturnsAsync(new HttpResponseMessage(Net.HttpStatusCode.OK));

            var httpClient = new HttpClient(mockHandler.Object);
            var result = await httpClient.GetStringAsync(requestUri).ConfigureAwait(false);
            Assert.AreEqual(expectedResponse, result);

            }
        }
</code></pre>

<p>However I don't know how to apply this approach to my code. Please can someone point my in the right direction in order to successfully unit test the HttpClient? </p>
",https://stackoverflow.com/questions/60005532/unit-testing-http-client,"['c#', 'unit-testing', 'http']",356,True,0,1
Unit testing error System.InvalidCastException:,"<p>I'm testing a method that calls a function from my repository and returns it as a list but I keep getting this error:</p>
<blockquote>
<p>System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.String[]'.</p>
</blockquote>
<p>I don't know what I'm missing. Here's the method:</p>
<pre><code>public IList&lt;TransactionStatus&gt; GetBookingStatuses(IList&lt;string&gt; uniqueTransactionRefs)
{
    TransactionStatus[] transactionStatuses = DBRepository.GetStatuses((string[])uniqueTransactionRefs);
    return transactionStatuses;
}
</code></pre>
<p>And this is the method <code>GetStatuses</code> in my repository:</p>
<pre><code>TransactionStatus[] GetStatuses(string[] uniqueTransactionRefs);
</code></pre>
",https://stackoverflow.com/questions/65168895/unit-testing-error-system-invalidcastexception,"['c#', 'unit-testing', 'asp.net-core']",426,True,-2,1
Unit testing console application,"<p>I am trying to test my very first console app and while trying to do so I came across the roadblock of not being able to test any negative scenarios.  Here's why - I've separated all user actions into individual methods, and those user actions are dictated by the result of an IF statement which either does or does not meet my conditions.  </p>

<p>I can simulate the console input for a positive condition which will then exit my code and complete my test.  But (and obviously so), when I try to test any false condition, the statement restarts and my test is failed with ""insufficient memory exception"".  What I've been trying to figure out is, is there any way to test my negative conditions?  </p>

<pre><code>public float UserInput2()
{
    // Ask the user to type the second number.
    Console.WriteLine(""Type another number, and then press Enter"");
    bool Valid2 = false;
    while (Valid2 == false)
    {
        string Input2 = Console.ReadLine();
        Console.WriteLine(Input2);
        if (!float.TryParse(Input2, out Number))
        {
            Console.WriteLine(""Not an integer, please try again."");
        }
        else
        {
            Valid2 = true;
            num2 = (float)Convert.ToDecimal(Input2);
        }
    }
    return num2;
}


[Test]
public void UserInput2Test()
{
    var calc = new CalculatorApp.Program();
    var output = new StringWriter();
    string expectedresult = (string.Format(""Type another number, and then press Enter\r\n5\r\n"", Environment.NewLine));
    Console.SetOut(output);
    var input = new StringReader(""f5"");
    Console.SetIn(input);
    var input2 = new StringReader(""5"");
    Console.SetIn(input2);

    calc.UserInput2();
    //num1 = (float)Convert.ToDecimal(output);

    Assert.That(output.ToString(), Is.EqualTo(expectedresult));

}
</code></pre>
",https://stackoverflow.com/questions/59615915/unit-testing-console-application,"['c#', 'unit-testing', 'console-application']",421,False,0,0
Kafka Topic Unit Testing,"<p>I'm creating topic in Kafka with the below method,</p>

<pre><code>public class  KafkaTopicAdmin {

  public void createTopic(final String topicName) {

        final AdminClient client = getKafkaClient();
        final List&lt;NewTopic&gt; topics = Collections.synchronizedList(new ArrayList&lt;&gt;());
        final NewTopic newTopic = new NewTopic(topicName, connectionConfig.getNoOfPartition(), (short) connectionConfig.getNoOfReplicas());
        topics.add(newTopic);
        client.createTopics(topics);

    }

private AdminClient getKafkaClient() {
        final Map&lt;String, Object&gt; configs = new ConcurrentHashMap&lt;&gt;();
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, ""bootstrap-ip"");
        return AdminClient.create(configs);
    }
}

</code></pre>

<p>and my test class is,</p>

<pre><code>@EmbeddedKafka
public class KafkaTopicAdminTest {

    private KafkaTopicAdmin kafkaTopicAdmin;
    private AdminClient kafkaAdminClient;

    @Before
    public void setUp(){

        kafkaTopicAdmin = new KafkaTopicAdmin();
        Properties properties = new Properties();
        properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,  StringUtils.arrayToCommaDelimitedString(new EmbeddedKafkaBroker(2).getBrokerAddresses()));
        kafkaAdminClient = KafkaAdminClient.create(properties);
    }

    @Test
    public void shouldCreateTopic() throws ExecutionException, InterruptedException {
        kafkaTopicAdmin.createTopic(""TestTopic"");
        ListTopicsOptions listTopicsOptions = new ListTopicsOptions();
        listTopicsOptions.listInternal(true);
        System.out.println(""topics:"" + kafkaAdminClient.listTopics(listTopicsOptions).names().get());
    }
}

</code></pre>

<p>I'm getting the below error,</p>

<pre><code>[AdminClient clientId=adminclient-1] Error connecting to node 127.0.0.1:0 (id: -2 rack: null)
java.net.BindException: Can't assign requested address
</code></pre>

<p>I use <code>@EmbeddedKafka</code> I just wanted to make sure the topic present in the list. Is this correct approach or any other suggestion please?</p>
",https://stackoverflow.com/questions/60454589/kafka-topic-unit-testing,"['unit-testing', 'apache-kafka', 'spring-kafka-test']",850,True,0,1
Unit Testing IO Scala,"<p>I'm starting unit testing in scala using scalatest.
the method I'm testing is as follows :</p>

<pre><code> def readAlpha: IO[Float] = IO {
    val alpha = scala.io.StdIn.readFloat()
    alpha
  }
</code></pre>

<p>The test consists of limiting the float that the user inserts to two decimals
Here is what I've tried but that doesn't seem to work.
How could I be fixing it </p>

<pre><code>  ""alpha"" should "" have two decimal numbers after comma"" in {
    val alpha = readAlpha
    //assert(alpha == (f""$alpha%.2f""))
  }
</code></pre>
",https://stackoverflow.com/questions/61253471/unit-testing-io-scala,"['scala', 'unit-testing', 'scalatest']",1017,True,0,1
Unit testing property modifier,"<p>I'm talking about Typescript but it could be a generic question...</p>
<p>How to test that a property is readonly?</p>
<p>I mean, it's a language feature so seems quite obvious that if I declare a property as readonly no one can reassign it as the code won't compile, but without any test, no one assure me that I can safely change the code, make the property writable and then modify it...
So how can I write a unit test that fails if the property is writable?</p>
",https://stackoverflow.com/questions/63960494/unit-testing-property-modifier,"['typescript', 'unit-testing', 'tdd']",81,True,0,2
unit testing GraphQL in Golang,"<p>in this case I am using</p>

<ul>
<li>Echo </li>
<li>mongo-driver (MongoDB)</li>
<li>gqlgen <a href=""https://github.com/99designs/gqlgen"" rel=""noreferrer"">graphql type safe</a></li>
</ul>

<p>is there any simple example for testing my Mutation and Query ? I do love to get advices for this. I have tried to find but can't found any so far, </p>

<p>thank you :)</p>
",https://stackoverflow.com/questions/62348857/unit-testing-graphql-in-golang,"['unit-testing', 'go', 'graphql', 'go-echo', 'gqlgen']",6010,True,6,1
Unit testing in Kotlin JS,"<p>I have a simple project in Kotlin JavaScript using React. I've added unit tests, but when I run them, they seem to call main method of production code, and fail on initialization, when trying to reach unexsistent DOM structure. Despite the fact that the tested class does not reference React or DOM in any way.</p>

<p>The error looks the same when run from Intelij IDEA or by <code>gradlew build</code> (I've replaced the full path to my project with /APP/ for clarity):</p>

<pre><code>Testing started at 17:51 ...
&gt; Task :cleanBrowserTest
&gt; Task :packageJson UP-TO-DATE
&gt; Task :testPackageJson UP-TO-DATE
&gt; Task :kotlinNodeJsSetup SKIPPED
&gt; Task :kotlinNpmInstall
&gt; Task :compileKotlinJs
&gt; Task :processResources
&gt; Task :mainClasses
&gt; Task :compileTestKotlinJs
&gt; Task :testProcessResources NO-SOURCE
&gt; Task :testClasses

&gt; Task :browserTest

(...)

Error: Target container is not a DOM element.

    at render (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:25359:13)

    at render_0 (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:29868:5)

    at main (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:146311:5)

    at Object.&lt;anonymous&gt; (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:146315:3)

    at http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:146289:37

    at Object.../example/kotlin/example.js (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:146292:2)

    at __webpack_require__ (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:20:30)

    at http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:146346:134

    at Object../kotlin/example-test.js (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:146351:2)

    at __webpack_require__ (http://localhost:9876/absoluteD:/APP/build/js/packages/example-test/adapter-browser.js?92ccabfdcfa982960828b65b2f4e2683080859b4:20:30)

HeadlessChrome 81.0.4044 (Windows 10.0.0) ERROR

  Uncaught Error: Target container is not a DOM element.

  at d:/APP/build/js/node_modules/react-dom/cjs/react-dom.development.js:24828:1 &lt;- D:/APP/build/js/packages/example-test/adapter-browser.js:25359:7

(...)


&gt; Task :browserTest FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':browserTest'.
&gt; command 'C:\Users\Arsen\.gradle\nodejs\node-v12.14.0-win-x64\node.exe' exited with errors (exit code: 1)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s
8 actionable tasks: 6 executed, 2 up-to-date
</code></pre>

<h1>Minimal example:</h1>

<p>./build.gradle.kts</p>

<pre><code>plugins {
    id(""org.jetbrains.kotlin.js"") version ""1.3.70-eap-184""
}

group = ""org.example""
version = ""1.0-SNAPSHOT""

repositories {
    maven { setUrl(""https://dl.bintray.com/kotlin/kotlin-eap"") }
    maven(""https://kotlin.bintray.com/kotlin-js-wrappers/"")
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin(""stdlib-js""))

    implementation(""org.jetbrains:kotlin-react:16.13.0-pre.94-kotlin-1.3.70"")
    implementation(""org.jetbrains:kotlin-react-dom:16.13.0-pre.94-kotlin-1.3.70"")
    implementation(npm(""react"", ""16.13.1""))
    implementation(npm(""react-dom"", ""16.13.1""))
    testImplementation(kotlin(""test-js""))
}

kotlin.target.browser {
}
</code></pre>

<p>./settings.gradle.kts</p>

<pre><code>pluginManagement {
    repositories {
        maven { setUrl(""https://dl.bintray.com/kotlin/kotlin-eap"") }

        mavenCentral()

        maven { setUrl(""https://plugins.gradle.org/m2/"") }
    }
}
rootProject.name = ""example""
</code></pre>

<p>./src/main/resources/index.html</p>

<pre><code>&lt;!doctype html&gt;
&lt;html lang=""en""&gt;
    &lt;head&gt;
        &lt;meta charset=""UTF-8""&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div id=""root""&gt;&lt;/div&gt;
        &lt;script src=""example.js""&gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>./src/main/kotlin/Main.kt</p>

<pre><code>import react.dom.*
import kotlin.browser.document

fun main(args: Array&lt;String&gt;) {
    render(document.getElementById(""root"")) {

    }
}
</code></pre>

<p>./src/main/kotlin/DummyClass.kt</p>

<pre><code>class DummyClass {
    fun foo(): String {
        return ""foo""
    }
}
</code></pre>

<p>./src/test/kotlin/ExampleTest.kt</p>

<pre><code>import kotlin.test.*

class ExampleTest {
    @Test
    fun foo() {
        assertEquals(DummyClass().foo(), ""foo"")
    }
}
</code></pre>

<p>The error does not occur if I don't reference production code at all (remove <code>DummyClass().foo()</code> from the test), or when main method does not call <code>render(document.getElementById(""root""))</code>.</p>

<p>PS: If it matters I run the code on Windows</p>
",https://stackoverflow.com/questions/61839800/unit-testing-in-kotlin-js,"['reactjs', 'unit-testing', 'kotlin-js']",1109,True,4,2
Python unit testing multiple inputs,"<p>This is a generic question geared towards unit testing specifically in Python. Is it acceptable to place 20 or some number of inputs to test in a dictionary as keys, where the values are the expected result output from the function?</p>

<p>I can't find an answer after scouring the internet. Almost everything I read were toy examples like adding numbers to obtain a sum or concatenating a first and last name. The following is another toyish example to describe my question in a simple way.</p>

<pre><code>import unittest
import some_module

class SomeModuleUnitTest(unittest.TestCase):

    def test_some_function(self):

        input_output_dict = {
            1: 1,
            2: 4,
            3: 9,
            4: 16,
            5: 25,
            6: 36,
            7: 49,
              .
              .
              .

            20: 400
        }

        for input_case, output_expected in input_output_dict.items():
            output_actual = some_module.some_function(input_case)
            self.assertEqual(output_expected, output_actual)
</code></pre>

<p>If this is considered archaic, what would be the Pythonic solution for testing multiple inputs?</p>
",https://stackoverflow.com/questions/61419269/python-unit-testing-multiple-inputs,"['python', 'unit-testing', 'python-unittest', 'multiple-input']",5939,True,4,1
Unit Testing for Providers in Flutter,"<p>We have started a new project on Flutter in the TDD approach. I am using providers for State Management.
While trying to write the Widget Testing we are facing the issue to test the providers.
Can you please suggest with an example to write the unit testing for providers and widget injects the provider.</p>
<p>I'm getting the following issue</p>
<pre><code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════
The following ProviderNotFoundException was thrown running a test:
Error: Could not find the correct Provider above this SplashScreen Widget

To fix, please:

Ensure the Provider is an ancestor to this SplashScreen Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Always use package imports. Ex: `import 'package:my_app/my_code.dart';
Ensure the correct context is being used.
</code></pre>
<p>══╡ Splash Screen Code╞════════════════════════════════════</p>
<pre class=""lang-dart prettyprint-override""><code>import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../routes.dart';
import '../../constants/constants.dart';
import '../../providers/provider.dart';
import '../../services/navigation_service.dart';
import '../../utils/utlis.dart';

class SplashScreen extends StatefulWidget {
  @override
  SplashScreenState createState() =&gt; SplashScreenState();
}

class SplashScreenState extends State {
  void startTime() {
    const _duration = Duration(seconds: Preferences.splashScreenTime);
    Timer(_duration, _getInitialData);
    _getInitialData();
  }

  dynamic _getInitialData() async {
    final TokenProvider tokenProvider =
    Provider.of(context, listen: false);

    await tokenProvider.setAccessToken();

    navigationPage();
  }

  void navigationPage() {
    NavigationService.pushReplacementNamedTo(Routes.home_screen);
  }

  @override
  void initState() {
    super.initState();
    startTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        key: const Key('splashScreen_body'),
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/flutter.png',
            key: const Key('splashScreen_image'),
          )
        ],
      ),
    );
  }
}
</code></pre>
<p>thank in advance</p>
",https://stackoverflow.com/questions/59735075/unit-testing-for-providers-in-flutter,"['flutter', 'flutter-dependencies', 'flutter-test', 'flutter-plugin', 'flutter-channel']",10501,True,12,2
Unit testing for GCP upload,"<p>I have the following method for which I need to write unit test, I am new to using pytest. I am uploading a file to a bucket on GCP using the google.cloud storage library in python.</p>

<pre class=""lang-py prettyprint-override""><code>def upload_to_gcs(topic, upload_file_name, upload_file_location, gcs_bucket_name, gcp_key_json):
    try:
        client = storage.Client.from_service_account_json(gcp_key_json)
        bucket = client.get_bucket(gcs_bucket_name)
        gcs_folder_loc = topic + '/' + upload_file_name
        bucket.blob(gcs_folder_loc).upload_from_filename(upload_file_location)
        _LOGGER.info(""File %s has been uploaded to folder %s"", upload_file_name, topic)
    except Exception as e:
        _LOGGER.exception(""Caught unexpected exception while uploading file to GCS %s"", e)
    finally:
        try:
            if os.path.isfile(upload_file_location):
                os.remove(upload_file_location)
        except OSError as e:
            _LOGGER.exception(""Error: %s - %s."" % (e.filename, e.strerror))
</code></pre>

<p>I have the following but I am not sure how to test the upload, Any help is appreciated - </p>

<pre class=""lang-py prettyprint-override""><code>def test_upload_to_gcs():
    mock_client = mock.create_autospec(storage.Client)
    mock_bucket = mock.create_autospec(storage.bucket.Bucket)
    mock_bucket.name = 'test_bucket'
    mock_client.get_bucket.return_value = mock_bucket
    mock_blob = mock.create_autospec(storage.blob.Blob)
    mock_blob.name = 'test_blob'
    mock_bucket.get_blob.return_value = mock_blob
</code></pre>
",https://stackoverflow.com/questions/62032662/unit-testing-for-gcp-upload,"['python', 'unit-testing', 'google-cloud-platform', 'mocking', 'pytest']",2085,False,4,0
AntD unit testing table render,"<p>How to unit test AntD Table render column?</p>
<p>Here's my code</p>
<pre><code>const columns = [
  {
    title: 'Evaluation Form',
    dataIndex: 'projectName',
    key: 'projectName',
    render: (text, record) =&gt; `${!_.isNil(text) ? text : '---'} - ${record.employeeName}`,
  },
]

&lt;Table
  columns={columns}
/&gt;
</code></pre>
<p>Here's the result from the test
<a href=""https://i.stack.imgur.com/MK7Kz.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/MK7Kz.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63904641/antd-unit-testing-table-render,"['unit-testing', 'jestjs', 'antd']",1103,False,3,1
Unit Testing hive abstraction layer,"<p>So I created a simpler level of abstraction to use Hive into my Flutter app. This should be the central point, where all hive boxes are administrated and accessed. Since e.g. <code>getApplicationDocumentsDirectory</code> is not available during testing, how can I still manage to test this whole file?</p>
<pre><code>import '../services/workout.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_rovider;

import 'workout.dart';

class HiveService {
  static final HiveService _singleton = HiveService._internal();

  static const String _workoutBox = &quot;workoutBox&quot;;

  factory HiveService() {
    return _singleton;
  }
  HiveService._internal();

  static Future&lt;void&gt; init() async {
    final appDocumentDirectory =
        await path_rovider.getApplicationDocumentsDirectory();
    Hive.init(appDocumentDirectory.path);
    Hive.registerAdapter(WorkoutAdapter());
  }

  static Future openWorkouts() {
    return Hive.openBox&lt;Workout&gt;(_workoutBox);
  }

  static Future close() {
    return Hive.close();
  }
  
}
</code></pre>
",https://stackoverflow.com/questions/61053727/unit-testing-hive-abstraction-layer,"['flutter', 'unit-testing', 'dart', 'flutter-hive']",1516,True,3,1
BigQuery unit testing using Python,"<p>I am trying to test a BigQuery class with a Mock object to represent the table. Instances of my <code>BigQueryRequest</code> class must provide the <code>BigQuery table uri</code>. Would it be possible for me to create a mock BigQuery table directly from Python? How would it possible?</p>
<pre><code>class BigQueryRequest:
    &quot;&quot;&quot;BigQueryRequest
    Contains a BigQuery request with its parameter.
    Receive a table uri ($project_id.$dataset.$table) to run query
    Args:
        uri (str): BigQuery table uri
    Properties:
        BigQueryRequest.project: return the project running BigQuery
        BigQueryRequest.dataset: return the dataset
        BigQueryRequest.table: return the table to query
        BigQueryRequest.destination_project: same as project but for destination project
        BigQueryRequest.destination_dataset: same as project but for destination dataset
        BigQueryRequest.destination_table: same as project but for destination table
    Methods:
        from_uri(): (@classmethod) parse a BigQuery uri to its project, dataset, table
        destination(): return a uri of the BigQuery request destination table
        query(): run the given BigQuery query
    Private methods:
        __set_destination(): generate a destination uri following the nomenclature or reuse entry uri
    &quot;&quot;&quot;

    def __init__(self, uri=&quot;&quot;, step=&quot;&quot;, params={}):
        self.project, self.dataset, self.table = self.from_uri(uri)
        self.step = step
        self.params = self.set_params(params)
        self.overwrite = False
        (
            self.destination_project,
            self.destination_dataset,
            self.destination_table,
        ) = self.__set_destination()
</code></pre>
",https://stackoverflow.com/questions/64664074/bigquery-unit-testing-using-python,"['python', 'google-cloud-platform']",5013,True,4,2
Unit Testing Coroutine Channel return,"<p>I'm doing a polling every few seconds and returns a Channel with a Result. My problem is how to test it.</p>

<p>Here is my viewmodel code:</p>

<pre><code>@ExperimentalCoroutinesApi
fun fetchInfo() {
    viewModelScope.launch {
        channel = fetchInfoUseCase(""1"")
        channel.consumeEach {
            viewAction.postValue(ViewAction.UPDATE)
        }
    }
}
</code></pre>

<p>My unit test code:</p>

<pre><code>@ExperimentalCoroutinesApi
class MyViewModelTest {
    @get:Rule
    val instantTask = InstantTaskExecutorRule()

    @get:Rule
    val coroutinesTestRule = CoroutinesTestRule()

    private val fetchInfo = mockk&lt;FetchInfoUseCase&gt;()

    private val channel = Channel&lt;Result&lt;MyModel, MyError&gt;&gt;()

    private val viewModel = MyViewModel(fetchInfo)

    @Test
    fun dispatchFunction_viewActionUpdate() {
        prepareScenario()
        viewModel.fetchInfo()
        coVerify(exactly = 1) { fetchInfo(any()) }

        assertEquals(
            viewModel.viewAction.value,
            ViewAction.UPDATE
        )
    }

    private fun prepareScenario() {
        coEvery { fetchInfo(any()) } returns channel
    }
}
</code></pre>

<p>My in my test, <em>viewModel.viewAction.value</em> is always null. 
How can I validate that the viewAction is being called and the value is <em>ViewAction.UPDATE</em>?</p>
",https://stackoverflow.com/questions/61469059/unit-testing-coroutine-channel-return,"['android', 'unit-testing', 'coroutine', 'kotlin-coroutines']",539,False,3,0
UserDefaults instance for unit testing?,"<p>I have a class which I want to test. It uses UserDefaults in its logic.
I know I have to inject a test double to test it, but I want to make it without too much effort.</p>
<p>If it's possible to make a temporary UserDefaults instance which is only valid during the unit testing, that will be the best. Or do I have to write a wrapper for mocking eventually?</p>
",https://stackoverflow.com/questions/65191363/userdefaults-instance-for-unit-testing,"['swift', 'unit-testing', 'nsuserdefaults', 'userdefaults']",796,True,3,1
Unit Testing UI-related functions,"<p>I'm trying to get unit-testing concept and get lost with testing UI-related functions, like this:</p>

<pre><code>const hideElem = elem =&gt; {
  elem.classList.add('js-hidden')
}
</code></pre>

<p>or this:</p>

<pre><code>const getInputValue = (inputElem) =&gt; {
  let inputEl = document.querySelector(inputElem)

  return inputEl.value
}
</code></pre>

<p>or this:</p>

<pre><code>const cleanInput = input =&gt; {
  const inputEl = document.querySelector(input)
  inputEl.value = ''
}
</code></pre>

<p>Do I need to cover such functions with unit tests in Jest? If yes - could you please explain how to combine here Jest and DOM-related things? </p>
",https://stackoverflow.com/questions/62455692/unit-testing-ui-related-functions,"['javascript', 'unit-testing', 'testing', 'jestjs']",90,True,2,1
component unit testing in Glimmer,"<p>For classic component unit tests, how would we migrate this to Glimmer? This component unit test is testing a local prop that is not exposed to the user.</p>
<pre><code>const component = this.owner
  .factoryFor('component:some-component')
  .create({
    someModel: { foo: 'bar' }
  });

assert.equal(component.get('someLocalProp'), false);
</code></pre>
",https://stackoverflow.com/questions/63307259/component-unit-testing-in-glimmer,"['unit-testing', 'ember.js', 'integration-testing', 'glimmer.js']",398,True,2,1
Spring boot unit testing suggestion.?,"<p>I have a controller class and a service class.
Controller has endpoints and service layer has functions performing something specific (inserting, loading a file and counting lines, updating, etc).</p>

<p>Now what I want to know is, should I unit test an endpoint(controllers) as a whole or individual functions present in the service layer? I've really been confused. Please help. </p>
",https://stackoverflow.com/questions/60675443/spring-boot-unit-testing-suggestion,"['java', 'spring-boot', 'junit']",59,True,2,2
Unit testing apache beam job,"<p>I have a very simple dataflow job and I want to write unit tests. Sadly, there are no good examples what is the best way approach.</p>

<p>Here is the code </p>

<pre class=""lang-py prettyprint-override""><code>import logging
from datetime import datetime
from re import sub

import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import GoogleCloudOptions
from beam_nuggets.io import relational_db


class BeamOptions(PipelineOptions):
    @classmethod
    def _add_argparse_args(cls, parser):
        parser.add_argument(
            ""--bigquery_input_table"",
            help=""A table from BigQuery to process"",
            default=""bigquery_input_table_empty"",
        )
        parser.add_argument(
            ""--bigquery_project"", help=""Project with BigQuery data"", default=""foo""
        )
        parser.add_argument(
            ""--bigquery_dataset"", help=""Dataset from BigQuery"", default=""bar""
        )
        parser.add_argument(
            ""--bucket"", help=""GCS Bucket for temporary files"", default=""model-foo-dev""
        )
        parser.add_argument(""--db_password"", help=""Password for profiles DB"", default=""postgres"")
        parser.add_argument(""--db_host"", help=""host for profiles DB"", default=""localhost"")
        parser.add_argument(""--db_port"", help=""port for profiles DB"", default=5432)


class BeamFeed:
    def __init__(self):
        logging.info(""fetching BeamOptions"")
        self.pipe_opt = BeamOptions()
        all_options = self.pipe_opt.get_all_options()
        self.bigquery_input_table = all_options[""bigquery_input_table""]
        self.bigquery_project = all_options[""bigquery_project""]
        self.bigquery_dataset = all_options[""bigquery_dataset""]

        self.google_cloud_options = self.pipe_opt.view_as(GoogleCloudOptions)
        self.google_cloud_options.job_name = ""model-foo-data-preparation-"" + sub(
            r""[^0-9]"", ""-"", str(datetime.now().isoformat())
        )
        self.google_cloud_options.staging_location = ""gs://"" + all_options[""bucket""] + ""/staging""
        self.google_cloud_options.temp_location = ""gs://"" + all_options[""bucket""] + ""/temp""
        self.pg_config = relational_db.SourceConfiguration(
            drivername=""postgresql+pg8000"",
            host=all_options[""db_host""],
            port=all_options[""db_port""],
            username=""postgres"",
            database=""postgres"",
            password=all_options[""db_password""],
        )
        self.table_config = relational_db.TableConfiguration(
            name=""users"", primary_key_columns=[""id""]
        )

    def run(self, pipeline):
        """"""runs whole beam job pipeline""""""
        users_bq = beam.io.BigQuerySource(
            dataset=self.bigquery_dataset,
            project=self.bigquery_project,
            table=self.bigquery_input_table,
            validate=True,
        )

        users_info = (
            pipeline
            | ""read_users"" &gt;&gt; beam.io.Read(users_bq)
            | ""map_by_user_id"" &gt;&gt; beam.Map(lambda usr: {""id"": usr[""id""], ""value"": usr})
        )

        users_info | ""Writing to DB table"" &gt;&gt; relational_db.Write(
            source_config=self.pg_config, table_config=self.table_config
        )


if __name__ == ""__main__"":
    logging.getLogger().setLevel(logging.INFO)
    logging.info(""starting BeamFeed process"")
    beam_job = BeamFeed()
    with beam.Pipeline(options=beam_job.pipe_opt) as pipeline:
        beam_job.run(pipeline)


</code></pre>

<p>And the UT attempt</p>

<pre><code>import pytest

import apache_beam
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that, equal_to
from apache_beam.transforms import Create, FlatMap
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.runners.direct.direct_runner import DirectRunner

from bla import beam, BeamFeed, BeamOptions



@pytest.fixture
def bg_mock(mocker):
    # apache_beam.Create(
    #     [{""id"": ""8d73fda0-00b8-4084-bb8a-eea0f5bca46a"", ""foo"": 1}]
    # )
    return mocker.patch(""apache_beam.io.BigQuerySource"")


def test_empty_profile_generation(bg_mock):
    pipeline = TestPipeline(runner=DirectRunner())
    beam_job = BeamFeed()
    beam_job.run(pipeline)
    pipeline.run()

</code></pre>

<p>I'm not sure what is the best approach to testing Dataflow jobs. Just integrations testing and no mocks? With given mock pytest fails <code>[1]    16845 abort</code> </p>
",https://stackoverflow.com/questions/59566683/unit-testing-apache-beam-job,"['python', 'google-cloud-dataflow', 'apache-beam']",2586,True,2,1
Unit testing Zsh completion script,"<p>I'm trying to write a completion script for Zsh. I'd like to unit test the completion script. For example, I'd like to test that completions for <code>my-command --h</code> include <code>--help</code>.</p>
<p>For Fish, I can use <a href=""https://fishshell.com/docs/current/cmds/complete.html"" rel=""nofollow noreferrer""><code>complete -C 'my-command --h'</code></a>, which would then output <code>--help</code> and any other valid completions.</p>
<p>I can't seem to find an equivalent command for Zsh. Does one exist? I've tried things like <code>_main_complete</code>, <code>_complete</code> and <code>_normal</code>, but either they don't support this or I'm not invoking them in the correct way (I get a lot of <code>can only be called from completion function</code> errors).</p>
",https://stackoverflow.com/questions/65386043/unit-testing-zsh-completion-script,['zsh'],407,True,2,1
Python unit testing flask_restful - RequestParser,"<p>I'm writing an API in Python and I'm using <a href=""https://flask-restful.readthedocs.io/en/latest/"" rel=""nofollow noreferrer"">Flask-RESTFul</a>. I have a <strong>Login</strong> method which receives <strong>Email</strong> and <strong>Password</strong> as request parameters, both are required:</p>

<pre><code>class Login(Resource):

    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('email', required=True)
        self.parser.add_argument('password', required=True)
</code></pre>

<p>The code works just fine. If I try a request via Postman without request parameters, Flask-RESTFul sends a response error that Email and Password are required fields.</p>

<p>Now I want to write a unit test for this. The test should actually be pretty simple:</p>

<pre><code>@mock.patch('flask_restful.reqparse.RequestParser.parse_args')
class TestLoginMethods(unittest.TestCase):

    def test_post_body_missing(self, parse_args):
        self.login = Login()
        self.login.post()
        # TODO: should assert error when Email and Password not found in request

</code></pre>

<p>The problem here is, that <code>parse_args</code> gets mocked and the functionality of Flask-RESTFul of raising error for the required fields is gone. <strong>That means, no error is returned if Email and Password have not been provided</strong>. How do I stub this functionality of <code>RequestParser</code>? I'm new in python, I could find only examples without Flask-RESTFul.</p>
",https://stackoverflow.com/questions/60496102/python-unit-testing-flask-restful-requestparser,"['python', 'flask', 'flask-restful']",783,False,2,1
Unit testing WKNavigationDelegate functions swift,"<p>I have a <code>UIViewController</code> that implements some <code>WKNavigationDelegate</code> 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 != &quot;https://my-approved-url&quot; {
        decisionHandler(.cancel)
        return
    }
    decisionHandler(.allow)
}
</code></pre>
<p>I'd like my unit test to make sure <code>decisionHandler</code> is called with the right <code>WKNavigationActionPolicy</code> based on the <code>request.url</code> of the <code>WKNavigationAction</code>.</p>
<p>I can't figure out how to test this function, however. Calling <code>.load()</code> 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 <code>WKNavigationAction</code> of my own (.request is read-only).</p>
<p>What is the right way to unit test logic in <code>WKNavigationDelegate</code> functions?</p>
",https://stackoverflow.com/questions/63826838/unit-testing-wknavigationdelegate-functions-swift,"['swift', 'webkit', 'wkwebview', 'wknavigationdelegate']",889,True,2,1
Unit Testing ICommand and Methods,"<p>I have developed an WPF application using MVVM as a architecture and am writing some unit tests as part of this. In my view I have a button that is bound to a property in the ViewModel which can be seen below. </p>

<p><strong>ViewModel</strong></p>

<pre><code>public ICommand MoreInfoCommand
{
    get
    {
        if (_moreInfoCommand == null) 
        {
             _moreInfoCommand = new RelayCommand(parameter =&gt; OpenLink());
        }
        return _moreInfoCommand;
    }
}

private void OpenLink() 
{
    try 
    {
         Process.Start(""https://www.google.com/"");
    }
    catch
    {
      // catch error...
    }
}
</code></pre>

<p>In my unit testing I have created the following unit test:</p>

<p><strong>UnitTest</strong></p>

<pre><code>[Description(""Test MoreInfoCommand"")]
[TestMethod]
public void TestMoreInfoCommand() 
{
     viewModel vm = new viewModel();
     Assert.IsTrue(vm.MoreInfoCommand.CanExecute(null));
}
</code></pre>

<p>Currently this tests the the property to see if when the button is clicked in the UI the relevant method can be executed. This passes as the conditions are met, however its my understanding I need to test the functionality as well. With this in mind how do I, for example tests that the correct functionality occurs when the button is clicked. I.e how to test what occurs when the ICommand MoreInfoCommand is executed as a result of button click in the UI. </p>

<p>I know private methods can be tested directly, but should in my unit testing I be checking the functionality as well and if so, how can I do this. </p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/62022588/unit-testing-icommand-and-methods,"['c#', 'wpf', 'unit-testing', 'mvvm', 'icommand']",1223,True,1,2
Unit Testing A @verified_email_required View,"<p>Im trying to unit test one of my views that is decorated with @verified_email_required. I am unable to find out how to set the user as having their email verified so that it will allow them to view the page and assert that it uses the correct template (creating a superuser doesnt help).</p>

<p>This is the error im getting</p>

<pre><code>AssertionError: False is not true : Template 'enrolment/index.html' was not a template used to render the response. Actual template(s) used: account/verified_email_required.html, account/base.html, base.html
</code></pre>

<p>And this is my test</p>

<pre><code>def test_verified_user_uses_correct_template(self):
    user = User.objects.create_superuser('username')
    self.client.force_login(user)
    response = self.client.get('/enrolment/')
    self.assertTemplateUsed(response, 'enrolment/index.html')
</code></pre>

<p>Thank you.</p>
",https://stackoverflow.com/questions/61789695/unit-testing-a-verified-email-required-view,"['django', 'selenium', 'testing', 'tdd']",201,True,1,1
JEST: Unit testing Javascript/Jquery,"<p>Hi I wanted to unit test my javascript code using Jest and the click function inside it.</p>

<p>swipe.js</p>

<pre><code>export default class swipe {
  constructor() {
    this.init();
  }

  init() {
    this.postRender();
  }

  postRender() {
    const jqry = jQuery.noConflict();
    (function (jqry) {
      jqry(document).ready(() =&gt; {
        jqry('#buttonID').on('click', () =&gt; {
          jqry('#navigation').addClass('blue');
        });
      });
    })(jqry);
  }
}
</code></pre>
",https://stackoverflow.com/questions/60190274/jest-unit-testing-javascript-jquery,"['javascript', 'jquery', 'unit-testing', 'jestjs']",3910,True,1,1
React unit testing anonymous function,"<p>I am trying to test an onChange anonymous function, which changes a value in my textbox. I want to verify that if the function inside onChange gets called, the state is changed. The function itself is simple:</p>

<pre><code>onChange={(e) =&gt; this.setState({someState: e.value})}
</code></pre>

<p>If the function had a name, I would do something like the following:</p>

<pre><code>         test('myFunction should change someState value', () =&gt; {

                 const wrapper = shallow(&lt;MyComponent/&gt;);
                 const instance = wrapper.instance();

                const mockEvent = {
                    target:{
                        value: ""some value in textbox""
                     }        
                   };

                const expectedValue = ""some value in textbox"";

                instance.myFunction(mockEvent);
                expect(wrapper.state().someState).toEqual(expectedValue)

              }); 
</code></pre>

<p>Since the function is anonymous, I don't know how to call it with instance. I'd prefer not to give the function a name because i don't want the testing to affect my code. What would be a good solution?</p>
",https://stackoverflow.com/questions/61597604/react-unit-testing-anonymous-function,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",1061,True,2,1
Jenkins Pipeline - Laravel Unit Testing,"<p>I have started my laravel project, i'm trying to unit test my code and test db connectivity with jankins, this is my <strong>Jenkinsfile</strong> and how i configured it:</p>

<pre><code>pipeline {
    agent {
        dockerfile true
    }
    stages {
        stage(""Build"") {
            steps {
                sh 'php --version'
                sh 'composer install'
                sh 'composer --version'
                sh 'cp .env.example .env'
                sh 'php artisan key:generate'
            }
        }
        stage(""Unit test"") {
            steps {
                script {
                    docker.image('mysql:5.7').withRun('-e ""MYSQL_DATABASE=testing"" -e ""MYSQL_ROOT_PASSWORD=root""') { c -&gt;
                        docker.image('mysql:5').inside(""--link ${c.id}:db"") {
                            /* Wait until mysql service is up */
                            sh 'while ! mysqladmin ping -hdb --silent; do sleep 1; done'
                        }
                        sh ""./vendor/bin/phpunit""
                    }
                }
            }
        }
    }
}
</code></pre>

<p>The unit testing stage get error all the time and does not complete, why please ??</p>

<p><strong>All project configured by Docker.</strong></p>
",https://stackoverflow.com/questions/61467365/jenkins-pipeline-laravel-unit-testing,"['laravel', 'docker', 'jenkins', 'jenkins-pipeline', 'dockerfile']",2314,False,1,1
Unit Testing Jest Node Fetch,"<p>I'm trying to test a class method's return value.</p>
<p>This class method fetches from an API.</p>
<p>When testing I decide to mock the fetch request so I don't hit the network.</p>
<p>How would I go about doing this?? Preferably without an external library.</p>
<p><strong>ClassA</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>class ClassA {
    constructor() {
    }

    fetchSpotDate(pair) {
        const url = 'url';
        const query = 'query';
        fetch(url + query)
            .then(response =&gt; response.json())
            .then(json =&gt; new Date(json.settlement_date + ""Z""))
            .catch(e =&gt; {
                log.error(e)
            });
    }
}</code></pre>
</div>
</div>
</p>
<p><strong>Test</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>it('should return correct date object format',  async () =&gt; {
        const mockSuccessResponse = {
          foo: 'bar', 
          settlement_date: '2020-06-29T00:00:00' 
        };
        const mockJsonPromise = Promise.resolve(mockSuccessResponse);
        const mockFetchPromise = Promise.resolve({json: () =&gt; mockJsonPromise})
        const expectedReturn = new Date(""2020-06-29T00:00:00Z"")
        global.fetch = jest.fn(() =&gt; mockFetchPromise);
        const classA = new ClassA();

        const result = await classA.fetchSpotDate('EURUSD')
        expect(???result Promise value???).toEqual(expectedReturn)
    });</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/62581826/unit-testing-jest-node-fetch,"['node.js', 'jestjs', 'fetch']",296,False,1,0
Unit testing GraphQL&#39;s DataFetchingEnvironment issue,"<p>I have a query that takes  <code>classA</code> or <code>ClassB</code> parameter and gets information from the graph and returns to user based on <code>id</code> of <code>classA</code> or <code>classB</code>.</p>
<pre class=""lang-java prettyprint-override""><code>public StudentSize get(final DataFetchingEnvironment dataFetchingEnvironment) {
  StudentSize ss = new StudentSize();
  final String classA = dataFetchingEnvironment.getArgument(&quot;classA&quot;);
  final String classB = dataFetchingEnvironment.getArgument(&quot;ClassB&quot;);
  if (classA is not empty) {
    ss = graphQLrepo.StudentSizefromClassA(classA);
  }else {
    ss = graphQLrepo.StudentSizefromClassB(classB);
  }
  return ss;
}
</code></pre>
<p>Now this working fine as it should. But when it comes to unit test cases it is failing. When I run <code>test1</code> it is passing
<code>test1</code> method:</p>
<pre class=""lang-java prettyprint-override""><code>DataFetchingEnvironment  env = getDFenv();
String classAvalue = &quot;58&quot;;
when(graphQLrepo.StudentSizefromClassA(classAvalue)).thenReturn(studentoutput);
StudentSize result = ssDataFetcher.get(env);
assertEquals(expectedResult, result);
</code></pre>
<p>but when I create another test <code>test2</code> method to cover else statement it is failing and is resulting in null rather than giving the expected output
test2 method:</p>
<pre class=""lang-java prettyprint-override""><code>DataFetchingEnvironment env = getDFenv();
String classBvalue = &quot;58&quot;;
when(graphQLrepo.StudentSizefromClassB(classBvalue)).thenReturn(studentoutput);
StudentSize result = ssDataFetcher.get(env);
assertEquals(expectedResult, result);
</code></pre>
<p>I checked and found out, in <code>test1</code> and <code>test2</code> both it is passing the same arguement for both <code>classA</code> value and <code>classB</code> value. So, it is passing the if statement and unable to return the desired output</p>
<pre class=""lang-java prettyprint-override""><code> private DataFetchingEnvironment getDFenv() {
        return new DataFetchingEnvironment() {
...
   @Override
   public &lt;T&gt; T getArgument(String s) {
        return (T) &quot;58&quot;;

            }
   &quot;Everything else inside this is returning null&quot;

...
</code></pre>
<p>I do not know where I went wrong and I'm trying to figure out how to pass only the required value in the test or a way to fail the condition check in if statement during test run. Any help will be greatly appreciated.</p>
",https://stackoverflow.com/questions/62113179/unit-testing-graphqls-datafetchingenvironment-issue,"['java', 'spring-boot', 'neo4j', 'graphql', 'mockito']",1656,False,1,0
Unit testing PHAsset and permissions,"<p>I'm developing a framework, and I would like to unit test the part of the framework that helps fetching assets from the camera roll.</p>

<p>I've added the permissions to the test module <code>Info.plist</code> , but I can't get the permission granted to access the camera roll when I run the test. Should I use UI Test Case instead ? </p>

<p>How can you test multimedia functionalities on PHAssets or AVAssets ? </p>
",https://stackoverflow.com/questions/62155026/unit-testing-phasset-and-permissions,"['ios', 'unit-testing', 'phasset', 'photosframework']",318,False,1,0
Unit Testing Spring Stream Kafka,"<p>I am trying to unit test kafka usage with spring boot but having trouble with the input channel. Below is and extract of what I am doing.</p>

<pre><code>public interface MyCustomStreamBinding{
   @Input
   SubscribableChannel consumeChannel();

   @Output
   MessageChannel produceChannel();
}

@EnableBinding(value = { Source.class, MyCustomStreamBinding.class })
public class StreamConfiguration {
...
}

@Service
public class MyService {

  private final MyCustomStreamBinding streamBinding;
  public MyService(MyCustomStreamBinding streamBinding) {
    this.streamBinding = streamBinding;
  }

  public void sendMessage() {
    streamBinding.produceChannel().send(new SomeObject);
  }

  @StreamListener(""consumeChannel"")
  public void consumeChannel(SomeObject payload){
    // do processing of payload
  }
}
</code></pre>

<p>Then in my test cases I have</p>

<pre><code>@SpringBootTest(classes = {MyApp.class})
class MyServiceTest {
  private MyService myService;

  @Autowired
  private MyCustomStreamBinding streamBinding;
  @Autowired
  private MessageCollector messageCollector;

  @BeforeEach
  public void setup(){
    myService = new MyService(streamBinding);
  }

  @Test
  public void TestMessaging(){
   myService.sendMessage();

   Message&lt;?&gt; m = messageCollector.forChannel(streamBinding.produceChannel()).poll();
   assertThat(m.getPayload(), equalTo(new SomeObject()));
  }
}
</code></pre>

<p>How do I test the consumeChannel and that it actually performed the processing as expected?</p>
",https://stackoverflow.com/questions/60876315/unit-testing-spring-stream-kafka,"['spring', 'spring-boot', 'junit', 'mockito', 'spring-kafka']",338,True,1,1
Navigation Unit Testing in MvvmCross,"<p>Trying to unit test the navigation in one of my command calls into a private method. Just trying to test if the navigation request has been made as a result of this command execution.</p>

<p>There's the old documentation; 
<a href=""https://www.mvvmcross.com/documentation/fundamentals/testing"" rel=""nofollow noreferrer"">https://www.mvvmcross.com/documentation/fundamentals/testing</a></p>

<p>This documentation does not factor in new async based calls as far as I found; For example <strong>IMvxMainThreadAsyncDispatcher</strong>
Either we need to implement two ExecuteOnMainThreadAsync methods or inherit from MvxMainThreadAsyncDispatcher in MockDispatcher.</p>

<p>Also need to add IMvxMainThreadAsyncDispatcher in IoC registration.</p>

<pre><code>var mockDispatcher = new MockDispatcher();

...

...

Ioc.RegisterSingleton&lt;IMvxMainThreadAsyncDispatcher&gt;(MockDispatcher);
</code></pre>

<p>So almost all tests work except navigation call requests. Below method inside MockDispatcher never gets called so I can't check request counts;</p>

<pre><code>public async Task&lt;bool&gt; ShowViewModel(MvxViewModelRequest request)
{
     Requests.Add(request);
     return true;
}
</code></pre>

<p>Anybody has a working code that would mock and gets this Request called or in some other form? IMvxMainThreadDispatcher is being set as absolute, and navigation calls are not done with ShowViewModel&lt;>() anymore in MVVMCross, it's done by calling navigationService.Navigate();</p>
",https://stackoverflow.com/questions/60527817/navigation-unit-testing-in-mvvmcross,"['unit-testing', 'xamarin.android', 'xamarin.ios', 'moq', 'mvvmcross']",714,True,1,1
Unit testing for asyncio coroutines,"<p>I'd like to use <code>nosetests</code> to test the coroutines in a class. My first thought was to call each coroutine with <code>asyncio.run()</code>. Unfortunately, I started to receive runtime exceptions after the first test. This is a minimal example to show the problem:</p>
<pre><code>import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print(&quot;Hello from MyClass&quot;)

class TestMyClass:

    def setup(self):
        self.my_class = MyClass()

    def test1(self):
        asyncio.run(self.my_class.hello())

    def test2(self):
        asyncio.run(self.my_class.hello())
</code></pre>
<p>When this script is run with <code>nosetests</code>, a <code>RuntimeError: There is no current event loop in thread 'MainThread'.</code> is raised for <code>test2</code>. The offending line is the creation of an <code>Event</code> in <code>MyClass</code>. I don't fully understand the issue. The <a href=""https://docs.python.org/3.7/library/asyncio-task.html#asyncio.run"" rel=""nofollow noreferrer"">documentation for <code>asyncio.run()</code></a> states that the function &quot;should be used as a main entry point for asyncio programs, and should ideally only be called once.&quot; To me, this sounds as if it's possible to call <code>asyncio.run()</code> multiple times in a program, even though it's not recommended.</p>
<p>Anyway, as the error points to a non-existing event loop, I decided to manage the event loop manually, and came up with the following workaround:</p>
<pre><code>import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print(&quot;Hello from MyClass&quot;)

class TestMyClass:

    def __init__(self):
        try:
            self.loop = asyncio.get_event_loop()
        except RuntimeError:
            self.loop = asyncio.new_event_loop()

    def setup(self):
        asyncio.set_event_loop(self.loop)
        self.my_class = MyClass()

    def test1(self):
        asyncio.run(self.my_class.hello())

    def test2(self):
        asyncio.run(self.my_class.hello())
</code></pre>
<p>The <code>try...except</code> in the initialization is required when multiple test scripts are run sequentially. I'm using Python 3.7.6.</p>
<p>My workaround doesn't look very clean to me, and I'm wondering if there's a better approach.</p>
",https://stackoverflow.com/questions/61101328/unit-testing-for-asyncio-coroutines,"['python', 'unit-testing', 'python-asyncio']",361,False,1,1
Unit testing Rust Syn crate,"<p>From the <a href=""https://lib.rs/crates/syn"" rel=""nofollow noreferrer"">Syn documentation</a>:</p>
<blockquote>
<p>Syn operates on the token representation provided by the <code>proc-macro2</code> crate from crates.io rather than using the compiler's built in <code>proc-macro</code> crate directly. This enables code using <code>Syn</code> to execute outside of the context of a procedural macro, such as in unit tests or <code>build.rs</code></p>
</blockquote>
<p>I am trying to enable unit testing for some Syn functions, however I can't get it to work no matter what I have tried. It does not work with the <code>proc_macro2::TokenStream</code> type, but it won't work with the <code>proc_macro::TokenStream</code> because we are not in a proc-macro context.</p>
<p><a href=""https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=79269a1175339b97213f28f3fa25a06d"" rel=""nofollow noreferrer"">link to playground</a></p>
<pre class=""lang-rust prettyprint-override""><code>use quote::quote;
use syn;

fn test() {
    // let stream: syn::export::TokenStream = quote!{fn foo() {};}.into(); // doesn't work
    let stream: proc_macro2::TokenStream = quote!{fn foo() {};}.into(); // doesn't work
    // let item = parse_macro_input!(stream as Item); // doesn't work
    let item = syn::parse(stream).unwrap();

}

fn main() {
    test();
}

</code></pre>
<p>Any help on how to test syn functions outside of the proc-macro context would be appreciated. I am aware of the <a href=""https://docs.rs/trybuild/1.0.35/trybuild/"" rel=""nofollow noreferrer"">trybuild</a> crate, but I would like to be able to unit test the macro's functions first.</p>
",https://stackoverflow.com/questions/65269173/unit-testing-rust-syn-crate,"['unit-testing', 'parsing', 'rust', 'rust-macros', 'rust-proc-macros']",828,True,1,1
VS2017 Unit Testing *.runsettings file,"<p>In Visual studio 2017, is there a way to have the .runsettings file automatically loaded by specifying it in the .sln or the cs.proj?</p>
<p>Whenever I want to run my tests, I currently have to go up to the menu and select Test-&gt;Test Settings -&gt;Select Test Settings file. Which obviously gets lost when I restart Visual Studio.</p>
<p>Am I correct in thinking this feature is only available in VS2019?</p>
",https://stackoverflow.com/questions/64450212/vs2017-unit-testing-runsettings-file,"['c#', 'unit-testing']",73,False,1,0
Unit testing a constructor method,"<p>I'm having trouble getting my head round how to unit test a constructor method.</p>

<p>I need to check an error is being thrown. The constructor is:</p>

<pre class=""lang-java prettyprint-override""><code>@Autowired
public BankDetailsValidator() {
  try {
    logDebugMessage(""BankDetailsValidator() constructor"");
    loadModulusWeightTable();
    loadSortCodeSubstitutionTable();
  } catch (final IOException e) {
    throw new BankDetailsValidationRuntimeException(""An error occured loading the modulus weight table or sort code substitution table"", e);
  }
}
</code></pre>

<p>To test this, I need to have the <code>loadModulusWeightTable</code> or <code>loadSortCodeSubstitutionTable</code> throw and <code>IOException</code>. </p>

<pre class=""lang-java prettyprint-override""><code>private void loadModulusWeightTable() throws IOException {
  modulusWeightTable.clear();
  logDebugMessage(""Attempting to load modulus weight table "" + MODULUS_WEIGHT_TABLE);

  final InputStream in = new FileInputStream(MODULUS_WEIGHT_TABLE);
  br = new BufferedReader(new InputStreamReader(in));
  try {
    String line;
    while ((line = br.readLine()) != null) {
      final String[] fields = line.split(""\\s+"");
      modulusWeightTable.add(new ModulusWeightTableEntry(fields));
    }
    logDebugMessage(""Modulus weight table loaded"");
  }
  finally {
    br.close();
  }
}
</code></pre>

<p>I was trying to use <code>Spy</code> to have the buffered file reader return a <code>IOException</code> but couldn't get it working due to it being in the constructor.</p>

<pre class=""lang-java prettyprint-override""><code>public class BankDetailsValidatorTest {

  @Spy
  private BufferedReader mockBufferReader;

  @InjectMocks
  private CDLBankDetailsValidator testSubject;

  @Test(expected = IOException.class)
  public void testIOErrorLogging() throws Exception{

    when(mockBufferReader.readLine()).thenThrow(new IOException());
    testSubject = new CDLBankDetailsValidator();
  }
}
</code></pre>
",https://stackoverflow.com/questions/60207562/unit-testing-a-constructor-method,"['java', 'junit4']",97,False,1,2
Unit Testing NodaTime Aliased DateTimeZone,"<p>I am working on a unit test for my extension method.</p>

<pre><code>public static DateTimeZone GetDateTimeZone(this IDateTimeZoneProvider dateTimeZoneProvider, String timezoneId)
{
    DateTimeZone dateTimeZone;
    if ((dateTimeZone = dateTimeZoneProvider.GetZoneOrNull(timezoneId)) != null)
        return dateTimeZone;    

    // Continues to try and map from TimeZoneInfo if dateTimeZone == null
}
</code></pre>

<p>When unit testing this method, the test is failing as the alias is being returned for the DateTimeZone Id.</p>

<pre><code>[TestMethod]
public void GetDateTimeZone_DateTimeZoneProviderHasTimezoneIdAsAlias_ReturnsDateTimeZone()
{
    var expectedTimezoneId = ""America/New_York"";
    var timezoneId = ""US/Eastern"";
    var dateTimeZone = _dateTimeZoneProvider.GetDateTimeZone(timezoneId); 

    Assert.AreEqual(expectedTimezoneId, dateTimeZone.Id);
}
</code></pre>

<p>As you can see, I am expecting what is in the Zone Id column (<a href=""https://nodatime.org/TimeZones"" rel=""nofollow noreferrer"">https://nodatime.org/TimeZones</a>), but instead the alias ""US/Eastern"" is being returned.
This is especially surprising since the documentation on GetZoneOrNull (<a href=""https://nodatime.org/2.4.x/api/NodaTime.IDateTimeZoneProvider.html#NodaTime_IDateTimeZoneProvider_GetZoneOrNull_System_String_"" rel=""nofollow noreferrer"">https://nodatime.org/2.4.x/api/NodaTime.IDateTimeZoneProvider.html#NodaTime_IDateTimeZoneProvider_GetZoneOrNull_System_String_</a>)
says ""Note that this may return a DateTimeZone that has a different ID to that requested, if the ID provided is an alias.""</p>

<p>After reading, ""Note also that this method is not required to return the same DateTimeZone instance for successive requests for the same ID; however, all instances returned for a given ID must compare as equal."",
I thought, maybe the aliased DateTimeZone would equate to the unaliased.</p>

<pre><code>[TestMethod]
public void GetDateTimeZone_DateTimeZoneProviderHasTimezoneIdAsAlias_ReturnsDateTimeZone()
{
    var expectedDateTimeZone = _dateTimeZoneProvider.GetZoneOrNull(""America/New_York"");
    var timezoneId = ""US/Eastern"";
    var dateTimeZone = _dateTimeZoneProvider.GetDateTimeZone(timezoneId);

    Assert.AreEqual(expectedDateTimeZone, dateTimeZone);
}
</code></pre>

<p>But, it does not.  The code that calls the extension method doesn't really care about the Id as it is using the DateTimeZone to convert from LocalTime to Utc.</p>

<pre><code>IDateTimeZoneProvider dateTimeZoneProvider = DateTimeZoneProviders.Tzdb;
var dateTimeZone = dateTimeZoneProvider.GetDateTimeZone(timezoneId);

var zonedDateTime = dateTimeZone.AtLeniently(localDateTime);
return zonedDateTime.ToDateTimeUtc(); 
</code></pre>

<p>So, it will take whatever the current offset is at the time of localDateTime.  But, for unit testing purposes, I can't just check the offset as in the example of ""America/New_York"", because it is sometimes -5 and other times -4.  Asserting that it is either -5 or -4 in a unit test doesn't feel kosher.  How should I go about testing an aliased DateTimeZone?</p>

<h2>UPDATE</h2>

<p>Here's the updated unit test using a specific date and time in which the offset is known.</p>

<pre><code>[TestMethod]
public void GetDateTimeZone_DateTimeZoneProviderHasTimezoneIdAsAlias_ReturnsDateTimeZone()
{
    var expectedOffset = Offset.FromHours(-5);
    var specificDateTimeWithKnownUtcOffset = new DateTime(2020, 1, 15, 8, 29, 15, DateTimeKind.Utc);
    var instant = Instant.FromDateTimeUtc(specificDateTimeWithKnownUtcOffset);
    var timezoneId = ""US/Eastern"";
    var dateTimeZone = _dateTimeZoneProvider.GetDateTimeZone(timezoneId);

    Assert.AreEqual(expectedOffset, dateTimeZone.GetUtcOffset(instant));
}
</code></pre>
",https://stackoverflow.com/questions/59737549/unit-testing-nodatime-aliased-datetimezone,"['c#', 'unit-testing', 'nodatime']",529,True,1,1
Unit testing BackgroundWorker reporting progress,"<p>The following class has a method that calls the <code>ReportProgress</code> method of a 'BackgroundWorker`:</p>

<pre><code>public class Project
{
    protected System.ComponentModel.BackgroundWorker worker;

    public void progress(int percentage)
    {
        if (worker != null)
             worker.ReportProgress(percentage);
    }
}
</code></pre>

<p>How to go about testing the <code>progress</code> method? The aim would be to test that the worker method has its <code>ReportProgress</code> method called with the correct argument. Correct me if this approach is wrong.</p>

<p>What has been tried is using FakeItEasy to create a fake of the <code>BackgroundWorker</code>, but that yields the error: ""non virtual methods can not be intercepted"".</p>
",https://stackoverflow.com/questions/62401119/unit-testing-backgroundworker-reporting-progress,"['c#', '.net', 'unit-testing', 'backgroundworker', 'reportprogress']",196,False,0,0
Mocking Newtonsoft.Json When Unit Testing,"<p>I'm currently testing a class that reads an embedded json file, deserialises and loads it into my DI container. Here is a tl;dr of the code, omitting error handling:</p>
<pre><code>private readonly IAssemblyManager _assemblyManager;
private readonly IContainerRegistry _containerRegistry

public void Load(string resourceName)
{
    string json = _assemblyManager.LoadResource(resourceName);

    IConfiguration config = JsonConvert.DeserializeObject&lt;Configuration&gt;(json);

    _containerRegistry.RegisterInstance&lt;IConfiguration&gt;(config);
}
</code></pre>
<p>I'm using NUnit and Moq to test and I'm fairly new to the testing game. I want to know the best approach to testing the <code>JsonConvert</code> method, I've had to write wrappers for some of my tests but would be absolutely devastated if I had to do it here. This is the most downloaded NuGet package, surely people have come across this issue and have a decent solution. I've used <a href=""https://github.com/System-IO-Abstractions/System.IO.Abstractions"" rel=""nofollow noreferrer""><code>System.IO.Abstractions</code></a> to allow me to test my file access code, I would have expected there would be something similar for <code>Newtonsoft.Json</code>.</p>
<p>Other potential workarounds could be to have my assembly manager doing the deserialisation:</p>
<pre><code>public interface IAssemblyManager
{
    T LoadResource&lt;T&gt;(string resourceName);
}
</code></pre>
<p>But for my application I want to use the <code>IAssemblyManager</code> to load sql &amp; json, I don't really want it being responsible for deserialising anything. And I've also just moved my problem from one class to another.</p>
",https://stackoverflow.com/questions/64265128/mocking-newtonsoft-json-when-unit-testing,"['c#', 'unit-testing', 'exception', 'json.net', 'nunit']",1532,True,0,1
Unit Testing failing with NullPoiterException,"<p>Hi i'm new to programming and i started doing unit testing.I have problem with NullPointerException.
I think something is broken in my InteliJ when i update it.My teachers type same code but their tests are passing.Here is what i should Test:</p>
<pre><code> @Before
public void SetUp() {
   this.motorcycle= new UnitMotorcycle(&quot;Nissan&quot;, 70, 120);
}

@Test(expected = NullPointerException.class)
public void testShouldThrowNullException() {
    UnitRider unitRider = new UnitRider(null, motorcycle);
}
@Test(expected = NullPointerException.class)
public void testNameShouldBeNull() {
    UnitRider unitRider = new UnitRider(null, motorcycle);
    assertNull(unitRider.getName());
}
@Test(expected = NullPointerException.class)
public void testNameAndMotorShouldBeNull() {
    UnitRider unitRider = new UnitRider(&quot;&quot;, null);
    assertEquals(&quot;&quot;,unitRider.getName());
}
</code></pre>
<p>Here is the method i am testing:</p>
<pre><code> public String addRider(UnitRider rider) {
    if (rider == null) {
        throw new NullPointerException(RIDER_INVALID);
    }
</code></pre>
<p>And my testing is failing and give me NullPointerException is expected.
Like i did what my teacher.And I think it was from update and i preinstall with diffrent versions of inteliJ but still dont't working.I'm using Java 11, Junit 4.12 and Maven 11</p>
",https://stackoverflow.com/questions/63420347/unit-testing-failing-with-nullpoiterexception,"['java', 'unit-testing', 'junit', 'nullpointerexception', 'jetbrains-ide']",35,False,0,0
Unit testing method with async,"<p>I am writing a unit test for a method using <code>Moq</code> framework.  </p>

<p>The method calls the method <code>Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request)</code> of <code>System.Net.Http</code> with <code>await</code>.</p>

<p>When I execute my test case the method does not return anything. Certainly, I am doing something wrong. Please help me to find it.</p>

<p>Please note that this call is not loosely coupled.</p>

<p>I did check the other answers like <a href=""https://stackoverflow.com/questions/19365479/unit-testing-async-method-test-never-completes"">Unit testing async method - test never completes</a> which have it as loosely coupled and could be mocked.</p>

<p><strong>Edit 1</strong>: 
The method similar to which I am trying to unit test</p>

<pre><code>class Class1
    {
        public async Task&lt;string&gt; Method(string url)
        {

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,url);
            HttpResponseMessage response = await new HttpClient().SendAsync(request);
            return System.Convert.ToString( response);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/60995119/unit-testing-method-with-async,"['unit-testing', 'asynchronous', 'moq']",384,True,0,1
Unit testing QWizard with QtTest,"<p>I am writing unit test cases for my QT application which contains a <code>QWizard</code>. I am using <code>QtTest</code> framework. But I am not able to get the Next button clicked on my wizard page.</p>

<pre><code>welcomePage-&gt;m_installedVersion-&gt;lineEdit()-&gt;setText(""1102"");
welcomePage-&gt;m_upgradeVersion-&gt;lineEdit()-&gt;setText(""12"");
welcomePage-&gt;completeChanged(); //Only the above two text fields are mandatory so Next button should be enabled here, but it is not. So I have manually enabled it below.

myWizard.getNextButton()-&gt;setEnabled(true);
while( !myWizard.getNextButton()-&gt;isEnabled())
{

}

//Trying different ways to click on Next    
QTest::mouseClick(myWizard.getNextButton(), Qt::RightButton, Qt::NoModifier, QPoint(), 5000);
QSignalSpy(myWizard.getNextButton(), &amp;QPushButton::clicked);
myWizard.getNextButton()-&gt;click();
</code></pre>

<p>The <code>initializePage</code> for the second page does not get called, so I don't think Next button has been clicked. How can I go to the Next page while unit testing?</p>
",https://stackoverflow.com/questions/59745303/unit-testing-qwizard-with-qttest,"['qt', 'qttest', 'qwizard']",128,True,-1,1
Unit testing requires many interfaces?,"<p>I'm currently working on my first project that uses TDD and unit testing. I'm writing in C++ with <strong>googletest</strong> and <strong>googlemock</strong> libraries. The project requires many small classes with particular functionalities. I mostly use dependency injection in constructors. According to this:</p>
<p><a href=""https://stackoverflow.com/questions/38181/when-should-i-mock"">When should I mock?</a> and
<a href=""https://stackoverflow.com/questions/56078171/when-to-use-mock-objects-in-unit-tests/56078734"">When to use mock objects in unit tests</a></p>
<p>dependency injected into constructor is good candidate for mocking in unit testing. There are two ways to do this in C++:</p>
<ol>
<li>Creating interface (pure virtual class). Production class and mock class derives from it.</li>
<li>Create virtual member functions inside Production class. Mock class derives from Production class. There is a problem when Production class does not define default constructor. Mock class has to call Base class constructor explicitly (personally it is not the stuff that mock object should do).</li>
</ol>
<p>How do you handle this kind of situation? Do you prefer many interfaces (N classes requires N interfaces) or deriving from Base class?</p>
",https://stackoverflow.com/questions/62829366/unit-testing-requires-many-interfaces,"['java', 'c++', 'unit-testing', 'googletest', 'googlemock']",231,True,1,1
Unit testing with inject annotation,"<p>How do I unit test a class that uses <code>@inject</code> annotation:class A{</p>
<pre><code>@inject
private B b;

void foo(){
    b.funcInClassB();
}
</code></pre>
<p>I am new to unit testing and having troubles testing this function because when calling <code>b.funcInClassB()</code> it throws NullPointerException because b is null.
I wrote the following test:</p>
<pre><code>class Atest{
   @MockBean
   private B b;
   @Test
   void foo(){
     when(b.funcInClassB()).willReturn(&quot;something&quot;);
      A a = new A();
      a.foo();
   }
}
</code></pre>
",https://stackoverflow.com/questions/63783609/unit-testing-with-inject-annotation,"['java', 'unit-testing', 'dependency-injection', 'mocking']",235,True,0,1
Unit testing state based test,"<p>Let's say I have a method called <code>CreateApplication</code> and a private helper method <code>GenerateApplication</code> which generates application object with calculated fields. After that, I am inserting the generated application object into the database.</p>
<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;Guid&gt; CreateApplication(CreateApplicationdRequest request)
{
    var application = GenerateApplication(request);

    await UnitOfWork.Application.InsertAsync(application); // it's same as _db.Application.InsertAsync(application) 
    await UnitOfWork.CommitAsync();  // it's same as _db.SaveChangesAsync();

    return application.Id;
}
</code></pre>
<p>What will be a proper unit test for such cases? Should I verify the <code>InsertAsync</code> method (which inserts application into the database)  and also check if the application object was correctly generated?</p>
<p>Something like this:</p>
<pre class=""lang-cs prettyprint-override""><code>[Fact]
public async Task CreateApplication_WhenCalled_ShouldStoreApplication()
{
    // I have already mocked unitofwork in constructor
    // when InsertAsync method will called, it will assign passed argument to declared private field (application)
    Application application;
    UnitOfWork.Setup(x =&gt; x.Application.InsertAsync(It.IsAny&lt;Application&gt;()))
        .Callback&lt;Application&gt;(app =&gt; application = app);

    //act
    await _applicationService.CreateApplication(new CreateApplicationdRequest()); // dummy request

    //assert 
    UnitOfWork.Verify(x =&gt; x.Application.InsertAsync(It.IsAny&lt;Application&gt;()), Times.Once);
    UnitOfWork.Verify(x =&gt; x.CommitAsync(), Times.Once);

    //here I am checking generated application's state
    Assert.Equal(application.CustomerId, request.CustomerId);
    Assert.Equal(application.Applicant.PhoneNumber, request.PhoneNumber);
    Assert.Equal(application.LoanCurrencyId, request.LoanCurrencyId);
    Assert.Equal(application.TermType, request.TermType);
    Assert.Equal(application.Term, request.Term);
    Assert.Equal(&quot;01017054322_CC-01001&quot;, application.DocumentNo);
    Assert.Equal(application.GracePeriod, request.DefaultGracePeriod);
}
</code></pre>
<p>Or this is not a correct approach and it's better to use integration tests for such cases?</p>
",https://stackoverflow.com/questions/64662712/unit-testing-state-based-test,"['c#', 'unit-testing', 'moq', 'xunit']",702,True,0,1
Avoid Thread Sleep Unit Testing,"<p>I have the below method which uses websocket connection to send request,</p>

<pre><code>public void sendLoginRequest(){

            WebSocket webSocket = webSocketConnection.getSocketConnection();

            Thread.sleep(300 * 1000);

            JSONObject loginJson = new JSONObject();
            loginJson.put(""username"",""test"");

            webSocket.sendText(loginJson.toString());
    }
</code></pre>

<p>I have created my tested case with,</p>

<pre><code>@Test
    public void testSendLoginRequest() {
        obj.sendLoginRequest();

    }
</code></pre>

<p>Due to Thread.sleep, it's waiting for 5 min. I'm just curious to control this flow, and make sure the data send to websocket. As far as i know verify method invokes on Mock object, but in this case how can i achieve it.</p>

<p>P.S: I use <code>com.refinitiv.qc.ert.infrastructure.socket.WebSocketConnection</code> API.</p>
",https://stackoverflow.com/questions/59880584/avoid-thread-sleep-unit-testing,"['unit-testing', 'java-8', 'mockito', 'junit5']",127,False,0,0
Unit testing Rest end points,"<p>I've REST end points written in java. And there's c# code in the app that invokes these end points using RestClient.
I'm thinking of writing unit tests for these.
Just wondering what would be the best approach for this? Moq framework or NUNIT or something else?
Any ideas?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/59673050/unit-testing-rest-end-points,"['java', 'c#', 'unit-testing']",97,True,0,2
Unit Testing Android Studio Textview,"<p>This is my main activity which gets a json array from a URL. My problem is that when I try and Unit test what should be in the textview it gives me a null pointer exeption. </p>

<p>public class MainActivity extends AppCompatActivity {</p>

<pre><code>TextView txtJson;
ProgressDialog pd;
public static TextView testString;
String jsonString = null;
List&lt;Location&gt; locations;`enter code here`


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtJson = (TextView) findViewById(R.id.tvJsonItem);
    testString = (TextView) findViewById(R.id.test_for_string);

    new JsonTask().execute(""https://wsu-dining-service.s3.amazonaws.com/current-menu.json"");
}

protected void postCreate()
{
    mapStrinToClass();
    testString.setText(locations.get(0).getName());
}


private void mapStrinToClass()
{
    ObjectMapper objectMapper = new ObjectMapper();
    JsonFactory jsonFactory = objectMapper.getFactory();
    try {
        JsonParser jsonParser = jsonFactory.createParser(jsonString);
        locations = objectMapper.readValue(jsonString,
                new TypeReference&lt;List&lt;Location&gt;&gt;() {
                });
    } catch (IOException e) {
        e.printStackTrace();
    }

}


private class JsonTask extends AsyncTask&lt;String, String, String&gt; {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage(""Please wait"");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = """";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+""\n"");
                Log.d(""Response: "", ""&gt; "" + line);   //here u ll get whole response...... :-)

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        jsonString = result;
        postCreate();
    }
}
</code></pre>

<p>}</p>

<p>My unit test
* When I run the app the textview is populated with ""Tim &amp; Jeanne's Dining Commons"" but the test fails and says the testString.getText().toString(); is null</p>

<pre><code>@Test
public void isMenuCorrect() {
    String menuTxt = MainActivity.testString.getText().toString();
    assert(menuTxt == ""Tim &amp; Jeanne's Dining Commons"");

}
</code></pre>
",https://stackoverflow.com/questions/60530299/unit-testing-android-studio-textview,"['android', 'unit-testing']",789,False,0,1
Enzyme Unit testing a component,"<p>I cant seem to get a basic unit test to run with enzyme.</p>
<pre><code>describe('&lt;Fixture /&gt;', () =&gt; {
    it(&quot;should the test&quot;,() =&gt; {
      const wrapper = mount(&lt;Fixture /&gt;);
      expect(wrapper.find('#checked')).toBeChecked();
      expect(wrapper.find('#not')).not.toBeChecked();
    })
  });


function Fixture() {
    return (
      &lt;div&gt;
        &lt;input id=&quot;checked&quot; defaultChecked /&gt;
        &lt;input id=&quot;not&quot; defaultChecked={false} /&gt;
        &lt;input id=&quot;tertiary&quot; defaultChecked checked={false} /&gt;
      &lt;/div&gt;
    );
  }
</code></pre>
<p>I keep getting the following error</p>
<pre><code>TypeError: Cannot read property 'child' of undefined
</code></pre>
",https://stackoverflow.com/questions/64897219/enzyme-unit-testing-a-component,"['arrays', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",805,True,-1,1
Unit testing Dapper/SqlConnection queries,"<p>I have the following service that I would like to create unit tests for</p>

<pre><code>public class Service
{
    public async Task&lt;IEnumerable&lt;Person&gt;&gt; GetPeople(string connString)
    {
        var conn = new SqlConnection(connString);
        await conn.OpenAsync();
        return await conn.QueryAsync&lt;Person&gt;(""SELECT * FROM People"");
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
</code></pre>

<p>I will be passing a connection string to connect to the db.
I know I need to create a in-memory database, then create the db structure, then table, then insert some data, then query using the service.</p>

<p>I tried using InMemoryDatabase but that seems to geared towards EF Code</p>

<p>My question how do I create unit tests for above code that would run in memory as this will also run azure.</p>
",https://stackoverflow.com/questions/60305103/unit-testing-dapper-sqlconnection-queries,"['c#', 'unit-testing', 'dapper']",468,True,-1,1
Unit testing events with mocha,"<p>Not sure where to start or what is the best approach to testing the following code with mocha and chai:</p>

<pre><code>module.exports = function trackCustomDyEvents(events){
let $;

trackEvents();

function trackEvents() {
    events.forEach((event) =&gt; {
        $(document).on(event.type, event.element, () =&gt; {
            if (!event.predicate()) return;
            window.DY.API('event', {
                name: event.name
            });
        });
    });
}
</code></pre>

<p>};</p>
",https://stackoverflow.com/questions/59569112/unit-testing-events-with-mocha,"['node.js', 'mocha.js', 'chai']",636,False,0,1
Unit Testing in Python Djnago,"<p>I am using</p>
<p>Django==3.0.3</p>
<p>djangorestframework==3.11.0</p>
<p>python ==3.6.8</p>
<p>I want to write unit testing for API and no need to use any database(no need of mock database)
that mean I want  to mock the database call and write unit test cases</p>
<p>how can i write which property is used for this</p>
<p>Showing my api</p>
<pre><code>@api_view(['POST'])
@permission_classes([IsAuthenticated])
def employee_entry(request):
    try:
        login = User.objects.get(pk=request.user.id)
        validationmsg = ''
        emp_data = request.data
        if not emp_data:
            validationmsg = validation[&quot;FDP15&quot;]
        elif emp_data[&quot;EmployeeName&quot;] is None or emp_data[&quot;EmployeeName&quot;] == '':
            validationmsg = validation[&quot;FDP1&quot;]
        elif emp_data[&quot;EmployeeCode&quot;] is None or emp_data[&quot;EmployeeCode&quot;] == '':
            validationmsg = validation[&quot;FDP2&quot;]
        elif Employee.objects.filter(EmployeeCode=emp_data[&quot;EmployeeCode&quot;]).count() &gt; 0:
            validationmsg = validation[&quot;FDP3&quot;]
        if validationmsg != '':
            return Response({msg: validationmsg}, status=status.HTTP_400_BAD_REQUEST)
        employee = Employee(
            EmployeeName=emp_data[&quot;EmployeeName&quot;],
            EmployeeCode=emp_data[&quot;EmployeeCode&quot;],
            Security=emp_data[&quot;Security&quot;],
            CreatedDate=date.today(),
            CreatedUser=login,
        )
        employee.save()
        if emp_data[&quot;Security&quot;] == 1:
            device = Device.objects.filter(~Q(DeviceStatus=static_values[&quot;const0&quot;]))
            employee.Device.set(device)
        elif emp_data[&quot;Security&quot;] == 0:
            device = Device.objects.filter(~Q(DeviceStatus=static_values[&quot;const0&quot;]), DefaultAccess=True)
            employee.Device.set(device)
        return Response({&quot;EmployeeId&quot;: employee.EmployeeId}, status=status.HTTP_200_OK)
    except(KeyError, TypeError, ValueError) as ex:
        logging.getLogger(&quot;error_logger&quot;).exception(repr(ex))
        return Response({msg: validation[&quot;FDP21&quot;]}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as ex:
        logging.getLogger(&quot;error_logger&quot;).exception(repr(ex))
        return Response({msg: validation[&quot;FDP23&quot;]}, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
",https://stackoverflow.com/questions/64763679/unit-testing-in-python-djnago,"['django', 'unit-testing', 'python-unittest', 'django-unittest', 'python-unittest.mock']",46,False,0,0
Unit testing an ExceptionHandler class,"<p>I’m trying write a unit test for an ExceptionHandler class but I’m not 100% sure how to go about it. I’m struggling to work out how do I go about setting up the MethodArgumentNotValidException class with an error list?</p>

<pre><code>@ControllerAdvice
public class InputExceptionHandler extends ResponseEntityExceptionHandler {

    private static final String INVALID_CHARACTER_MESSAGE = ""Fields contain invalid characters:"";

    @Override
    protected ResponseEntity&lt;Object&gt; handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status,
                                                                  WebRequest request) {

        final List&lt;String&gt; errorList = getErrorList(ex);
        final StringBuilder errorMessage = new StringBuilder(popFirstError(errorList));
        if(errorMessage.toString().contains(INVALID_CHARACTER_MESSAGE)) {
            combineDuplicateErrorMessage(errorList, errorMessage);
        }
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(makeBankDetailsValidationModel(errorMessage.toString()));
    }

    private BankDetailsValidationModel makeBankDetailsValidationModel(String validationErrorDescription){
        return new BankDetailsValidationModel(false, false, validationErrorDescription, """");
    }

    private StringBuilder combineDuplicateErrorMessage(List&lt;String&gt; errorList, StringBuilder errorMessage) {
        return errorList.stream()
                .filter(value -&gt; value.contains(INVALID_CHARACTER_MESSAGE))
                .findFirst()
                .map(value -&gt; errorMessage.append("", "").append(value.substring(35)))
                .orElse(null);
    }

    private String popFirstError(List&lt;String&gt; errorMessages) {
        final String message = errorMessages.get(0);
        errorMessages.remove(0);
        return message;
    }

    private List&lt;String&gt; getErrorList(MethodArgumentNotValidException ex) {
        return ex.getBindingResult()
                .getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .sorted()
                .collect(Collectors.toCollection(ArrayList::new));
    }
}
</code></pre>
",https://stackoverflow.com/questions/60622863/unit-testing-an-exceptionhandler-class,"['java', 'junit5']",723,False,0,1
Unit testing an ExceptionHandler class,"<p>I’m trying write a unit test for an ExceptionHandler class but I’m not 100% sure how to go about it. I’m struggling to work out how do I go about setting up the MethodArgumentNotValidException class with an error list?</p>

<pre><code>@ControllerAdvice
public class InputExceptionHandler extends ResponseEntityExceptionHandler {

    private static final String INVALID_CHARACTER_MESSAGE = ""Fields contain invalid characters:"";

    @Override
    protected ResponseEntity&lt;Object&gt; handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status,
                                                                  WebRequest request) {

        final List&lt;String&gt; errorList = getErrorList(ex);
        final StringBuilder errorMessage = new StringBuilder(popFirstError(errorList));
        if(errorMessage.toString().contains(INVALID_CHARACTER_MESSAGE)) {
            combineDuplicateErrorMessage(errorList, errorMessage);
        }
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(makeBankDetailsValidationModel(errorMessage.toString()));
    }

    private BankDetailsValidationModel makeBankDetailsValidationModel(String validationErrorDescription){
        return new BankDetailsValidationModel(false, false, validationErrorDescription, """");
    }

    private StringBuilder combineDuplicateErrorMessage(List&lt;String&gt; errorList, StringBuilder errorMessage) {
        return errorList.stream()
                .filter(value -&gt; value.contains(INVALID_CHARACTER_MESSAGE))
                .findFirst()
                .map(value -&gt; errorMessage.append("", "").append(value.substring(35)))
                .orElse(null);
    }

    private String popFirstError(List&lt;String&gt; errorMessages) {
        final String message = errorMessages.get(0);
        errorMessages.remove(0);
        return message;
    }

    private List&lt;String&gt; getErrorList(MethodArgumentNotValidException ex) {
        return ex.getBindingResult()
                .getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .sorted()
                .collect(Collectors.toCollection(ArrayList::new));
    }
}
</code></pre>
",https://stackoverflow.com/questions/60622863/unit-testing-an-exceptionhandler-class,"['java', 'junit5']",723,False,0,1
Unit testing a File.ReadAllText method,"<p>Hi i'm learning to write tests with xUnit. I utilized System.IO.Abstractions in this class in order to use IFileSystem interface.</p>

<pre><code>public class MyDictionary : IMyDictionary   
{
    IFileSystem _fileSystem;
    public MyDictionary() : this (new FileSystem()) {}

    public MyDictionary(IFileSystem fileSystem)
    {
        _fileSystem = fileSystem;
    }
    public Dictionary&lt;string, string&gt; GetDictionary()
    {
        return JsonConvert.DeserializeObject&lt;Dictionary&lt;string, string&gt;(_fileSystem.File.ReadAllText(""dictionary.json""));
    }

}
</code></pre>

<p>Here is the test i wrote using Moq</p>

<pre><code>    [Fact]
    public void GetDictionary_ShouldReturnDictionary()
    {
       using (var mock = AutoMock.GetLoose())
        {
            mock.Mock&lt;IFileSystem&gt;().Setup(x =&gt; x.File.ReadAllText(""dictionary.json""))
                .Returns(JsonConvert.SerializeObject(dic));

            var cls = mock.Create&lt;MyDictionary&gt;();
            var expected = dic;
            var actual = cls.GetDictionary();

            Assert.True(actual != null);
            Assert.Equal(expected, actual);

        }
    }

 Dictionary&lt;string, string&gt; dic = new Dictionary&lt;string, string&gt;
    {
        { ""Key1"",   ""Value1"" },
        {""Key2"",    ""Value2"" }
    };
</code></pre>

<p>Is this ok?(the test works fine) Is there any other unit test i should write against this simple method? Testing for exceptions for example? If so how should i do it? Thanks in advance!</p>
",https://stackoverflow.com/questions/61468625/unit-testing-a-file-readalltext-method,"['c#', '.net', 'moq', 'xunit']",754,False,0,0
Moq Unit testing linq queries,"<p>I'm trying to test a method in my service class layer, it currently gives a null reference error message because I'm using a method in my setup called .GetById but in my service class I'm using a linq query.</p>
<p>My main question is how would I change .GetById to actually test a linq query?</p>
<p>Please let me know if more information is needed</p>
<p>My current unit test method:</p>
<pre><code>    [Fact]
    public async Task GetCafeByIdAsync_Should_Throw_ArgumentNullException()
    {
        var cafe = new Cafe()
        {
            CafeId = 1,
            Name = &quot;Bellas&quot;
        };

        var mockCafe = new Mock&lt;IRepositoryAsync&lt;Cafe&gt;&gt;();
        mockCafe.Setup(x =&gt; x.GetByIdAsync(cafe.CafeId)).ReturnsAsync(cafe); //errors on this line

        
        var mapper = new MapperConfiguration(cfg =&gt;
        {
            cfg.AddProfile(new AutoMapperProfile());
        }).CreateMapper();

        var cafeService = new CafeService(mockCafe.Object, mapper);
        
        await Assert.ThrowsAsync&lt;ArgumentNullException&gt;(() =&gt; cafeService.Get(2));
    }
</code></pre>
<p>My service class I'm trying to unit test:</p>
<pre><code>        public async Task&lt;VersionResponse&gt; Get(int cafeId)
        {
            var cafe = await _context.Cafe.Where(w =&gt; w.CafeId== cafeId).ToResponse().FirstOrDefaultAsync();
            
            return new VersionResponse()
            {
                Data = cafe
            };
        }
</code></pre>
",https://stackoverflow.com/questions/63784798/moq-unit-testing-linq-queries,"['c#', 'unit-testing', 'moq']",92,False,0,0
Unit Testing http4s router websocket endpoints,"<p>The idea is to be able to unit test websocket endpoints on a router service. Any other kind of endpoint is fairly easy to test with a <code>Request</code>, but I can't figure out a way of easily testing websocket responses, as hitting the endpoint with a <code>Request</code> will give you a 501 error since you don't have any corresponding socket to handshake with.</p>

<p>This is the router I'm using</p>

<pre class=""lang-scala prettyprint-override""><code>def router(averages: IO[SomeAverages]): HttpRoutes[F] =
    HttpRoutes.of[F] {
        case GET -&gt; Root =&gt;
            val toClient: Stream[F, WebSocketFrame] = {
                Stream
                  .awakeEvery[F](5.seconds)
                  .map(_ =&gt; {
                      val avg = averages.unsafeRunSync
                      WebSocketFrame.Text(avg.toString)
                  })
            }
            val fromClient: Pipe[F, WebSocketFrame, Unit] = _.evalMap {
                case WebSocketFrame.Text(t, _) =&gt; F.delay(println(t))
                case f =&gt; F.delay(println(s""Unknown type: $f""))
            }
            WebSocketBuilder[F].build(toClient, fromClient)
    }
</code></pre>

<p>The idea is to get something akin to the below code to work with websockets</p>

<pre class=""lang-scala prettyprint-override""><code>val server = Server.initServer[IO]
val router = server.router
val request = Request[IO](Method.GET, uri""/"")

val io = router.orNotFound.run(request)

val response = io.unsafeRunSync

// response.status should be 200
// will return 501 if a websocket endpoint
</code></pre>

<p>I've tried variations of this such as adding headers like</p>

<pre><code>val request = Request[IO](
    Method.GET,
    uri""/"",
    Headers(Header(""Connection"", ""Upgrade""), Header(""Upgrade"", ""websocket"")
)

</code></pre>

<p>Though any <code>Request</code> will return a 501.</p>

<p>I'm not sure where to go from here, so if anyone has any suggestions I'd be glad to hear. I think it has something to do with creating a websocket client, but I don't know of a way to do that in http4s.</p>
",https://stackoverflow.com/questions/60738697/unit-testing-http4s-router-websocket-endpoints,"['scala', 'unit-testing', 'websocket', 'scala-cats', 'http4s']",563,False,7,0
Unit testing static method- GsonSerializer,"<p>I need to junit test a piece of code, but the GsonConverter it calls from different class is in static method that i cannot change. I haven't a clue how to proceed as i cant mock it due to it being static.</p>
<pre><code>public String fetchEntity(Object retValue, Object[] args) {

        String refDet= null;
        List&lt;Details&gt; updatedDetails = null;
        if (retValue != null &amp;&amp; retValue instanceof List &amp;&amp; ((List) retValue).stream()
                .noneMatch((o -&gt; !(o instanceof Details)))) {
            updatedDetails = (List&lt;Details&gt;) retValue;  
        } else {
            logger.warn(&quot;Error&quot;);
            return null;    
        }
        try {
            refDet= GsonConverter.serialize(updatedDetails );
        } catch (Exception e) {
            logger.warn(&quot;Error updatedDetails &quot;);   
        } 
        return refDet;
    }
</code></pre>
<p>Here is the class with static methods</p>
<pre><code>class GsonConverter{
public static final Gson GSON = new GsonBuilder()
 .registerTypeAdapter(DateTime.class, (JsonDeserializer&lt;DateTime&gt;) (dateTime, type, context) -&gt; ISODateTimeFormat.dateTime().parseDateTime(dateTime.getAsString()))
            .create();

    public static String serialize(Object o) {
        return GSON.toJson(o);
    }
}
</code></pre>
",https://stackoverflow.com/questions/63905751/unit-testing-static-method-gsonserializer,"['java', 'junit', 'mockito', 'gson']",196,True,0,1
Unit testing Struts 2 actions,"<p>Guys I need to figure out a way to unit test our legacy code in our enterprise application which uses struts 2.</p>
<p>I can't seem to figure it out, I tried using the JUnit plugin the same way used in their website <a href=""https://struts.apache.org/getting-started/unit-testing.html"" rel=""nofollow noreferrer"">https://struts.apache.org/getting-started/unit-testing.html</a> but I can't seem to make it work.. didn't find any other useful resources(most of it is very outdated).</p>
<p>I am getting this stack trace when trying to run the test:</p>
<pre><code>javax.xml.parsers.FactoryConfigurationError: Provider for class javax.xml.parsers.SAXParserFactory cannot be created

    at javax.xml.parsers.FactoryFinder.findServiceProvider(FactoryFinder.java:311)
    at javax.xml.parsers.FactoryFinder.find(FactoryFinder.java:267)
    at javax.xml.parsers.SAXParserFactory.newInstance(SAXParserFactory.java:127)
    at com.opensymphony.xwork2.util.DomHelper.parse(DomHelper.java:98)
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadConfigurationFiles(XmlConfigurationProvider.java:1060)
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadDocuments(XmlConfigurationProvider.java:198)
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.init(XmlConfigurationProvider.java:165)
    at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:166)
    at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66)
    at org.apache.struts2.dispatcher.Dispatcher.getContainer(Dispatcher.java:957)
    at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:463)
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:496)
    at org.apache.struts2.util.StrutsTestCaseHelper.initDispatcher(StrutsTestCaseHelper.java:44)
    at org.apache.struts2.StrutsTestCase.initDispatcher(StrutsTestCase.java:236)
    at org.apache.struts2.StrutsTestCase.setUp(StrutsTestCase.java:216)
    at junit.framework.TestCase.runBare(TestCase.java:139)
    at junit.framework.TestResult$1.protect(TestResult.java:122)
    at junit.framework.TestResult.runProtected(TestResult.java:142)
    at junit.framework.TestResult.run(TestResult.java:125)
    at junit.framework.TestCase.run(TestCase.java:129)
    at junit.framework.TestSuite.runTest(TestSuite.java:252)
    at junit.framework.TestSuite.run(TestSuite.java:247)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.lang.RuntimeException: Provider for class javax.xml.parsers.SAXParserFactory cannot be created
    at javax.xml.parsers.FactoryFinder.findServiceProvider(FactoryFinder.java:308)
    ... 27 more
</code></pre>
<p>Is this happening because of a jar/dependency conflict?</p>
",https://stackoverflow.com/questions/63018614/unit-testing-struts-2-actions,"['java', 'junit', 'struts2']",135,False,0,0
Unit testing http4s with scalatest,"<p>o/</p>

<p>I am trying to implement a client for the API of cex.io in Scala. Because I like functional programming (or I think I do), I try to do this by using the http4s library. This is some experimental code:</p>

<pre><code>class CexApi {
    val baseUrl: String = ""https://cex.io/api/""

    private val blockingEC = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(5))
    private implicit val cs: ContextShift[IO] = IO.contextShift(blockingEC)
    private val httpClient: Client[IO] = JavaNetClientBuilder[IO](blockingEC).create

    def testCall(): IO[String] = {
        httpClient.expect[String](baseUrl + ""currency_limits"")
    }
}
</code></pre>

<p>Now I want to test said client:</p>

<pre><code>
class CexApiSpec extends AnyFlatSpec {

    ""The Api"" should ""be able to run a simple method"" in {
        val api = new CexApi
        val result = api.testCall()
        assert(result.toString() != null)
    }
}
</code></pre>

<p>Unfortunately, running the tests in IntelliJ directly always gives me:</p>

<pre><code>A needed class was not found. This could be due to an error in your runpath. Missing class: scala/Serializable
java.lang.NoClassDefFoundError: scala/Serializable
</code></pre>

<p>Debugging into the test says the error happens when instantiating the api class (<code>val api = new CexApi</code>).</p>

<p>The project is built with Gradle because I'd like to use Spring Boot alongside of what I'm doing. When running the gradle test task, it states that it simply does not receive any test events.</p>

<p>I'm on Scala 2.13, ScalaTest 2.13:3.1.0 http4s 0.20.15, Gradle 6.0.1 and I already switched between JDK 1.8 and 11 back and forth. I have read the internet up and down on the issue and now I'm out of ideas. Any suggestions are highly appreciated!</p>
",https://stackoverflow.com/questions/59594994/unit-testing-http4s-with-scalatest,"['scala', 'gradle', 'scalatest', 'http4s']",641,False,0,0
tryCatch Unit testing with Jest,"<p>I'm trying to test tryCatch code with jest but keep on getting error, currently this is what I've tried</p>

<p>student.js</p>

<pre><code>async checkStudentExist(studentName) {
        try {
            const studentExist = await this.StudentRepository.getOne({name: studentName})
            if (studentExist) {
                throw new Error(`Student already exist with the name: ${studentName}`)
            }
            return studentExist
        } catch (error) {
            throw error   
        }
    }
</code></pre>

<p>student.test.js</p>

<pre><code>it('should throw an error if the input name already exist in database', async () =&gt; {
    mockGetOne.mockReturnValue(Promise.resolve(expectedOrganization))
    await studentService.checkStudentExist('john doe')
    expect(mockGetOne).toHaveBeenCalledWith({name: 'sample org'})
    expect(studentService.checkStudentExist('john doe')).resolves.toThrowError(new Error(`Organization already exist with the name: john doe`))
})
</code></pre>

<p>and this is the error I'm getting</p>

<pre><code> FAIL  test/specs/services/student_service.test.js
  ● Console

    console.log src/services/student_service.js:53
      111
    console.log src/services/student_service.js:53
      111

  ● Check if Student exist › should throw an error if the input name already exist in database

    Student already exist with the name: john doe

      55 |             const studentExist = await this.StudentRepository.getOne({name: studentName})
      56 |             if (studentExist) {
    &gt; 57 |                 throw new Error(`Student already exist with the name: ${studentName}`)
         |                       ^
      58 |             }
      59 |             return studentExist
      60 |         } catch (error) {

      at StudentService.checkStudentExist (src/services/student_service.js:57:23)
</code></pre>
",https://stackoverflow.com/questions/60860941/trycatch-unit-testing-with-jest,"['javascript', 'jestjs']",75,False,0,0
Unit-testing on a database,"<p>I want to do a unit-testing on a database through overriding or mocking without bringing any changes to the database. Is there any simple way to do it?</p>

<pre><code>import sqlite3
from customer import Customer

class DataChecker:
    def __init__(self):
        self.conn = sqlite3.connect('pos.db')
        self.cursor = self.conn.cursor()

    def customer_has_equipment_attached(self, customerID):
        cursor.execute(""""""SELECT * FROM Customers WHERE ID == ?;"""""", (customerID,))
        conn.commit()
        customers = cursor.fetchall()

        if len(customers) == 0:
            print(""Customer ID not found in DB"")
            return False

        customer = customers[0]
        tmp_customer = Customer(ID=customer[0], Firstname=customer[1], Lastname=customer[2],        

        Age=customer[3], Sex=customer[4], Street=customer[5], Zip=customer[6], City=customer[7],  Nationality=customer[8], IMSIPtr=customer[9], IMEIPtr=customer[10], SubscriptionPtr=customer[11], Email=customer[12], Password=customer[13])

        # Fetch equipment
        if tmp_customer.IMEIPtr != None:
            cursor.execute(""""""SELECT * FROM Equipment WHERE ID = ?;"""""", (tmp_customer.IMEIPtr,))
            conn.commit()
            equipment = cursor.fetchone()

            if len(equipment) == 0:
                print('Customer has equipment ID but ID cant be found in DB.')
                return False

        else:
            print('Customer has no equipment attached to profile.')
            return False
</code></pre>
",https://stackoverflow.com/questions/61122554/unit-testing-on-a-database,"['python', 'python-3.x', 'database', 'sqlite', 'unit-testing']",61,False,0,1
Unit testing @Sheduled with cron,"<p>I need to test if the following scheduled method is executed at every midnight:</p>

<pre><code>public class CacheService {

  /** Evicts token from the cache at midnight */
  @Scheduled(cron = ""0 0 0 * * *"", zone = ""Europe/London"")
  @CacheEvict(value = CacheConfig.AUTH_TOKEN, allEntries = true)
  public void clearCacheAtMidnight() {
    log.info(""Scheduled cache clean at: "" + Instant.now());
  }
}
</code></pre>

<p>I am using the following unit test:</p>

<pre><code>@SpringBootTest
class CacheServiceTest {

  @SpyBean private CacheService cacheService;

  @Test
  void shouldClearCacheAtMidnight() {
    Instant.now(Clock.fixed(Instant.parse(""2020-01-01T00:00:00Z""), ZoneId.of(""Europe/London"")));
    await()
            .atMost(Duration.ofMinutes(1))
            .untilAsserted(() -&gt; verify(cacheService, atLeast(1)).clearCacheAtMidnight());
  }
}
</code></pre>

<p>But not joy. It works perfectly if I change from cron to fixrate.
I have a feeling that I am not overriding the system clock properly or I am not using the set Interval properly. </p>

<p>Any clue? </p>
",https://stackoverflow.com/questions/62195269/unit-testing-sheduled-with-cron,"['java', 'spring-boot']",919,True,-1,1
Unit testing angular and jasmine,"<p>How does one go about unit testing in angular something in the index.html file?</p>

<p>For example:  I want to create a unit test that checks that the body tag has a specific class assigned to it.  Is this possible</p>

<p>Most unit test or spec files are made for components but I cant seem to access the body tag.</p>

<p>this is a working css unit test for anything inside a component, just no idea how to get access to the body tag of the index.html page.</p>

<pre><code>
  it('should have class-name in body class tag', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);

    fixture.detectChanges();
    const compiled = fixture.debugElement;

    expect(compiled.query(By.css('.class-name'))).toBeTruthy();
  });

</code></pre>
",https://stackoverflow.com/questions/61602228/unit-testing-angular-and-jasmine,"['angular', 'unit-testing', 'jasmine']",1006,True,0,1
NullPointerException error when unit testing,"<p>When I unit test my <code>pop</code> and <code>peek</code> methods for my <code>MyStack</code> class, I encounter a <code>NullPointerException</code> relating to the <code>getData</code> method of my node class.</p>
<p>I cannot tell why and I am wondering if anyone has any ideas on how to fix it and make it so that there is not a <code>NullPointerException</code>. I have tried editing how the node works and how <code>getData</code> itself works but cannot find a solution and since cannot figure out the problem. Any help would be very much appreciated</p>
<pre><code>import java.io.*; 
import java.util.*;

public class MyStack&lt;E&gt; implements StackInterface&lt;E&gt;
{
    public Node&lt;E&gt; head;
    public int nodeCount = 0;

    public static void main(String args[]) {
    }

    public E peek() {
        return head.getData();
    }

    public E pop() {
        if (nodeCount == 0) {
            throw new EmptyStackException();
        }
        E item = head.getData();
        head = head.getNext();
        nodeCount--;
        return item;
    }

    public boolean empty() {
        if (head == null &amp;&amp; nodeCount == 0) {
            return true;
        } else {
            return false;
        }
    }
    
    public void push(E data) {
        Node&lt;E&gt; head = new Node&lt;E&gt;(data);
        nodeCount++;
    }

    public int search(Object o) {
        int count = 0;
        Node&lt;E&gt; current = new Node&lt;E&gt;(head.getData());
        while (current.getData() != o) {
            current.getNext();
            count++;
        }
        return count;
    }
}

public class Node&lt;E&gt; 
{
    public E data;
    public Node&lt;E&gt; next;
    // getters and setters  
    public Node(E data) 
    { 
        this.data = data; 
        this.next = null; 
    } 
    public E getData() {
        return this.data;
    }
    public void setData(E data) {
        this.data = data;
    }
    public Node&lt;E&gt; getNext() {
        return next;
    }
    public void setNext(Node&lt;E&gt; next) {
        this.next = next;
    }
}
</code></pre>
",https://stackoverflow.com/questions/64302416/nullpointerexception-error-when-unit-testing,"['java', 'nullpointerexception', 'stack', 'nodes']",35,True,0,1
Enzyme Unit testing a component,"<p>I cant seem to get a basic unit test to run with enzyme.</p>
<pre><code>describe('&lt;Fixture /&gt;', () =&gt; {
    it(&quot;should the test&quot;,() =&gt; {
      const wrapper = mount(&lt;Fixture /&gt;);
      expect(wrapper.find('#checked')).toBeChecked();
      expect(wrapper.find('#not')).not.toBeChecked();
    })
  });


function Fixture() {
    return (
      &lt;div&gt;
        &lt;input id=&quot;checked&quot; defaultChecked /&gt;
        &lt;input id=&quot;not&quot; defaultChecked={false} /&gt;
        &lt;input id=&quot;tertiary&quot; defaultChecked checked={false} /&gt;
      &lt;/div&gt;
    );
  }
</code></pre>
<p>I keep getting the following error</p>
<pre><code>TypeError: Cannot read property 'child' of undefined
</code></pre>
",https://stackoverflow.com/questions/64897219/enzyme-unit-testing-a-component,"['arrays', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",805,True,-1,1
Unit testing Dapper/SqlConnection queries,"<p>I have the following service that I would like to create unit tests for</p>

<pre><code>public class Service
{
    public async Task&lt;IEnumerable&lt;Person&gt;&gt; GetPeople(string connString)
    {
        var conn = new SqlConnection(connString);
        await conn.OpenAsync();
        return await conn.QueryAsync&lt;Person&gt;(""SELECT * FROM People"");
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
</code></pre>

<p>I will be passing a connection string to connect to the db.
I know I need to create a in-memory database, then create the db structure, then table, then insert some data, then query using the service.</p>

<p>I tried using InMemoryDatabase but that seems to geared towards EF Code</p>

<p>My question how do I create unit tests for above code that would run in memory as this will also run azure.</p>
",https://stackoverflow.com/questions/60305103/unit-testing-dapper-sqlconnection-queries,"['c#', 'unit-testing', 'dapper']",468,True,-1,1
Unit Testing UICollectionView.indexPath(for: UICollectionViewCell),"<p>I am trying to unit test this bit of code in a <code>ViewController</code></p>

<pre><code>    func categoryTextEditedAt(_ cell: UICollectionViewCell, _ text: String) {
        guard let indexPath = self.collectionView.indexPath(for: cell), text != """" else {return}

        //Rest of the codes to be tested
    }
</code></pre>

<p>And in my Unit Test to test the above function is as follows: </p>

<pre><code>    func testCategoryTextEditedAt() {
        sut.viewDidLoad()
        sut.collectionView.reloadData()
        let cell = sut.collectionView.dataSource?.collectionView(sut.collectionView, cellForItemAt: IndexPath(item: 0, section: 0))
        sut.categoryTextEditedAt(cell!, ""testString"")
    }
</code></pre>

<p>but I am keep getting 'nil' for the <code>indexPath</code> inside <code>categoryTextEditedAt(:)</code> function. As I debug, I found that inside <code>testCategoryTextEditedAt()</code> cell has a value but <code>self.collectionView.indexPath(for:cell)</code> keeps returning 'nil' for 'indexPath.'</p>

<p>How can I go about this process? </p>
",https://stackoverflow.com/questions/59712274/unit-testing-uicollectionview-indexpathfor-uicollectionviewcell,"['ios', 'swift', 'unit-testing', 'uikit', 'collectionview']",2989,True,0,2
Unit testing a custom symfony constraint,"<p>This should be incredibly simple but it is driving me mad this afternoon, what is the correct way to unit test a custom symfony validator? All the articles I can find have exactly the same way as I am doing it</p>
<pre><code>class Foo extends Constraint
{
    public string $message = 'The string &quot;{{ string }}&quot; is not a valid foo.';
}
</code></pre>
<pre><code>class FooValidator extends ConstraintValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint): void
    {
        if ($value !== 'foo') {
            $this-&gt;context-&gt;buildViolation($constraint-&gt;message)
                -&gt;setParameter('{{ string }}', $value)
                -&gt;addViolation();
        }
    }
}
</code></pre>
<pre><code>class FooValidatorTest extends TestCase
{

    /** @test  */
    public function validate(): void
    {
        $this-&gt;expectNotToPerformAssertions();

        $constraint = new Foo();
        $context    = \Mockery::mock(ExecutionContextInterface::class);
        $builder    = \Mockery::mock(ConstraintViolationBuilderInterface::class);

        $context-&gt;shouldReceive('buildViolation')
            -&gt;with($constraint-&gt;message)
            -&gt;andReturn($this-&gt;builder);

        $builder-&gt;shouldReceive('setParameter')
            -&gt;with('{{ string }}', 'foo-bar')
            -&gt;andReturn($builder);

        $builder-&gt;shouldReceive('addViolation');

        $validator = new FooValidator();
        $validator-&gt;initialize($context);
        $validator-&gt;validate('foo-bar', $constraint);
    }
}
</code></pre>
<p>This should work, and indeed it does, however it causes like 9 deprecation warnings</p>
<pre><code>
  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::setGroup()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.

  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::setConstraint()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.

  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::markGroupAsValidated()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.

  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::isGroupValidated()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.

  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::markConstraintAsValidated()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.

  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::isConstraintValidated()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.

  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::markObjectAsInitialized()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.

  1x: The &quot;Symfony\Component\Validator\Context\ExecutionContextInterface::isObjectInitialized()&quot; method is considered internal Used by the validator engine. Should not be called by user *           code. It may change without further notice. You should not extend it from &quot;Mockery_0_Symfony_Component_Validator_Context_ExecutionContextInterface&quot;.
</code></pre>
<p>due to the <code>@internal</code> annotation on those methods. So if you are using <code>SymfonyTestsListener</code> with deprecations set to 0 it causes the tests to fail.</p>
<p>Does anyone have any idea how you are supposed to test this without getting deprecations? I have been going round in circles. I have tried only a partial mock of <code>ExecutionContextInterface</code> and mocked <code>ExecutionContext</code> directly and it makes no difference (and the latter is also marked as <code>@internal</code>).</p>
<p>I am sure there is a really simple solution but I have been going around in circles, and everything I find when searching is basically doing the same thing just with PHPUnit's createMock (which at this rate I may just do...)</p>
",https://stackoverflow.com/questions/63473271/unit-testing-a-custom-symfony-constraint,"['php', 'unit-testing', 'symfony', 'mockery']",2398,True,7,1
"Unit testing, mocking and traits in rust","<p>Iam current building a application which heavy relies on File IO, so obviously lots of parts of my code have <code>File::open(file)</code>.</p>
<p>Doing some integration tests are ok, I can easily set folders to load file and scenarios needed for it.</p>
<p>The problem comes whatever I want to unit tests, and code branches. I know there is lots of mocking libraries out there that claim to mocks, but i feel my biggest problem is code design itself.</p>
<p>Let's say for instance, I would do the same code in any object oriented language (java in the example), i could write some interfaces, and on tests simple override the default behavior I want to mock, set the a fake <code>ClientRepository</code>, whatever reimplemented wih a fixed return, or use some mocking framework, like mockito.</p>
<pre class=""lang-java prettyprint-override""><code>
public interface ClientRepository {
   Client getClient(int id)
}

public class ClientRepositoryDB {
   
  private ClientRepository repository;
  
  //getters and setters

  public Client getClientById(int id) {
    Client client = repository.getClient(id);

    //Some data manipulation and validation
  }
}

</code></pre>
<p>But i couldn`t manage to get the same results in rust, since we endup mixing data with behavior.</p>
<p>On the <a href=""https://doc.rust-lang.org/1.33.0/book/ch15-05-interior-mutability.html#a-use-case-for-interior-mutability-mock-objects"" rel=""noreferrer"">RefCell documentation</a>, there is a similar example with the one I gave on java. Some of answers points to traits, <a href=""https://stackoverflow.com/questions/61941650/how-do-i-create-a-mock-function-in-rust"">clojures</a>, <a href=""https://klau.si/blog/mocking-in-rust-with-conditional-compilation/"" rel=""noreferrer"">conditional compiliation</a></p>
<p>We might come with some scenarios in test, first one a public function in some mod.rs</p>
<pre class=""lang-rust prettyprint-override""><code>

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SomeData {
    pub name: Option&lt;String&gt;,
    pub address: Option&lt;String&gt;,
}


pub fn get_some_data(file_path: PathBuf) -&gt; Option&lt;SomeData&gt; {
    let mut contents = String::new();


    match File::open(file_path) {
        Ok(mut file) =&gt; {
            match file.read_to_string(&amp;mut contents) {
                Ok(result) =&gt; result,
                Err(_err) =&gt; panic!(
                    panic!(&quot;Problem reading file&quot;)
                ),
            };
        }
        Err(err) =&gt; panic!(&quot;File not find&quot;),
    }
    
    // using serde for operate on data output
    let some_data: SomeData = match serde_json::from_str(&amp;contents) {
        Ok(some_data) =&gt; some_data,
        Err(err) =&gt; panic!(
            &quot;An error occour when parsing: {:?}&quot;,
            err
        ),
    };

    //we might do some checks or whatever here
    Some(some_data) or None
}


mod test {

    use super::*;
    
    #[test]
    fn test_if_scenario_a_happen() -&gt; std::io::Result&lt;()&gt; {
       //tied with File::open
       let some_data = get_some_data(PathBuf::new);

        assert!(result.is_some());

        Ok(())
    }


    #[test]
    fn test_if_scenario_b_happen() -&gt; std::io::Result&lt;()&gt; {
       //We might need to write two files, and we want to test is the logic, not the file loading itself
       let some_data = get_some_data(PathBuf::new);

        assert!(result.is_none());

        Ok(())
    }
}
</code></pre>
<p>The second the same function becoming a trait and some struct implement it.</p>
<pre class=""lang-rust prettyprint-override""><code>


#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SomeData {
   pub name: Option&lt;String&gt;,
   pub address: Option&lt;String&gt;,
}

trait GetSomeData {
   fn get_some_data(&amp;self, file_path: PathBuf) -&gt; Option&lt;SomeData&gt;;
}

pub struct SomeDataService {}

impl GetSomeData for SomeDataService {
   fn get_some_data(&amp;self, file_path: PathBuf) -&gt; Option&lt;SomeData&gt; {
       let mut contents = String::new();

       match File::open(file_path) {
           Ok(mut file) =&gt; {
               match file.read_to_string(&amp;mut contents) {
                   Ok(result) =&gt; result,
                   Err(_err) =&gt; panic!(&quot;Problem reading file&quot;),
               };
           }
           Err(err) =&gt; panic!(&quot;File not find&quot;),
       }
       // using serde for operate on data output
       let some_data: SomeData = match serde_json::from_str(&amp;contents) {
           Ok(some_data) =&gt; some_data,
           Err(err) =&gt; panic!(&quot;An error occour when parsing: {:?}&quot;, err),
       };

       //we might do some checks or whatever here
       Some(some_data) or None
   }
}

impl SomeDataService {
   pub fn do_something_with_data(&amp;self) -&gt; Option&lt;SomeData&gt; {

       self.get_some_data(PathBuf::new())
   }
}


mod test {

   use super::*;
   
   #[test]
   fn test_if_scenario_a_happen() -&gt; std::io::Result&lt;()&gt; {
      //tied with File::open
      let service = SomeDataService{}

      let some_data = service.do_something_with_data(PathBuf::new);

       assert!(result.is_some());

       Ok(())
   }

}
</code></pre>
<p>On both examples, we have a hard time unit testing it, since we tied with <code>File::open</code>, and surely, this might be extend to any non-deterministic function, like time, db connection, etc.</p>
<p>How would you design this or any similar code to make easier to unit testing and better design?</p>
",https://stackoverflow.com/questions/63850791/unit-testing-mocking-and-traits-in-rust,"['unit-testing', 'rust', 'mocking', 'tdd', 'traits']",12874,True,14,2
Android unit testing view model that receives flow,"<p>I have a ViewModel that talks to a use case and gets a flow back i.e <code>Flow&lt;MyResult&gt;</code>. I want to unit test my ViewModel. I am new to using the flow. Need help pls. Here is the viewModel below - </p>

<pre><code>class MyViewModel(private val handle: SavedStateHandle, private val useCase: MyUseCase) : ViewModel() {

        private val viewState = MyViewState()

        fun onOptionsSelected() =
            useCase.getListOfChocolates(MyAction.GetChocolateList).map {
                when (it) {
                    is MyResult.Loading -&gt; viewState.copy(loading = true)
                    is MyResult.ChocolateList -&gt; viewState.copy(loading = false, data = it.choclateList)
                    is MyResult.Error -&gt; viewState.copy(loading = false, error = ""Error"")
                }
            }.asLiveData(Dispatchers.Default + viewModelScope.coroutineContext)
</code></pre>

<p>MyViewState looks like this -</p>

<pre><code> data class MyViewState(
        val loading: Boolean = false,
        val data: List&lt;ChocolateModel&gt; = emptyList(),
        val error: String? = null
    )
</code></pre>

<p>The unit test looks like below. The assert fails always don't know what I am doing wrong there.</p>

<pre><code>class MyViewModelTest {

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    private val mainThreadSurrogate = newSingleThreadContext(""UI thread"")

    private lateinit var myViewModel: MyViewModel

    @Mock
    private lateinit var useCase: MyUseCase

    @Mock
    private lateinit var handle: SavedStateHandle

    @Mock
    private lateinit var chocolateList: List&lt;ChocolateModel&gt;

    private lateinit var viewState: MyViewState


    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        Dispatchers.setMain(mainThreadSurrogate)
        viewState = MyViewState()
        myViewModel = MyViewModel(handle, useCase)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
        mainThreadSurrogate.close()
    }

    @Test
    fun onOptionsSelected() {
        runBlocking {
            val flow = flow {
                emit(MyResult.Loading)
                emit(MyResult.ChocolateList(chocolateList))
            }

            Mockito.`when`(useCase.getListOfChocolates(MyAction.GetChocolateList)).thenReturn(flow)
            myViewModel.onOptionsSelected().observeForever {}

            viewState.copy(loading = true)
            assertEquals(viewState.loading, true)

            viewState.copy(loading = false, data = chocolateList)
            assertEquals(viewState.data.isEmpty(), false)
            assertEquals(viewState.loading, true)
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/60713244/android-unit-testing-view-model-that-receives-flow,"['android', 'kotlin', 'junit4', 'kotlin-coroutines', 'android-mvvm']",16858,True,21,2
angular5 unit testing jasmine+karma,"<p>I have a simple method that i want to test:</p>
<p>ts file:</p>
<pre><code>policyOptions(event): void {
    this.selectedPolicy = event.srcElement[&quot;value&quot;];
    this.detectFormValueChanges();
  }
</code></pre>
<p>spec file, what i wrote:</p>
<pre><code>it(&quot;policyOptions function test case&quot;, () =&gt; {
    const mockSelectedPolicy = {&quot;value&quot;: &quot;DEFAULT&quot;};
    component.policyOptions(mockSelectedPolicy);
    component.detectFormValueChanges();
  });
</code></pre>
<p>html code:</p>
<pre><code>    &lt;input id=&quot;enable&quot; (change)=&quot;policyOptions($event)&quot; type=&quot;radio&quot; value=&quot;ENABLED&quot; name=&quot;antiPhishingSelectPolicy&quot; class=&quot;radio__input&quot; [checked]=&quot;selectedPolicy==='ENABLED'&quot;&gt;
</code></pre>
<p>I am getting error: <code>&quot;value is undefined&quot;</code>. What am i doing wrong? how can i resolve it?</p>
<p>I am new to angular, so i am finding unit testing difficult to overcome. Please help.</p>
",https://stackoverflow.com/questions/62750156/angular5-unit-testing-jasminekarma,"['angular', 'unit-testing', 'karma-jasmine']",95,True,0,1
AEM Mockito unit testing issue,"<p>Since i am new to Mockito and AEM model java. I have a gone through some docs and wrote my first Mockito file for AEM Model java. In my code i've not see any errors, but while running i am not getting success and can't complete the code coverage 100%. Can anyone correct/help me to fix my code[given sample java with respective mockito file] </p>

<p><strong>Java File:</strong>  </p>

<pre><code>import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
@Model(adaptables = SlingHttpServletRequest.class)
public class AccordionModel {
    private final static Logger log = LoggerFactory.getLogger(AccordionModel.class);
    @SlingObject
    private SlingHttpServletRequest request;
    @Inject
    public ResourceResolverService resolverService;
    private Resource resource;
    public List &lt; Accordion &gt; accordionList = new ArrayList &lt; Accordion &gt; ();
    @PostConstruct
    protected void init() throws LoginException, JSONException {
        log.info(""AccordionModel init method Start"");
        resource = request.getResource();
        final ValueMap configurationOptionProperties = resource.getValueMap();
        log.debug(""iconfigurationOptionProperties is "" + configurationOptionProperties);
        String count = configurationOptionProperties.get(""count"", String.class);
        if (count != null) {
            for (int i = 1; i &lt;= Integer.valueOf(count); i++) {
                Accordion accordion = new Accordion();
                String title = configurationOptionProperties.get(""title"" + i, String.class);
                String rte = configurationOptionProperties.get(""rte"" + i, String.class);
                accordion.setTitle(title);
                accordion.setRte(rte);
                accordionList.add(accordion);
            }
        }
        log.info(""AccordionModel init method End"");
    }
    public List &lt; Accordion &gt; getAccordionList() {
        return accordionList;
    }
}
</code></pre>

<p><strong>Mockito code</strong></p>

<pre><code>import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
@RunWith(MockitoJUnitRunner.class)
public class AccordionModelTest {
    @InjectMocks
    private AccordionModel accordionModel;
    @Mock
    Resource resource;
    @Mock
    SlingHttpServletRequest request;
    @Mock
    ResourceResolverService resourceResolverService;
    @Mock
    ValueMap valuemap;
    public List &lt; Accordion &gt; accordionList = new ArrayList &lt; Accordion &gt; ();
    String count = ""6"";
    //max count, based on this count loop execute and get/set into the list  
    @Before
    public void setUp() throws Exception {
        when(request.getResource()).thenReturn(resource);
        when(resource.getValueMap()).thenReturn(valuemap);
    }
    @Test
    public void shouldReturnNullWhenPropertyIsNull() throws LoginException, JSONException {
        when(valuemap.get(""count"", String.class)).thenReturn(null);
        accordionModel.init();
        assertEquals(accordionModel.getAccordionList(), null);
    }
    @Test
    public void shouldReturnWhenPropertyNotNull() throws LoginException, JSONException {
        when(valuemap.get(""count"", String.class)).thenReturn(""count"");
        accordionModel.init();
        assertEquals(accordionModel.getAccordionList(), count);
    }
}
</code></pre>

<p><strong>Errors</strong> in program its showing line--> accordionModel.init();</p>

<pre><code>    java.lang.NumberFormatException: For input string: ""count""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)
    at com..services.sling.models.AccordionModel.init(AccordionModel.java:44) at   
    com..services.sling.models.AccordionModelTest.
    shouldReturnWhenPropertyNotNull(AccordionModelTest.java:55)

    java.lang.AssertionError: expected:&lt;[]&gt; but was:&lt;null&gt;
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:118)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at com..services.sling.models.AccordionModelTest.
    shouldReturnNullWhenPropertyIsNull(AccordionModelTest.java:53)
</code></pre>
",https://stackoverflow.com/questions/59824254/aem-mockito-unit-testing-issue,"['junit', 'mockito', 'aem', 'sling-models']",2283,True,0,1
CMake unit testing - Unresolved external symbol,"<p>I am rather new to C++ and CMake. I'm trying to make a library, and I'm getting the errors when I try to run my unit tests. From my research I've already gathered what the &quot;Unresolved external symbol&quot; errors mean, but I'm unable to figure out how to fix it.</p>
<p>Here's my project structure:</p>
<pre><code>lib
  glfw - GLFW source folder
src
  ogl-renderer.cpp
  ogl-renderer.h
  CMakeLists.txt
  ...additional source files
test
  ogl-test.cpp
  ogl-test.h
  CMakeLists.txt
CMakeLists.txt
</code></pre>
<p>CMakeLists.txt:</p>
<pre><code>cmake_minimum_required (VERSION 3.8)

project(&quot;ogl-renderer&quot;)

set(GLFW_BUILD_DOCS OFF CACHE BOOL &quot;&quot; FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL &quot;&quot; FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL &quot;&quot; FORCE)

add_subdirectory (&quot;lib/glfw-3.3.2&quot;)

add_subdirectory (&quot;src&quot;)
add_subdirectory (&quot;test&quot;)

enable_testing()

add_test (ogl-renderer olg-test)
</code></pre>
<p>src/CMakeLists.txt:</p>
<pre><code>cmake_minimum_required (VERSION 3.8)

add_library (ogl-renderer &quot;engine/renderer.cpp&quot; &quot;engine/renderer.h&quot; &quot;engine/renderer.cpp&quot; &quot;engine/renderer.h&quot; &quot;engine/Window.cpp&quot; &quot;engine/Window.h&quot; &quot;engine/Shape.cpp&quot; &quot;engine/Shape.h&quot; &quot;engine/message-queue.cpp&quot; &quot;engine/message-queue.h&quot; &quot;engine/messages/window-mgmt.h&quot; &quot;engine/messages/window-mgmt.cpp&quot;)

target_link_libraries(ogl-renderer glfw)
</code></pre>
<p>test/CMakeLists.txt:</p>
<pre><code>add_executable (ogl-test &quot;ogl-test.cpp&quot; &quot;ogl-test.h&quot;)

target_link_libraries(ogl-test ogl-renderer)
</code></pre>
<p>test/ogl-test.cpp:</p>
<pre><code>#include &quot;../src/ogl-renderer.h&quot;

void testWindow() {
    NglRenderer::startRenderer();

    int windowId = NglRenderer::createWindow(&quot;Test&quot;, 640, 480);
}

int main() {
    testWindow();
}
</code></pre>
<p>Errors:</p>
<pre><code>Error   LNK2019 unresolved external symbol &quot;void __cdecl NglRenderer::startRenderer(void)&quot; (?startRenderer@NglRenderer@@YAXXZ) referenced in function &quot;void __cdecl testWindow(void)&quot; (?testWindow@@YAXXZ)  C:\Users\chansen\source\repos\ogl-renderer\out\build\x64-Debug\ogl-renderer C:\Users\chansen\source\repos\ogl-renderer\out\build\x64-Debug\ogl-test.cpp.obj 1

Error   LNK2019 unresolved external symbol &quot;int __cdecl NglRenderer::createWindow(char *,int,int)&quot; (?createWindow@NglRenderer@@YAHPEADHH@Z) referenced in function &quot;void __cdecl testWindow(void)&quot; (?testWindow@@YAXXZ) C:\Users\chansen\source\repos\ogl-renderer\out\build\x64-Debug\ogl-renderer C:\Users\chansen\source\repos\ogl-renderer\out\build\x64-Debug\ogl-test.cpp.obj 1
</code></pre>
<p>I am able to fix it by always including the .h and .cpp files in every location, but I want to figure this out the right way. I understand that I need to compile the source project into a library, then link that to the test executable, but I can't figure out how to do it correctly. I'm not even entirely certain how correct my CMakeList.txt files even are. I either guessed or copied on all these configurations.</p>
",https://stackoverflow.com/questions/62836167/cmake-unit-testing-unresolved-external-symbol,"['c++', 'cmake']",1302,True,6,1
Unit testing Chakra UI with Jest,"<p>Currently I am trying to unit test my application that is built with Create-React-App with typescript, and it is styled with chakraui. Chakrui includes a component ThemeProvider that must wrap the entire application as such.</p>
<p>This is my index.tsx 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 React from ""react"";
import ReactDOM from ""react-dom"";
import ""./index.css"";
import App from ""./App"";
import * as serviceWorker from ""./serviceWorker"";
import { ThemeProvider, CSSReset } from ""@chakra-ui/core/dist"";
import { theme } from ""@chakra-ui/core/dist"";

ReactDOM.render(
  &lt;React.StrictMode&gt;
    &lt;ThemeProvider theme={theme}&gt;
      &lt;CSSReset /&gt;
      &lt;App /&gt;
    &lt;/ThemeProvider&gt;
  &lt;/React.StrictMode&gt;,
  document.getElementById(""root"")</code></pre>
</div>
</div>
</p>
<p>For every unit test that I write, I am having to wrap the component with ThemeProvider for the test to pass:</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 { render } from ""@testing-library/react"";
import { ThemeProvider } from ""@chakra-ui/core/dist"";

import App from ""./App"";

describe(""&lt;App /&gt;"", () =&gt; {
  test(""smoke test"", () =&gt; {
    render(
      &lt;ThemeProvider&gt;
        &lt;App /&gt;
      &lt;/ThemeProvider&gt;
    );
  });
});</code></pre>
</div>
</div>
</p>
<p>But this is very verbose, and must be done for <em>every</em> test that I write. Is there a way to do this just once in each <code>.test.tsx</code> file?</p>
",https://stackoverflow.com/questions/63855604/unit-testing-chakra-ui-with-jest,"['reactjs', 'jestjs', 'react-testing-library']",8317,True,5,2
Unit testing validation through MediatR PipelineBehavior,"<p>I'm using FluentValidation and MediatR PipelineBehavior to validate the CQRS requests. How should I test this behavior in my unit tests?</p>

<ol>
<li><p>Use the <a href=""https://docs.fluentvalidation.net/en/latest/testing.html"" rel=""noreferrer"">test extensions</a> of FluentValidation and I test only the rules.</p>

<pre><code>[Theory]
[InlineData(null)]
[InlineData("""")]
[InlineData(""   "")]
public void Should_have_error_when_name_is_empty(string recipeName)
{
    validator.ShouldHaveValidationErrorFor(recipe =&gt; recipe.Name, recipeName);
}
</code></pre></li>
<li><p>Manually validate the request in the unit test</p>

<pre><code>[Theory]
[InlineData("""")]
[InlineData(""  "")]
public async Task Should_not_create_recipe_when_name_is_empty(string recipeName)
{
    var createRecipeCommand = new CreateRecipeCommand
    {
        Name = recipeName,
    };

    var validator = new CreateRecipeCommandValidator();
    var validationResult = validator.Validate(createRecipeCommand);
    validationResult.Errors.Should().BeEmpty();
}
</code></pre></li>
<li><p>Initialize the PipelineBehavior</p>

<pre><code>[Theory]
[InlineData("""")]
[InlineData(""  "")]
public async Task Should_not_create_recipe_when_name_is_empty(string recipeName)
{
    var createRecipeCommand = new CreateRecipeCommand
    {
        Name = recipeName
    };

    var createRecipeCommandHandler = new CreateRecipeCommand.Handler(_context);

    var validationBehavior = new ValidationBehavior&lt;CreateRecipeCommand, MediatR.Unit&gt;(new List&lt;CreateRecipeCommandValidator&gt;()
    {
        new CreateRecipeCommandValidator()
    });

    await Assert.ThrowsAsync&lt;Application.Common.Exceptions.ValidationException&gt;(() =&gt; 
        validationBehavior.Handle(createRecipeCommand, CancellationToken.None, () =&gt;
        {
            return createRecipeCommandHandler.Handle(createRecipeCommand, CancellationToken.None);
        })
    );
}
</code></pre></li>
</ol>

<p>Or should I use more of these?</p>

<p>The ValidationBehavior class:</p>

<pre><code>public class ValidationBehavior&lt;TRequest, TResponse&gt; : IPipelineBehavior&lt;TRequest, TResponse&gt;
    where TRequest : IRequest&lt;TResponse&gt;
{
    private readonly IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; _validators;

    public RequestValidationBehavior(IEnumerable&lt;IValidator&lt;TRequest&gt;&gt; validators)
    {
        _validators = validators;
    }

    public Task&lt;TResponse&gt; Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate&lt;TResponse&gt; next)
    {
        var context = new ValidationContext(request);

        var failures = _validators
            .Select(v =&gt; v.Validate(context))
            .SelectMany(result =&gt; result.Errors)
            .Where(f =&gt; f != null)
            .ToList();

        if (failures.Count != 0)
        {
            throw new ValidationException(failures);
        }

        return next();
    }
}
</code></pre>
",https://stackoverflow.com/questions/60687927/unit-testing-validation-through-mediatr-pipelinebehavior,"['c#', 'unit-testing', 'cqrs', 'fluentvalidation', 'mediatr']",6914,True,5,1
Koin DI Android Unit testing ViewModel,"<p>I use Koin DI in my app, and everything works fine. I have injected viewModels without no issue.</p>
<p>Eg, I have a calcViewModel with function:</p>
<pre><code>class CalcViewModel(): ViewModel() {
    fun calculateNumber(): Int{
        var a = 5 + 3
        return a
    }
}
</code></pre>
<p>And in the app I use it like this:</p>
<pre><code>class Application : Application() {
    override fun onCreate() {
        super.onCreate()

        startKoin {
        // androidContext(this@MyApp)
        androidLogger(Level.DEBUG)
        androidContext(this@Application)
        modules(
            listOf(
                myModule
            )
        )
    }
</code></pre>
<p>And in my appModule file:</p>
<pre><code>val myModule= module {
    viewModel { CalcViewModel() }
}
</code></pre>
<p>And in the app, whenever I need my viewModel instance, I just use:</p>
<pre><code>private val calcViewModel by viewModel&lt;CalcViewModel&gt;()
</code></pre>
<p>And as I said, everything works perfectly but when I try to write a simple unit test for this function</p>
<pre><code>fun calculateNumber(): Int{
        var a = 5 + 3
        return a
}
</code></pre>
<p>from the view model I have null pointer.</p>
<p>This is the test Class I tried</p>
<pre><code>class CalcViewModelTest: KoinTest{

val calcViewModel:CalcViewModel by inject()

@Before
fun setup() {

    startKoin {
        module { single { myModule} }
      
    }
}

@Test
fun calculateNumber(){
    val result = calcViewModel.calculateNumber()  // here I get that error when trying to access calcViewModel var
    Assert.assertEquals(result,8)
}

@After
fun tearDown() {
    stopKoin()
}

}
</code></pre>
<p>And everytime I get this error when I try to run my unit test:</p>
<pre><code>org.koin.core.error.NoBeanDefFoundException: No definition found for 
class:'com.package.CalcViewModel'. Check your definitions!
</code></pre>
<p>Also if I use the same way to fetch the viewModel in test class like in the app:</p>
<pre><code>val calcViewModel by viewModel&lt;CalcViewModel&gt;()
</code></pre>
<p>It uses a different constructor that asks for 3 params (class, owner, scope)</p>
<p>I also imported in the gradle:</p>
<pre><code>testImplementation &quot;org.koin:koin-androidx-viewmodel:$koin_version&quot;
testImplementation &quot;org.koin:koin-test:$koin_version&quot;
</code></pre>
<p>Did anyone tried to write unit tests with Koin and using viewModels ?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/63756158/koin-di-android-unit-testing-viewmodel,"['android', 'unit-testing', 'koin']",2150,True,3,2
RxJS - Unit testing mergeMap inner Observable,"<p>I have the following code:</p>

<pre><code>  createAsset(asset: Asset): void {
    this._assetsService.uploadFile()
    .pipe(
      mergeMap(_ =&gt; this._assetsService.createAsset({
        ...asset,
        extension: 'png'
      })),
      take(1)
    )
    .subscribe(_ =&gt; {}, _ =&gt; console.error(_));
  }
</code></pre>

<p>And I would like to ensure that whenever this function is called, and it calls <code>createAsset</code> with the right parameters.</p>

<p>I did write a UT using <code>Karma</code> and <code>Jasmine</code>:</p>

<pre><code>it('...', async (async () =&gt; {
    const assetsService = TestBed.inject(AssetsService);
    const uploadSpy = spyOn(assetsService, 'uploadFile').and.returnValue(of());
    const createSpy = spyOn(assetsService, 'createAsset').and.returnValue(of());

    const extension = 'png';

    const asset = {
      name: 'name',
      extension: null
    };

    component.createAsset(asset);

    await fixture.whenStable();
    expect(uploadSpy).toHaveBeenCalled();
    expect(createSpy).toHaveBeenCalledWith({...asset, extension}); // Error : This is never called
  }));
</code></pre>

<p>The inner obversable from the <code>mergeMap</code> <code>createSpy</code> is never called.
Is there something I am missing ?</p>
",https://stackoverflow.com/questions/61998890/rxjs-unit-testing-mergemap-inner-observable,"['angular', 'rxjs']",1264,True,3,1
Unit testing NestJS controller with injection,"<p>I need to make an unit test for a controller who use injection with NestJS.</p>

<p>I don't know how to mock and spy this service (MyEmitter).
I need to declare it in test.controller.spec.ts inside beforeEach() but how ?</p>

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

<pre><code>import {
  Controller,
  Body,
  Post,
} from '@nestjs/common';
import {
  WebhookDto,
} from './dto/webhook.dto';
import { MyEmitter } from './test.events';
import { InjectEventEmitter } from 'nest-emitter';

@Controller()
export class TestController {
  constructor(
    @InjectEventEmitter() private readonly myEmitter: MyEmitter,
  ) {}

  @Post('webhook')
  public async postWebhook(
    @Body() webhookDto: WebhookDto,
  ): Promise&lt;void&gt; {
    ...
    this.myEmitter.emit('webhook', webhookDto);
  }
}
</code></pre>

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

<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { TestController } from './test.controller';
import EventEmitter = require('events');
import { EVENT_EMITTER_TOKEN } from 'nest-emitter';
import { MyEmitter } from './test.events';

describe('Test Controller', () =&gt; {
  let testController: TestController;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      imports: [],
      providers: [
        {
          provide: EVENT_EMITTER_TOKEN,
          useValue: {
            emit: jest.fn(),
          },
        },
      ],
      controllers: [TestController],
    }).compile();

    testController = module.get&lt;TestController&gt;(TetsController);
  });

  describe('postWebhook', () =&gt; {
    it('should send the event', async () =&gt; {
      const myEmitterSpy = jest.spyOn(myEmitter, 'emit');
      const result = await testController.postWebhook({...});
      expect(myEmitterSpy).toBeCalledTimes(1);
    });
  });
});
</code></pre>

<p>Thank you really much for your help.</p>
",https://stackoverflow.com/questions/61733060/unit-testing-nestjs-controller-with-injection,"['typescript', 'unit-testing', 'testing', 'dependency-injection', 'nestjs']",13704,True,3,2
Unit testing of BCryptPasswordEncoder hashed password,"<p>In spring 5, I am using BCryptPasswordEncoder for password hashing. My code looks like below</p>

<pre><code>@Autowired
private BCryptPasswordEncoder passwordEncoder;
</code></pre>

<p>and I am checking my code for password equals like</p>

<pre><code>String hashedPassword = userRepository.findById(101L).orElse(null).getPassword();
assertEquals(passwordEncoder.encode(""myPassword""), hashedPassword);
</code></pre>

<p>The testcase is getting failed. Does anyone have idea how to check 'assertEquals' for 'BCryptPasswordEncoder'?</p>

<p>Stackstrace:</p>

<pre><code>org.junit.ComparisonFailure: expected:&lt;$2[a$10$EulgXiN/bEwjJZc2IqRgoOyTcJWNZp0STtgY0fZv9XSIWigMHiBN2]&gt; but was:&lt;$2[y$12$Q3BUtijkUb.HdXsYbS9rCuaCcQE0/VdU2YC.N18uZB7jZ4/r0DSzO]&gt;
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.home.practice.MessageControllerTest.hello(MessageControllerTest.java:172)
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.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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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.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>
",https://stackoverflow.com/questions/60448763/unit-testing-of-bcryptpasswordencoder-hashed-password,"['java', 'spring-security', 'junit4', 'password-encryption']",3012,True,3,2
Unit testing With Jest in Node.js,"<p>I'm very new to unit testing and very excited about it. But I've uncertainty whether I should add defensive programming style or not to my production code. So, please see the following codes.</p>
<p>calclateFinalYearGPA.js (production code)</p>
<pre class=""lang-js prettyprint-override""><code>const _ = require('lodash');
const getGPAPoint = require('./getGPAPoint');

module.exports = function (gradings) {
  let totalPoint = 0;

  gradings.forEach((grading) =&gt; {
    const grade = grading.grading.grade.name;
    const point = getGPAPoint(grade);
    totalPoint += point;
  });

  const finalYearGPA = _.round(totalPoint / gradings.length, 1);

  return finalYearGPA;
};
</code></pre>
<p>The <code>gradings</code> is an array of objects which is pulled from the db, with the following structure.</p>
<pre><code>&quot;gradings&quot;: [
    {
        &quot;grading&quot;: {
            &quot;gradeId&quot;: 3,
            &quot;grade&quot;: {
                &quot;gradeId&quot;: 3,
                &quot;name&quot;: &quot;A-&quot;
            }
        }
    },
    ...
]
</code></pre>
<p>In my <code>calculateFinalYearGPA.js</code>, I loop through that array and extract <code>grading.grade.name</code> which is <code>A-</code> in the above structure, and pass it to <code>getGPAPoint</code>. It will return the decimal number.</p>
<p>So, now in my <code>calculateFinalYearGPA.test.js</code> test, I've add the following code which is test whether it fails when <code>gradings</code> is not an array.</p>
<pre class=""lang-js prettyprint-override""><code>const calculateFinalYearGPA = require('../../../utils/calculateFinalYearGPA');

describe('calculateFinalYearGPA', () =&gt; {
  it('should throw an exception if input is not an array', () =&gt; {
    const inputs = [1, 'a', null, undefined, {}];
    inputs.forEach((i) =&gt; {
      expect(() =&gt; {
        calculateFinalYearGPA(i);
      }).toThrow();
    });
  });
});

</code></pre>
<p>So, now I need to add some defensive programming code to my production code.</p>
<pre class=""lang-js prettyprint-override""><code>if (gradings.constructor !== Array)
    throw new Error(`Expected to get an array, got ${typeof gradings}.`);
</code></pre>
<p>The way I'm doing is correct? Should I test the <code>gradings</code> array has the proper structure as well? If so, I need to add some code that nothing with business logic is done but check the <code>gradings</code> array's structure. My production code will populate with that kind of code. Is it supposed to be?</p>
<p>What is the proper ways to test my <code>calculateFinalYearGPA.js</code>?</p>
",https://stackoverflow.com/questions/63643941/unit-testing-with-jest-in-node-js,"['javascript', 'node.js', 'unit-testing', 'jestjs']",426,True,3,1
Unit Testing NodeJs Controller with Axios,"<p>I have a controller and a request file that look like this, making the requests with axios(to an external API), and sending the controller response to somewhere else, my question is, how to apply Unit Testing to my controller function (getInfoById), how do I mock the axiosRequest since it's inside the controller?. I am using Jest and only Jest for testing(might need something else, but I'm not changing)</p>

<pre><code>file: axiosFile.js

  import axios from ""axios""

  export const axiosRequest = async (name) =&gt; {
    const { data } = await axios.get(""url"")
    return data
  }


file: controllerFile.js

  import { axiosRequest } from ""./axiosFile""

  export const getInfoById = async (name) =&gt; {
    try {
      const response = await axiosRequest(name)
      return { status: 200, ...response }
    } catch {
      return { status: 500, { err: ""Internal ServerError"" } }
    }
  }
</code></pre>

<p>Thanks in advance.
PS: It's a Backend in NodeJs</p>
",https://stackoverflow.com/questions/60421207/unit-testing-nodejs-controller-with-axios,"['node.js', 'unit-testing', 'mocking', 'jestjs', 'axios']",410,False,2,1
Unit testing lazy loaded modules routing,"<p>I'm facing some problems with unit testing for routing. I've tried <a href=""https://stackoverflow.com/questions/51635273/angular-unit-testing-lazy-loaded-modules-with-routing"">this</a> solution, but this lazy loading notation is now <a href=""https://stackoverflow.com/questions/59943328/what-is-difference-between-loadchildren-import-hoge-module-ts-thenm"">deprecated</a>, so my tests are failed for some reason.
Could someone give me advice what might be wrong with my code?</p>

<p><strong><em>app-routing.module.ts</em></strong>:</p>

<pre><code>export const routes: Routes = [
{path: 'about', component: AboutComponent},
{path: 'files', loadChildren: () =&gt; import('./files/files.module').then(m =&gt; m.FilesModule)}, 
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }
</code></pre>

<p><strong><em>app-routing.module.spec.ts</em></strong>:</p>

<pre><code>describe('AppRoutingModule', () =&gt; {
   let location: Location;
   let router: Router;
   let fixture;

   beforeEach(() =&gt; {
   TestBed.configureTestingModule({
       imports:[
           RouterTestingModule.withRoutes(routes),
           HttpClientModule,
           AboutComponent,
       ],
       declarations: [
           AppComponent,
           FilesComponent,
       ],
       providers: [{provide: APP_BASE_HREF, useValue: '/'}]
   })

   router = TestBed.get(Router);
   location = TestBed.get(Location);

   fixture = TestBed.createComponent(AppComponent);
   router.initialNavigation();
   });

   it('should navigate to files', fakeAsync(() =&gt; {
       const loader = TestBed.get(NgModuleFactoryLoader);
       loader.stubbedModules = {lazyModule : FilesModule }

       router.resetConfig([
           {path: 'files', loadChildren: 'lazyModule'},
       ]);

       router.navigate(['files']);
       tick(50);
       fixture.detectChanges();

       expect(location.path()).toBe('/files');
   }));
});

</code></pre>

<p>Thank you!</p>
",https://stackoverflow.com/questions/60262547/unit-testing-lazy-loaded-modules-routing,"['angular', 'typescript', 'unit-testing', 'jasmine', 'lazy-loading']",4898,True,2,2
Unit testing a controller throwing exception,"<p>I have a controller with the following signature:</p>
<pre><code>public CustomerTypeController(
    IHttpContextAccessor accessor,
    IPrincipalProvider provider,
    IMapper mapper, 
    ILogger&lt;CustomerTypeController&gt; logger,
    ICustomerTypeService customerTypeService)
{ }
</code></pre>
<p>For now my <code>Theory</code> looks like this:</p>
<pre><code>[Theory, AutoMoqData]
public void GetWhenHasCustomerTypesShouldReturnOneCustomerType(
    IFixture fixture,
    [Frozen] Mock&lt;ICustomerTypeService&gt; service,
    CustomerTypeController sut)
{
    //Arrange
    var items = fixture.CreateMany&lt;Model.CustomerType&gt;(3).ToList();

    //Act
    var result = sut.Get(1);

    //Assert
    Assert.IsType&lt;OkResult&gt;(result);
}
</code></pre>
<p>When I run this test as-is, I get the following exception:</p>
<blockquote>
<p>AutoFixture.ObjectCreationExceptionWithPath : AutoFixture was unable to create an instance from Microsoft.AspNetCore.Mvc.ModelBinding.BindingInfo because creation unexpectedly failed with exception. Please refer to the inner exception to investigate the root cause of the failure.</p>
</blockquote>
<blockquote>
<p>Inner exception messages:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
System.ArgumentException: The type 'System.Object' must implement 'Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinder' to be used as a model binder. (Parameter 'value')</p>
</blockquote>
<p>What am I doing wrong, and how do I solve the problem?</p>
",https://stackoverflow.com/questions/64602206/unit-testing-a-controller-throwing-exception,"['c#', 'asp.net-core', 'moq', 'xunit.net', 'autofixture']",1923,True,2,1
Unit testing of OAuth on Flask,"<p>I'm new to coding and I feel really stuck. I decided to unit test my micro Flask app. I use &quot;Google sign in&quot; to authenticate my users, but I'm not able to get through the Google authentication and assert what is really on the page. I have no idea if I need to mock, play with the session or application context.</p>
<p>Here is the code for authentication process:</p>
<pre><code>def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = dict(session).get('profile', None)
        if user is not None:
            email = session['profile']['email']
        else:
            email = None
        if user:
            return f(*args, **kwargs)

        return render_template('login.html', email=email)

    return decorated_function

@app.route('/login/')
def login():
    google = oauth.create_client('google')  # create the google oauth client
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)

@app.route('/authorize')
    def authorize():
        google = oauth.create_client('google')  # create the google oauth client
        token = google.authorize_access_token()  # Access token from google (needed to get user info)
        resp = google.get('userinfo')  # userinfo specificed in the scrope
        user_info = resp.json()
        # Loading and cleaning all user emails
        auth_users = db.session.query(users.email).all()
        auth_users = [str(i).strip(&quot;(),'&quot;) for i in auth_users]
        # Checking if user is in the list
        if user_info['email'] in auth_users:
            flash(&quot;Boli ste úspešne prihlásený.&quot;, category=&quot;success&quot;)
        else:
            flash(&quot;Nemáte práva na prístup.&quot;, category=&quot;primary&quot;)
            return redirect('/')
        session['profile'] = user_info
        # make the session pernament so it keeps existing after broweser gets closed
        session.permanent = True
        return redirect('/')
</code></pre>
<p>The test structure look like this:</p>
<pre><code>class Uvo_page(unittest.TestCase):

    def setUp(self):
        self.client = app.test_client(self)
        self.user_info = {'email': 'xxx'}
        self.auth_users = ['xxx', 'yyy']

   # UVO page shows results
    def test_uvo_page_show_results(self):
        response = self.client.get('/show/1',
                                   content_type='html/text',
                                   follow_redirects=True)
        test_string = bytes('Sledované stránky', 'utf-8')
        self.assertTrue(test_string in response.data)
</code></pre>
<p>I thought that by defining the &quot;user_info&quot; it will be used for authentication evaluation. Instead of it it does not continue to &quot;/authorize&quot; and authentication, but stays on the login page.</p>
",https://stackoverflow.com/questions/65499920/unit-testing-of-oauth-on-flask,"['flask', 'oauth', 'google-signin']",263,False,3,0
Fortran Unit Testing with Visual Studio,"<p><strong>Dear all</strong>,</p>

<p>I tried to find any existing documentation about Fortran and <strong>Unit testing</strong> in Visual Studio but couldn't find any.
Do you have experience with Unit Testing for Fortran, can you recommend some good tutorials or books for that topic? The tools need to integrate into the Visual Studio 19 environment and I would love to use the built in Test-Explorer. (I use the Intel Compiler, but that should not matter for testing, right?)</p>

<p>best regards,</p>
",https://stackoverflow.com/questions/60973769/fortran-unit-testing-with-visual-studio,"['visual-studio', 'unit-testing', 'fortran']",480,True,3,2
Unit testing button with routerLink directive,"<p>I have a simple static view that I would like to write tests for:</p>

<pre><code>&lt;div class=""landing-page""&gt;
 &lt;app-cover&gt;
   &lt;app-stack [large]=""true""&gt;
     &lt;app-center&gt; 
       &lt;img src=""assets/images/logo.svg"" /&gt;
     &lt;/app-center&gt;
     &lt;app-center&gt;
       &lt;p&gt;
         Try matching the employee to their photo.
       &lt;/p&gt;
     &lt;/app-center&gt;
     &lt;app-center&gt;
       &lt;app-button routerLink=""namegame""&gt;
         Play!
       &lt;/app-button&gt;
     &lt;/app-center&gt;
   &lt;/app-stack&gt;
 &lt;/app-cover&gt;
&lt;/div&gt;
</code></pre>

<p>I was able to make assertions that the text of the <code>&lt;p&gt;</code> tag and the <code>&lt;button&gt;</code> are accurate easily. However, I am having trouble writing a unit test for the button behavior, e.g. when I click on the button I get navigated to the <code>/namegame</code> route. </p>

<p>The message I see from Karma is really confusing:</p>

<pre><code>Chrome 83.0.4103.106 (Mac OS 10.15.5) NamegameComponent navigates to /namegame when the ""Play"" 

button is clicked FAILED
Expected spy navigateByUrl to have been called with:
 [ '/namegame', &lt;jasmine.anything&gt; ]
but actual calls were:
 [ /namegame, Object({ skipLocationChange: false, replaceUrl: false, state: undefined }) ].
Call 0:
 Expected $[0] = /namegame to equal '/namegame'.
</code></pre>

<p>Test code:</p>

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

describe('NamegameComponent', () =&gt; {
 let component: LandingPageComponent;
 let fixture: ComponentFixture&lt;LandingPageComponent&gt;;
 let router: Router;

 beforeEach(async(() =&gt; {
   TestBed.configureTestingModule({
     imports: [RouterTestingModule.withRoutes([])],
     declarations: [
       LandingPageComponent,
       CenterComponent,
       CoverComponent,
       StackComponent,
       ButtonComponent,
     ],
   }).compileComponents();
 }));

 beforeEach(() =&gt; {
   fixture = TestBed.createComponent(LandingPageComponent);
   component = fixture.componentInstance;
   router = TestBed.inject(Router);
   fixture.detectChanges();
 });

 // ... other tests ...

 it('navigates to /namegame when the ""Play"" button is clicked', () =&gt; {
   const navSpy = spyOn(router, 'navigateByUrl');
   const button = fixture.nativeElement.querySelector('app-button');
   button.click();
   expect(navSpy).toHaveBeenCalledTimes(1);
   expect(navSpy).toHaveBeenCalledWith(`/namegame`, jasmine.anything());
 });
});
</code></pre>

<p>Any ideas why the assertion doesn't match? Is there something wrong with the quoting?</p>
",https://stackoverflow.com/questions/62436030/unit-testing-button-with-routerlink-directive,['angular'],826,True,3,2
Unit Testing class with IStringLocalizer&lt;T&gt;,"<p>I have a class with a constructor, that gets an <code>IStringLocalizer&lt;T&gt;</code> injected.</p>

<pre><code>public MailBuilder(IStringLocalizer&lt;MailTexte&gt; stringLocalizer)
{ ... }
</code></pre>

<p>I'm trying to setup the fake of the string localizer:</p>

<pre><code>A.CallTo(() =&gt; this.stringLocalizer[""ConfirmationMailTitel""]).Returns(subject);
</code></pre>

<p>But I get the message </p>

<blockquote>
  <p>IReturnValueArgumentValidationConfiguration LocalizedString does not contain a definition for 'Returns'</p>
</blockquote>

<p>The interfact of the IStringLocalizer looks like this:</p>

<pre><code>LocalizedString this[string name] { get; }
</code></pre>

<p>How can I setup this indexer correctly in FakeItEasy?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/61116490/unit-testing-class-with-istringlocalizert,"['c#', '.net', 'unit-testing', 'fakeiteasy']",1239,True,2,1
"Unit testing streams in node.js, jasmine","<p>I have a promise that calls an HTTP get, to retrieve ana csv file, this HTTP returns me a response that I can use as a stream, I piping the response through a csv parser, and thought another func that is a writable stream, and then I listen toa some events.</p>

<p>But my problem is testing this, my problem is that I am not able to simulate the call to the events, I don't know how to reach the codes inside the finish and error.</p>

<p>Here is the snippet that retrieves a file and pipe the response:</p>

<pre><code>return new Promise((resolve, reject) =&gt; {
    https.get(url, async response =&gt; {
      response
        .pipe(this.csvParser)
        .pipe(crazyfunc)
        .on(""finish"", () =&gt; {
          logger.info(""File process finished"")
          resolve()
        })
        .on(""error"", (err: Error) =&gt; {
          if (err) {
            reject(err)
          }
        })
      resolve()
    })
  })
</code></pre>

<p>And here my .spec file, I mocking this call as follows:</p>

<pre><code>const response = {
    pipe: () =&gt; { },
    on: () =&gt; { }
};

beforeEach(async () =&gt; {
    spyOn(response, 'pipe').and.returnValue(response)
    spyOn(response, 'on').and.returnValue(response)
});

spyOn(https, 'get').and.callFake((url, func) =&gt; func(response))
</code></pre>
",https://stackoverflow.com/questions/61121812/unit-testing-streams-in-node-js-jasmine,"['node.js', 'unit-testing', 'jasmine']",1006,True,2,1
Angular Unit Testing - stub complex object,"<p>In my unit tests, I have to create stubs that have a large number of properties.</p>

<p>So I would have an interface like this:</p>

<pre><code>interface Person {
  id: string;
  name: string;
  age: number
  ...
}
</code></pre>

<p>Then I will have to create an object that implements this interface and pass some values to each property.
Doesn't Jasmine have a function that receives an interface and returns an object with default values?</p>

<p>In the example above, I would get: </p>

<pre><code>const stub: Person = createStubObj&lt;Person&gt;();
stub.id // """"
stub.name // """"
stub.getAge // 0
</code></pre>

<p>I did some research but didn't found anything useful.</p>

<p><strong>createSpyObj</strong> doesn't seem to help me because I don't have any functions that I want to spy on. The object only has properties.</p>

<p>This case can happen when an HTTP request returns a complex object (many properties, nested properties). I'm wondering how can I mock that object in that case, without needing to specify a value for each property.</p>

<p>Something similar to what this library is doing: <a href=""https://www.npmjs.com/package/ts-auto-mock#usage"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/ts-auto-mock#usage</a></p>

<p>I'm wondering if this can be achieved in Jasmine as well or if there is a better approach</p>
",https://stackoverflow.com/questions/61538150/angular-unit-testing-stub-complex-object,"['angular', 'jasmine', 'karma-jasmine', 'angular-test']",2635,True,2,1
Q# unit testing to check phase,"<p>I want to test a phase oracle by testing if the phase of qubit flipped.
I tried to do it by</p>
<pre><code>AssertQubitIsInStateWithinTolerance((Complex(0., 0.), Complex(-1., 0.)), qubit, 1e-5);
</code></pre>
<p>But it doesn't really check the phase because the same input also worked for the test without phase</p>
<pre><code>AssertQubitIsInStateWithinTolerance((Complex(0., 0.), Complex(1., 0.)), qubit, 1e-5);
</code></pre>
<p>Is there a way to use unit tests to check the phase of qubit (or of the entire register)?</p>
<p>Thanks for the help.</p>
",https://stackoverflow.com/questions/63097579/q-unit-testing-to-check-phase,"['unit-testing', 'quantum-computing', 'q#']",64,True,2,1
Unit Testing Postgres db connection golang,"<p>I am expected to have 80% test coverage even for pushing the basic project structure. I am a bit confused how do I write unit tests for the following code to Connect to postgres db and ping postgres for health check. Can someone help me please.</p>
<pre><code>var postgres *sql.DB

// ConnectToPostgres func to connect to postgres
func ConnectToPostgres(connStr string) (*sql.DB, error) {

    db, err := sql.Open(&quot;postgres&quot;, connStr)
    if err != nil {
        log.Println(&quot;postgres-client &quot;, err)
        return nil, err

    }
    postgres = db
    return db, nil

}
</code></pre>
<pre><code>// PostgresHealthCheck to ping database and check for errors
func PostgresHealthCheck() error {
    if err := postgres.Ping(); err != nil {
        return err
    }
    return nil
}
</code></pre>
<pre><code>type PostgresRepo struct {
    db *sql.DB
}
</code></pre>
<p>// NewPostgresRepo constructor</p>
<pre><code>func NewPostgresRepo(database *sql.DB) *PostgresRepo {
    return &amp;PostgresRepo{
        db: database,
    }
}
</code></pre>
",https://stackoverflow.com/questions/65187815/unit-testing-postgres-db-connection-golang,"['postgresql', 'unit-testing', 'go']",8898,True,2,2
Event Click on unit testing VUE,"<p>I can't get my <code>click</code>-event test to work.</p>

<p>I'm using a Vuetify component: <code>v-btn</code>, but my <code>click</code>-event doesn't seem to dispatch. I tried using a normal button tag, but that had the same outcome. I'm new at testing, this is actually my first run, so tips and pointer are welcome.</p>

<p>This is my component being tested:</p>

<pre class=""lang-html prettyprint-override""><code>&lt;template&gt;
  &lt;div&gt;
    &lt;div class=""marked""&gt;
      &lt;h2&gt;Clicks: {{ counter }}&lt;/h2&gt;
    &lt;/div&gt;
    &lt;v-btn @click=""addOne"" :style=""buttonStyle""&gt;Counter&lt;/v-btn&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: ""UnitTesting"",
  data() {
    return {
      counter: 0
    };
  },
  computed: {
    count() {
      return this.counter;
    },
    buttonStyle() {
      return {
        border: ""solid 2px blue"",
        background: ""black"",
        padding: ""5px 12px"",
        color: ""white"",
        borderRadius: ""8px""
      };
    }
  },
  methods: {
    addOne() {
      this.counter++;
    }
  }
};
&lt;/script&gt;
</code></pre>

<p>I have a simple test here to see if the component does mount, checks the content of the title, and tries to dispatch an event for the button, failing:</p>

<pre class=""lang-js prettyprint-override""><code>// Library
import Vue from ""vue""
import Vuetify from ""vuetify"";
// Utils
import UnitTesting from ""../UnitTesting.vue"";
import { mount, createLocalVue } from '@vue/test-utils'

const localVue = createLocalVue()
Vue.use(Vuetify);

describe(""UnitTesting.vue"", () =&gt; {
  let vuetify;
  beforeEach(() =&gt; {
    vuetify = new Vuetify()
  })

  it(""Testing UnitTesting Component"", () =&gt; {
    const wrapper = mount(UnitTesting, {
      localVue,
      vuetify,
    });

    expect(wrapper).toBeTruthy()
  });

  it(""Testing button"", () =&gt; {
    const wrapper = mount(UnitTesting, {
      localVue, vuetify
    });
    const event = jest.fn();
    const button = wrapper.find("".v-btn"");
    expect(button.text()).toContain(""Counter"")
    const title = wrapper.find("".marked"");

    expect(title.text()).toContain(""Clicks: 0"");
    button.vm.$on(""action-btn:clicked"", event);
    expect(event).toHaveBeenCalledTimes(0); 
    button.trigger(""click"");
    expect(event).toHaveBeenCalledTimes(1); 
  })
})
</code></pre>

<p>As you can see, my test breaks when it expects the <code>click</code>-event to have been dispatched:</p>

<pre class=""lang-sh prettyprint-override""><code> FAIL  src/views/__tests__/UnitTesting.spec.js
  ● UnitTesting.vue › Testing button

    expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

      37 |     expect(event).toHaveBeenCalledTimes(0);
      38 |     button.trigger(""click"");
    &gt; 39 |     expect(event).toHaveBeenCalledTimes(1);
         |                   ^
      40 |   })
      41 | })

      at Object.&lt;anonymous&gt; (src/views/__tests__/UnitTesting.spec.js:39:19)

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 2 passed, 3 total
Snapshots:   0 total
Time:        2.249 s
</code></pre>

<p>Did I do something wrong?</p>
",https://stackoverflow.com/questions/62477303/event-click-on-unit-testing-vue,"['vue.js', 'vuejs2', 'vuetify.js', 'vue-test-utils']",2128,True,2,2
Unit testing with FakeAsync in Dart,"<p>I'm kind of new to unit testing, and I am writing a unit test which uses the <a href=""https://pub.dev/packages/quiver"" rel=""nofollow noreferrer"">quiver package</a> for faking async execution. The function I am using looks something like this:</p>

<pre class=""lang-dart prettyprint-override""><code>import 'dart:async';

import 'package:quiver/testing/async.dart';
import 'package:rxdart/rxdart.dart';
import 'package:test/test.dart' as tester;

testStream&lt;MyType&gt;(
  String message, {
  Iterable expecting,
  Future&lt;void&gt; Function(BehaviorSubject) action,
  Duration waitTime,
  int skip = 1,
}) {
  tester.test(message, () {
    final _stream = BehaviorSubject&lt;MyType&gt;();
    FakeAsync().run((async) async {
      final List&lt;MyType&gt; _results = &lt;MyType&gt;[];
      final _subscription = _stream.skip(skip).listen(_results.add);
      await action?.call(_stream);

      if (waitTime != null) async.elapse(waitTime);

      _subscription.cancel();
      if (expecting != null) {
        tester.expect(_results, expecting);
      }
    });
  });
}
</code></pre>

<p>It works well on most tests I wrote, but I am having problems with a specific example due to the lack of knowledge. In the particular case I pass the action which adds a delayed future to the stream similarly like this:  </p>

<pre class=""lang-dart prettyprint-override""><code>testStream&lt;int&gt;(
  'Just a basic message',
  expecting: [1],
  action: (stream) async =&gt;
       Future.delayed(Duration(days: 99), () =&gt; stream.add(1)),
  waitTime: Duration(seconds: 1),
);
</code></pre>

<p>If I understood it right, this test should fail, however when I run it, it passes. <strong>What am I doing wrong here</strong>?</p>

<p>Then, what should I do to make it execute the action first and then elapse the timer after the action has been called without waiting for it?</p>
",https://stackoverflow.com/questions/60549440/unit-testing-with-fakeasync-in-dart,"['unit-testing', 'asynchronous', 'dart']",730,False,2,0
Android Unit Testing dependencies not found,"<p>I am trying to write the following unit test for a function in my project</p>
<pre><code>import android.content.Context
import org.junit.Test
import androidx.test.core.app.ApplicationProvider
import com.adi_random.tracky.api.searchBook
import com.adi_random.tracky.models.GoodreadsBook
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import com.google.common.truth.Truth.assertThat

/**
 * Created by meadi on 6/27/2020.
 */
class BookFetchTest {
    /**
     * Test if the Tracy API searchBook endpoint returns the expected result and gets parsed correctly
     */
    val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()

    @Test
    fun bookFetchResultValidation() {
        val query = &quot;Dune&quot;;
        searchBook(query, context, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                TODO(&quot;Not yet implemented&quot;)
            }

            override fun onResponse(call: Call, response: Response) {
                val gson = Gson();
                val res = gson.fromJson&lt;Array&lt;GoodreadsBook&gt;&gt;(
                    response.body?.charStream(),
                    Array&lt;GoodreadsBook&gt;
                    ::class.java
                )
                assertThat(res).hasLength(20);
            }

        })
    }
}
</code></pre>
<p>When hitting run, I am getting <code>Unresolved reference</code> in <code>:app:compileDebugUnitTestKotlin</code> gradle task for the following dependencies: test (double clicking the error highlights <code>androidx.test.core.app.ApplicationProvider</code>), common ( in <code>com.google.common.truth.Truth.assertThat</code>), ApplicationProvider ( in <code>ApplicationProvider.getApplicationContext()</code>) and assertThat (in the <code>assertThat</code> call at the end of the test).</p>
<p>Here is my module <code>build.gradle</code> file:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion &quot;29.0.3&quot;
    buildFeatures {
        viewBinding true
    }
    testOptions {
        unitTests.includeAndroidResources = true
    }
    defaultConfig {
        applicationId &quot;com.adi_random.tracky&quot;
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName &quot;1.0&quot;

        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    useLibrary 'android.test.runner'
    useLibrary 'android.test.base'
    useLibrary 'android.test.mock'
}

dependencies {
    implementation fileTree(dir: &quot;libs&quot;, include: [&quot;*.jar&quot;])
    implementation &quot;org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version&quot;
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.squareup.okhttp3:okhttp:4.1.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.1.0'
    implementation 'androidx.navigation:navigation-ui-ktx:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.ext:truth:1.2.0'
    androidTestImplementation 'com.google.truth:truth:0.42'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test:core:1.2.0'

    // AndroidJUnitRunner and JUnit Rules
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'

}
</code></pre>
<p>As you can see I have those dependencies added to my gradle build file with the <code>androidTestImplementation</code> directive, so I don't understand why those errors get thrown. Does anyone have any idea? Thanks in advance!</p>
<p>Edit:Here is a screenshot of the problem:
<a href=""https://i.stack.imgur.com/OQ5vD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/OQ5vD.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/62633868/android-unit-testing-dependencies-not-found,"['android', 'unit-testing', 'kotlin', 'junit']",2156,True,2,1
unit testing angular component with @input,"<p>I have an angular component which has an @input attribute and processes this on the <code>ngOnInit</code>.  Normally when unit testing an @input I just give it as <code>component.inputproperty=value</code> but in this case I cannot since its being used on the <code>ngOnInit</code>.  How do I provide this input value in the <code>.spec.ts</code> file.  The only option I can think of is to create a test host component, but I really don't want to go down this path if there is an easier method.</p>
",https://stackoverflow.com/questions/63839249/unit-testing-angular-component-with-input,"['angular', 'unit-testing', 'input']",6820,True,2,1
Unit testing a Symfony Service Class,"<p>I am looking for some guidance on how to write a unit test for Symfony Service class. All day hunting down the web but what I mostly find is outdated questions and answers regarding old phpunit versions and old Symfony versions.</p>
<p>I am running Symfony 4 and have a service class called ApiService.php. This class connects to an external API service, I am not looking at testing this external API service but rather my own methods with a fixed dataset.</p>
<p>A very towned down version of the class is like this and lives in the folder <em>src/Service/ApiService.php</em>:</p>
<pre><code>&lt;?php

namespace App\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Uri;
use JsonException;

class ApiService
{
    /**
     * Set if test environment is enabled
     *
     * @var    bool
     * @since  1.0.0
     */
    private bool $test;

    /**
     * User key for API authentication
     *
     * @var    string
     * @since  1.0.0
     */
    private string $userKey;

    /**
     * Construct the class.
     *
     * @param   bool    $test  Set API mode
     * @param   string  $key   Set the API token
     *
     * @since   1.0.0
     */
    public function __construct(bool $test, string $key)
    {
        $this-&gt;userKey = $key;
        $this-&gt;test    = $test;
    }

    /**
     * Search companies.
     *
     * @param   array  $params     Parameters to filter the query on
     * @param   array  $companies  List of retrieved companies
     *
     * @return  array  List of companies.
     *
     * @since   1.0.0
     * @throws  JsonException
     * @throws  GuzzleException
     */
    public function getCompanies(array $params, array $companies = []): array
    {
        $results = $this-&gt;callApi('search/companies', $params);

        if (isset($results['data']['items'])) {
            $companies = array_merge(
                $companies,
                $results['data']['items']
            );
        }

        $nextLink = $results['data']['nextLink'] ?? null;

        if ($nextLink) {
            $uri = new Uri($nextLink);
            parse_str($uri-&gt;getQuery(), $params);
            $companies = $this-&gt;getCompanies($params, $companies);
        }

        return $companies;
    }

    /**
     * Call the API.
     *
     * @param   string  $destination  The endpoint to call
     * @param   array   $params       The parameters to pass to the API
     *
     * @return  array  API details.
     *
     * @since   1.0.0
     * @throws  GuzzleException|JsonException
     */
    private function callApi(string $destination, array $params = []): array
    {
        $client = new Client(['base_uri' =&gt; 'https://test.com/']);

        if ($this-&gt;test) {
            $destination = 'test' . $destination;
        }

        if ($this-&gt;userKey) {
            $params['user_key'] = $this-&gt;userKey;
        }

        $response = $client-&gt;get($destination, ['query' =&gt; $params]);

        return json_decode(
            $response-&gt;getBody()-&gt;getContents(),
            true,
            512,
            JSON_THROW_ON_ERROR
        );
    }
}
</code></pre>
<p>Here is the test class I have ended up with so far but it does not work:</p>
<pre><code>&lt;?php

namespace App\Tests\Service;

use App\Service\ApiService;
use PHPUnit\Framework\TestCase;

class ApiServiceTest extends TestCase
{
    public function testGetCompanies()
    {
        $result = ['data' =&gt; [
            'items' =&gt; [
                1 =&gt; 'first',
                2 =&gt; 'second'
            ]
        ];

        $apiService = $this-&gt;getMockBuilder(ApiService::class)
            -&gt;disableOriginalConstructor()
            -&gt;getMock();
        $apiService-&gt;method('callApi')
            -&gt;with($result);

        $result = $apiService-&gt;getCompanies([]);

       print_r($result);
    }
}
</code></pre>
<p>What I failing to understand is a couple of things.</p>
<p>First which class I should extend:</p>
<ul>
<li>TestCase</li>
<li>WebTestCase</li>
<li>KernelTestCase</li>
</ul>
<p>Second, how do I setup mock data so I am not going the external API but rather pass in the <em>$result</em> I have defined.</p>
<p>As mentioned earlier, I am not looking to test the external API but rather that my methods always behave as designed in the test given the sample data to test with.</p>
<p>Any tips will be greatly appreciated.</p>
",https://stackoverflow.com/questions/63290170/unit-testing-a-symfony-service-class,"['php', 'unit-testing', 'symfony', 'symfony4']",1272,True,2,2
RNPickerSelect unit testing (changing the value),"<p>I'm using <a href=""https://www.npmjs.com/package/react-native-picker-select"" rel=""nofollow noreferrer"">this</a> library for select/options and I'd like to unit test certain things like if there's the disabled passed to it, prevent it from changing the value.
So far, I tried something like this:<br>
Component:</p>
<pre><code>import React, {useState, useEffect} from 'react';
import {View} from 'react-native';
import RNPickerSelect from 'react-native-picker-select';

export default function PickerInput(props) {
    const [pickerItems, setPickerItems] = useState([]);
    const [selectedIndex, setSelectedIndex] = useState(0);
    const [placeholder, setPlaceholder] = useState({});
    const [error, setError] = useState(false);
    const [enabled, setEnabled] = useState(true);

    useEffect(() =&gt; {
        // loop over options prop and construct the array
        const pickerItemsArray = [];
        if (
            Array.isArray(props.options) &amp;&amp;
            props.options.length &amp;&amp;
            props.selectedIndex &gt;= 0
        ) {
            props.options.map((option, index) =&gt; {
                pickerItemsArray.push({
                    label: option,
                    value: index,
                });
            });
        }

        // push the constructed array
        {
            pickerItemsArray.length
                ? setPickerItems(pickerItemsArray)
                : setPickerItems([]);
        }

        // check if placeholder prop has a value and pass it, else pass empty object to prevent the picker from showing a placeholder
        {
            props.placeholder &amp;&amp;
                setPlaceholder({
                    label: props.placeholder,
                    value: null,
                });
        }

        {
            setError(props.error);
        }

        {
            !props.enabled ? setEnabled(false) : setEnabled(true);
        }
    }, []);

    useEffect(() =&gt; {
        props.selectedIndex &lt; 0 &amp;&amp; setSelectedIndex(-1);

        // check if selectedIndex prop is larger than the options prop and set it to the length of options prop, else pass the selectedIndex prop
        {
            Array.isArray(props.options) &amp;&amp;
            props.options.length - 1 &lt; props.selectedIndex &amp;&amp;
            props.selectedIndex &gt;= 0
                ? setSelectedIndex(props.options.length - 1)
                : setSelectedIndex(props.selectedIndex);
        }
    }, [selectedIndex]);

    const onValueChange = value =&gt; {
        if ((value === 0 || value) &amp;&amp; props.enabled) {
            setSelectedIndex(value);
            props.onValueChange(pickerItems[value].label);
        } else {
            setSelectedIndex(null);
        }
    };

    return (
        &lt;View
            testID=&quot;picker-wrapper&quot;&gt;
            &lt;RNPickerSelect
                onValueChange={value =&gt; onValueChange(value)}
                items={pickerItems}
                disabled={!enabled}
                placeholder={placeholder}
                value={selectedIndex}
            /&gt;
        &lt;/View&gt;
    );
}
</code></pre>
<p>Test:</p>
<pre><code>...
it('should not make the component change value when enabled is false', () =&gt; {
    const props = {
        placeholder: 'Select',
        options: ['testOption', 'testOption2'],
        selectedIndex: 0,
        error: false,
        enabled: false,
    };

    const newSelectedIndex = 1;

    const {queryByTestId} = render(
        &lt;PickerInput {...props} onValueChange={true} /&gt;,
    );

    const pickerWrapper = queryByTestId('picker-wrapper');

        pickerWrapper.props.children.props.value = newSelectedIndex

    expect(pickerWrapper.props.children.props.value).toBe(
        props.selectedIndex,
    );
});
</code></pre>
<p>I'm pretty new to react native and also testing, is this the best way to achieve this? Shouldn't there be a <code>fireEvent</code> where I fire the event of changing the value? I can't seem to find any. Would really appreciate someone's help.</p>
",https://stackoverflow.com/questions/62987759/rnpickerselect-unit-testing-changing-the-value,"['react-native', 'unit-testing']",1488,True,2,1
Modifying the UI when unit testing,"<p>Just curious what would be the most optimal strategy in this case:</p>

<ol>
<li>Testing Logout functionality (Header with Logout Button)</li>
<li><p>When that button is clicked, I <code>dispatch(Logout)</code>, which changes the state of my redux reducer:</p>

<p><code>#action-creator.js</code></p>

<p><code>return {
    type: LOGOUT
};</code></p>

<p><code>#reducers.js</code></p>

<p><code>case LOGOUT:
   return {
      ...state,
      loggedin: false
   }</code></p></li>
</ol>

<p>In my <code>Header</code> I have basically the following:</p>

<pre><code>const user_state = useSelector(state =&gt; state.user)
...
{ user_state.loggedin ? &lt;button&gt;Logout&lt;/button&gt; : &lt;button&gt;Login&lt;/button&gt; }
</code></pre>

<p>So in my tests, among other things, I want to test if the UI changes when the Logout button is clicked:</p>

<pre><code>test('Can logout', () =&gt; {

let store = mockStore({
    user: {
        loggedin: true // simulate logged in state to display ""Logout""
    }
});

const { getByText } = render(&lt;Provider store={store}&gt;&lt;Header/&gt;. 
&lt;/Provider&gt;);

fireEvent.click(getByText('Logout'))

// ????

});
</code></pre>

<p>Ideally, I want to test <code>expect(getByText(""Login"")).toBeTruthy();</code> but, obviously, my mocked state is not going to change... Should I initialize the test with the real store and then somehow update it so when <code>fireEvent</code> is fired, the state actually updates and the Login button is rendered.</p>
",https://stackoverflow.com/questions/61993906/modifying-the-ui-when-unit-testing,"['reactjs', 'react-redux', 'jestjs', 'react-testing-library']",264,True,2,1
EhCache 3 configuration class Unit Testing,"<p>I am using EhCache 3 with Spring and I want to do unit tests on this configuration class.</p>
<pre><code>@Configuration
@EnableCaching
public class EhCacheConfiguration {

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        return cacheManager -&gt; {
            Cache&lt;SimpleKey, Try.Success&lt;Person&gt;&gt; cache = cacheManager .getCache(&quot;cache&quot;);
            if (cache == null) {
                cacheManager .createCache(&quot;cache&quot;, jcacheConfiguration());
            }
        };
    }

    private javax.cache.configuration.Configuration&lt;SimpleKey, Try.Success&gt; jcacheConfiguration() {
        return Eh107Configuration.fromEhcacheCacheConfiguration(
                CacheConfigurationBuilder
                        .newCacheConfigurationBuilder(
                                SimpleKey.class,
                                Try.Success.class,
                                ResourcePoolsBuilder.heap(2000).offheap(25, MemoryUnit.MB)
                        )
                        .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(timeToLive)))
                        .build()
        );
    }
}   
</code></pre>
<p>I tried with this test class, but I can't mock the cacheManager inside the bean cacheManagerCustomizer.
I tried with MockBean, Mock, InjectMocks but I'm lost</p>
<pre><code>@ExtendWith(MockitoExtension.class)
class EhCacheConfigurationTest {

    private EhCacheConfiguration cut;

    @MockBean
    private CacheManager cacheManager;

    @BeforeEach
    void setUp() {
        cut = new EhCacheConfiguration();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void checkIfCacheIsCalled() {
        assertThat(cut.cacheManagerCustomizer()).isInstanceOf(JCacheManagerCustomizer.class);

        verify(cacheManager).getCache(&quot;cache&quot;);
    }
}
</code></pre>
<p>I have this error message:</p>
<pre><code>org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to verify() should be a mock but is null!
</code></pre>
<p>How I can mock the CacheManager bean inside the cacheManagerCustomizer bean ?</p>
",https://stackoverflow.com/questions/64934438/ehcache-3-configuration-class-unit-testing,"['java', 'spring', 'mockito', 'ehcache', 'ehcache-3']",309,False,1,0
angular unit testing fakeasync vs whenstable,"<p>I'm writing unit tests for an angular component.  So far when testing async code from what I have read I have two approaches</p>
<ul>
<li>Approach 1: use <code>fakeAsync</code> along with <code>tick</code></li>
<li>Approach 2: use <code>async</code> along with <code>whenStable</code></li>
</ul>
<p>I preferred the first approach <code>fakeAsync</code>, however I noticed that this does no update ngModel when I modify an input element value.  However if I use <code>whenStable</code> with <code>async</code> then it works fine.  Is this expected ? I actually thought approach 1 and approach 2 were the same from what I have read so far.</p>
",https://stackoverflow.com/questions/63555368/angular-unit-testing-fakeasync-vs-whenstable,"['angular', 'unit-testing', 'asynchronous']",105,False,1,0
Unit testing for Django login page,"<p>I'm currently trying to write unit tests for the built-in django login page, and I keep getting this error.</p>
<pre><code>ERROR: test_login_success (User.tests.LoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File &quot;C:\---------------\User\tests.py&quot;, line 74, in test_login_success
    self.assertTrue(response.data['authenticated'])
AttributeError: 'TemplateResponse' object has no attribute 'data'
</code></pre>
<p>Codes:</p>
<p>no view function because I used the Django built-in login page</p>
<pre><code>test.py
def test_login_success(self):
 
        testuser = User.objects.create_user(username = 'howdycowboy', password= 'Testing123' )
        response=self.client.post(self.login_url,{'username':'howdycowboy', 'password': 'Testing123'},format='text/html')
        #self.assertEqual(response.status_code ,302)
        self.assertTrue(response.data['authenticated'])
        
</code></pre>
<pre><code>#HTML code
{%  extends 'User/base.html' %}

{% block title %}Login{% endblock %}

{% block content %}
  &lt;h2&gt;Login&lt;/h2&gt;
  &lt;form method=&quot;post&quot;&gt;
    {% csrf_token %}
    {{ form.as_p }}
    &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;
  &lt;/form&gt;
{% endblock %}
</code></pre>
<p>I've also tried <code>self.assertEqual(response.status_code ,302)</code>
it redirects once it logs in, but for some reason the response.statuscode is 200.</p>
<pre><code>% (response.status_code, status_code)
AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302)
</code></pre>
",https://stackoverflow.com/questions/64566085/unit-testing-for-django-login-page,"['python', 'django', 'django-testing', 'django-tests', 'django-login']",216,False,1,0
Unit Testing LiveData Value with Coroutines,"<p>I want to test if the viewmodel's variable has the return value of the repository call. It is my first time using Coroutines. </p>

<p>The problem here is that my event variable is returning null here:</p>

<blockquote>
  <p>Assert.assertEquals(viewModel.event.getOrAwaitValue(), EventGame(games = games))</p>
</blockquote>

<p>My viewModel:</p>

<pre><code>class GamesViewModel(private val repository: GameRepository) : ViewModel(), CoroutineScope {
    override val coroutineContext: CoroutineContext =
        Dispatchers.Main + SupervisorJob()

    private val _event = MutableLiveData&lt;EventGame&gt;()
    val event: LiveData&lt;EventGame&gt; get() = _event


    fun listGames() = this.launch {
        val ej = withContext(Dispatchers.Default) {
            repository.listGames()
        }
        _event.postValue(ej)
    }
}
</code></pre>

<p>My unit test class</p>

<pre><code>class GamesUnitTest : KoinTest{
    lateinit var viewModel: GameViewModel

    private val g1 = Game(id = 1, data = ""01/01/2020 18:35"" ...)
    private val g2 = Game(id = 2, data = ""01/10/2020 18:35""...)
    private val games = listOf(g1, g2)

    @Mock
    lateinit var repository: GameRepository

    @get:Rule
    var coroutinesTestRule = CoroutinesTestRule()

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    @Mock
    lateinit var observer: Observer&lt;EventGame&gt;

    @After
    fun after() {
        stopKoin()
    }

    @Before
    fun before() {
        MockitoAnnotations.initMocks(this)
        viewModel = GameViewModel(repository)
    }

    @Test
    fun testListOfGames() = runBlockingTest{
        Mockito.`when`(repository.listGames()).thenReturn(EventGame(games = games))
        viewModel.event.observeForever(observer)
        viewModel.listGames()
        Assert.assertEquals(viewModel.event.getOrAwaitValue(), EventGame(games = games))

    }
}
</code></pre>

<p>--Edit2</p>

<p>I removed the GlobalScope.launch{}. The event is still null</p>

<p>I'm not sure how to fix that.</p>
",https://stackoverflow.com/questions/59843480/unit-testing-livedata-value-with-coroutines,"['android', 'mockito', 'android-lifecycle', 'android-testing', 'coroutine']",1517,False,1,1
Mock Injected Service In Unit Testing Nest.js,"<p>I would like to test my service (Location Service). In this Location Service, I inject repository and other service called GeoLocationService, but got stuck when I am trying to mock this GeoLocationService.</p>
<p>It throws me an error</p>
<pre><code>GeolocationService › should be defined

    Nest can't resolve dependencies of the GeolocationService (?). Please make sure that the argument HttpService at index [0] is available in the RootTestModule context.

</code></pre>
<p>Here is the provider's code</p>
<pre><code>@Injectable()
export class LocationService {
  constructor(
    @Inject('LOCATION_REPOSITORY')
    private locationRepository: Repository&lt;Location&gt;,

    private geolocationService: GeolocationService, // this is actually what I ma trying to mock
  ) {}

  async getAllLocations(): Promise&lt;Object&gt; {
return await this.locationRepository.find()
  }
....
}

</code></pre>
<p>Here is the test code</p>
<pre><code>describe('LocationService', () =&gt; {
  let service: LocationService;
  let repo: Repository&lt;Location&gt;;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      imports: [GeolocationModule],
      providers: [
        LocationService,
        {
          provide: getRepositoryToken(Location),
          useClass: Repository,
        },
      ],
    }).compile();

    service = module.get&lt;LocationService&gt;(LocationService);
    repo = module.get&lt;Repository&lt;Location&gt;&gt;(getRepositoryToken(Location));
  });

  it('should be defined', () =&gt; {
    expect(service).toBeDefined();
  });
});
</code></pre>
",https://stackoverflow.com/questions/65478137/mock-injected-service-in-unit-testing-nest-js,"['node.js', 'jestjs', 'nestjs']",15517,True,8,1
Automated Unit Testing - SPFX Application Customiser,"<p>I am trying to implement automated unit test cases using jest for SPFX Application customizer. But currently i could not find out any solution to mock the SPFX methods. Is there any way by which i can mock SharePoint context or the methods which return required properties.</p>
",https://stackoverflow.com/questions/60037507/automated-unit-testing-spfx-application-customiser,"['automated-tests', 'jestjs', 'office365', 'sharepoint-online']",92,False,1,0
"Kotlin enum, Companion and unit testing","<p>I have an <code>enum</code> in Kotlin with ""util"" associated functions as part of a <code>Companion</code> object and marked as <code>@JVMStatic</code> to be able to access them from java code as static methods.<br>
I would like to be able to have some unit testing for that functions.<br>
Is the approach I took bad for testing and what would be the proper approach for Kotlin and testing?</p>
",https://stackoverflow.com/questions/60990213/kotlin-enum-companion-and-unit-testing,"['unit-testing', 'kotlin', 'enums']",124,False,1,0
Unit testing NestJS Observable Http Retry,"<p>I'm making a request to a 3rd party API via NestJS's built in HttpService. I'm trying to simulate a scenario where the initial call to one of this api's endpoints might return an empty array on the first try. I'd like to use RxJS's <code>retryWhen</code> to hit the api again after a delay of 1 second. I'm currently unable to get the unit test to mock the second response however:</p>

<pre><code>it('Retries view account status if needed', (done) =&gt; {
    jest.spyOn(httpService, 'post')
      .mockReturnValueOnce(of(failView)) // mock gets stuck on returning this value
      .mockReturnValueOnce(of(successfulView));
    const accountId = '0812081208';
    const batchNo = '39cba402-bfa9-424c-b265-1c98204df7ea';
    const response =client.viewAccountStatus(accountId, batchNo);
    response.subscribe(
      data =&gt; {
        expect(data[0].accountNo)
          .toBe('0812081208');
        expect(data[0].companyName)
          .toBe('Some company name');
        done();
      },
    )
  });
</code></pre>

<p>My implementation is:</p>

<pre><code>viewAccountStatus(accountId: string, batchNo: string): Observable&lt;any&gt; {
    const verificationRequest = new VerificationRequest();
    verificationRequest.accountNo = accountId;
    verificationRequest.batchNo = batchNo;


    this.logger.debug(`Calling 3rd party service with batchNo: ${batchNo}`);

    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };

    const response = this.httpService.post(url, verificationRequest, config)
      .pipe(
        map(res =&gt; {
          console.log(res.data); // always empty
          if (res.status &gt;= 400) {
            throw new HttpException(res.statusText, res.status);
          }

          if (!res.data.length) {
            this.logger.debug('Response was empty');
            throw new HttpException('Account not found', 404);
          }

          return res.data;
        }),
        retryWhen(errors =&gt; {
          this.logger.debug(`Retrying accountId: ${accountId}`);
          // It's entirely possible the first call will return an empty array
          // So we retry with a backoff
          return errors.pipe(
            delayWhen(() =&gt; timer(1000)),
            take(1),
          );
        }),
      );

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

<p>When logging from inside the initial map, I can see that the array is always empty. It's as if the second mocked value never happens. Perhaps I also have a solid misunderstanding of how observables work and I should somehow be trying to assert against the SECOND value that gets emitted? Regardless, when the observable retries, we should be seeing that second mocked value, right? </p>

<p>I'm also getting </p>

<pre><code>: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
</code></pre>

<p>On each run... so I'm guessing I'm not calling <code>done()</code> in the right place. </p>
",https://stackoverflow.com/questions/61786244/unit-testing-nestjs-observable-http-retry,"['rxjs', 'jestjs', 'nestjs']",1811,True,1,1
Unit testing vue component containing vuetify,"<p>For example, how to trigger a change event in v-autocomplete inside your component, so that I </p>

<p>I tried something like:</p>

<pre class=""lang-js prettyprint-override""><code>import SomethingAutocomplete from ""@/components/SomethingAutocomplete.vue"";
import { shallowMount } from ""@vue/test-utils"";
import { VAutocomplete } from ""vuetify/lib"";
import { Constructor } from ""vue/types/options"";

test(""Some test"", async () =&gt; {
  const wrapper = shallowMount(SomethingAutocomplete);
  let ac = wrapper.find(&lt;Constructor&gt;VAutocomplete);
  ac.trigger(""input"");
  await wrapper.vm.$nextTick();
  ...
  &lt;handler was never called&gt;
});

</code></pre>

<p>Any hints? TIA.</p>
",https://stackoverflow.com/questions/61310492/unit-testing-vue-component-containing-vuetify,"['unit-testing', 'vue.js', 'jestjs', 'vuetify.js']",367,True,1,1
Sanic unit testing for file uploads,"<p>The below is a snippet of code that summarizes how I am posting a file to an endpoint on a Sanic app:</p>

<pre><code>from sanic import Sanic, response

class Server(object):
    def __init__(self, test=False):
        self.app = Sanic()
        self.app.add_route(self.upload, '/upload', methods=['POST'])

    async def upload(self,request):
        # Obtain some data from the request to compare md5
        md5 = request.form.get('md5')

        # Check for file
        if not request.files.get('file'):
            return {""message"":""No file selected!"",""success"":False}
        test_file = request.files.get('file')
</code></pre>

<p><strong>How can I write a unit test which is able to pass in a file, md5 etc as part of the request object?</strong> The following is what I have tried, but no luck:</p>

<pre><code>from server import Server
import unittest

class TestUpload(unittest.TestCase):
    def test_upload(self):
        app = Server(test=True).app

        upload_payload = {'upload': open('upload_file.yaml', 'rb'), 'digest': '56d5b275ab20831b22f835cc7bf9905a'}
        headers = {""content-type"": ""multipart/form-data; boundary=------sanic""}
        files = {'file': ('upload', open('upload_file.yaml', 'rb'), 'text/yaml'), 'Content-Type': 'multipart/form-data', 'Content-Disposition': 'form-data; name=""upload""; filename=""upload_file.yaml""'}

        request, response = app.test_client.post(""/upload"", data=upload_payload, headers=headers, files=files)
</code></pre>

<p>As you can see above, I have tried a variety of methods to see if the request object created using the SanicTestClient would contain the file as part of the <code>request.files</code> and the custom <code>request.form.md5</code>, but those properties are never populated on the request that the SanicTestClient creates. Any insight would be much appreciated.</p>
",https://stackoverflow.com/questions/59606576/sanic-unit-testing-for-file-uploads,"['python', 'unit-testing', 'web-services', 'python-unittest', 'sanic']",711,False,1,1
Unit testing for Spring Boot API,"<p>I'm developing a Spring Boot Web API, and I'm currently writing the required units tests.</p>

<p>I was wondering : Isn't writing the units tests (JUnit + Mockito) for the controllers sufficient ? Since the controllers are the entrypoint of my application and that all the logic that is implemented within the Service side is called from the exposed API, why do I need to write test for the Service side ?</p>
",https://stackoverflow.com/questions/61413347/unit-testing-for-spring-boot-api,"['spring-boot', 'junit', 'mockito', 'spring-boot-test']",411,True,1,2
AWS SDK Go Lambda Unit Testing,"<p>I'm trying to wrap my head around writing some unit tests for the first time ever, and I'm doing it in golang for a side project utilising aws lambda.</p>
<p>Below are two files.</p>
<p><code>main.go</code> takes an event containing an email address, and creates the user in a cognito user pool.</p>
<p><code>main_test.go</code> is supposed to mock the <code>createUser</code> function in <code>main.go</code>, but I'm getting an error when I try to run the test.</p>
<p>I've just switched my code from <a href=""https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html#golang-handler-state"" rel=""nofollow noreferrer"">instantiating the client globally</a> to using pointer receiver methods on the aws sdk interfaces after watching <a href=""http://%20%20https://www.youtube.com/watch?v=Zv-42EWBsos"" rel=""nofollow noreferrer"">this youtube video</a>.</p>
<p><strong>main.go</strong></p>
<pre><code>package main

import (
    &quot;fmt&quot;
    &quot;log&quot;
    &quot;os&quot;

    &quot;github.com/aws/aws-lambda-go/events&quot;
    &quot;github.com/aws/aws-lambda-go/lambda&quot;
    &quot;github.com/aws/aws-sdk-go/aws&quot;
    &quot;github.com/aws/aws-sdk-go/aws/awserr&quot;
    &quot;github.com/aws/aws-sdk-go/aws/session&quot;
    cidp &quot;github.com/aws/aws-sdk-go/service/cognitoidentityprovider&quot;
    cidpif &quot;github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface&quot;
    lib &quot;github.com/sean/repo/lib&quot;
)

type createUserEvent struct {
    EmailAddress string `json:&quot;email_address&quot;`
}

type awsService struct {
    cidpif.CognitoIdentityProviderAPI
}

func (c *awsService) createUser(e createUserEvent) error {
    input := &amp;cidp.AdminCreateUserInput{
        UserPoolId:             aws.String(os.Getenv(&quot;USER_POOL_ID&quot;)),
        Username:               aws.String(e.EmailAddress),
        DesiredDeliveryMediums: []*string{aws.String(&quot;EMAIL&quot;)},
        ForceAliasCreation:     aws.Bool(true),
        UserAttributes: []*cidp.AttributeType{
            {
                Name:  aws.String(&quot;email&quot;),
                Value: aws.String(e.EmailAddress),
            },
        },
    }
    _, err := c.AdminCreateUser(input)
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case cidp.ErrCodeResourceNotFoundException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeResourceNotFoundException, aerr.Error())
            case cidp.ErrCodeInvalidParameterException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeInvalidParameterException, aerr.Error())
            case cidp.ErrCodeUserNotFoundException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeUserNotFoundException, aerr.Error())
            case cidp.ErrCodeUsernameExistsException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeUsernameExistsException, aerr.Error())
            case cidp.ErrCodeInvalidPasswordException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeInvalidPasswordException, aerr.Error())
            case cidp.ErrCodeCodeDeliveryFailureException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeCodeDeliveryFailureException, aerr.Error())
            case cidp.ErrCodeUnexpectedLambdaException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeUnexpectedLambdaException, aerr.Error())
            case cidp.ErrCodeUserLambdaValidationException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeUserLambdaValidationException, aerr.Error())
            case cidp.ErrCodeInvalidLambdaResponseException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeInvalidLambdaResponseException, aerr.Error())
            case cidp.ErrCodePreconditionNotMetException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodePreconditionNotMetException, aerr.Error())
            case cidp.ErrCodeInvalidSmsRoleAccessPolicyException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeInvalidSmsRoleAccessPolicyException, aerr.Error())
            case cidp.ErrCodeInvalidSmsRoleTrustRelationshipException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeInvalidSmsRoleTrustRelationshipException, aerr.Error())
            case cidp.ErrCodeTooManyRequestsException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeTooManyRequestsException, aerr.Error())
            case cidp.ErrCodeNotAuthorizedException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeNotAuthorizedException, aerr.Error())
            case cidp.ErrCodeUnsupportedUserStateException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeUnsupportedUserStateException, aerr.Error())
            case cidp.ErrCodeInternalErrorException:
                log.Printf(&quot;[ERROR] %v, %v&quot;, cidp.ErrCodeInternalErrorException, aerr.Error())
            default:
                log.Printf(&quot;[ERROR] %v&quot;, err.Error())
            }
        } else {
            log.Printf(&quot;[ERROR] %v&quot;, err.Error())
        }
        return err
    }
    log.Printf(&quot;[INFO] Created new user %v successfully&quot;, e.EmailAddress)
    return nil
}

func (c *awsService) handler(e createUserEvent) (events.APIGatewayProxyResponse, error) {
    headers := map[string]string{&quot;Content-Type&quot;: &quot;application/json&quot;}

    err := c.createUser(e)
    if err != nil {
        resp := lib.GenerateResponseBody(fmt.Sprintf(&quot;Error creating user %v&quot;, e.EmailAddress), 404, err, headers)
        return resp, nil
    }

    resp := lib.GenerateResponseBody(fmt.Sprintf(&quot;Created new user %v&quot;, e.EmailAddress), 200, nil, headers)
    return resp, nil
}

func main() {
    c := awsService{cidp.New(session.New())}

    lambda.Start(c.handler)
}
</code></pre>
<p><strong>main_test.go</strong></p>
<pre><code>package main

import (
    &quot;os&quot;
    &quot;testing&quot;

    cidp &quot;github.com/aws/aws-sdk-go/service/cognitoidentityprovider&quot;
    cidpif &quot;github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface&quot;
)

type mockCreateUser struct {
    cidpif.CognitoIdentityProviderAPI
    Response cidp.AdminCreateUserOutput
}

func (d mockCreateUser) CreateUser(e createUserEvent) error {
    return nil
}

func TestCreateUser(t *testing.T) {
    t.Run(&quot;Successfully create user&quot;, func(t *testing.T) {
        m := mockCreateUser{Response: cidp.AdminCreateUserOutput{}}
        c := awsService{m}

        err := os.Setenv(&quot;USER_POOL_ID&quot;, &quot;ap-southeast-2_ovum4dzAL&quot;)
        if err != nil {
            t.Fatal(err)
        }

        err = c.createUser(createUserEvent{EmailAddress: &quot;user@example.com&quot;})
        if err != nil {
            t.Fatal(&quot;User should have been created&quot;)
        }
    })
}
</code></pre>
<p><strong>the error</strong></p>
<pre><code>Running tool: /usr/local/go/bin/go test -timeout 30s -run ^TestCreateUser$ github.com/sean/repo/src/create_user

--- FAIL: TestCreateUser (0.00s)
    --- FAIL: TestCreateUser/Successfully_create_user (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x60 pc=0x137c2f2]

goroutine 6 [running]:
testing.tRunner.func1.1(0x13e00c0, 0x173fd70)
    /usr/local/go/src/testing/testing.go:1072 +0x30d
testing.tRunner.func1(0xc000001b00)
    /usr/local/go/src/testing/testing.go:1075 +0x41a
panic(0x13e00c0, 0x173fd70)
    /usr/local/go/src/runtime/panic.go:969 +0x1b9
github.com/sean/repo/src/create_user.(*mockCreateUser).AdminCreateUser(0xc00000ee40, 0xc00006a200, 0xc00001e39d, 0x18, 0xc0000b24b0)
    &lt;autogenerated&gt;:1 +0x32
github.com/sean/repo/src/create_user.(*awsService).createUser(0xc000030738, 0x145bbca, 0x10, 0x18, 0x0)
    /Users/sean/code/github/sean/repo/src/create_user/main.go:39 +0x2b7
github.com/sean/repo/src/create_user.TestCreateUser.func1(0xc000001b00)
    /Users/sean/code/github/sean/repo/src/create_user/main_test.go:30 +0x10c
testing.tRunner(0xc000001b00, 0x1476718)
    /usr/local/go/src/testing/testing.go:1123 +0xef
created by testing.(*T).Run
    /usr/local/go/src/testing/testing.go:1168 +0x2b3
FAIL    github.com/sean/repo/src/create_user    0.543s
FAIL
</code></pre>
",https://stackoverflow.com/questions/65464240/aws-sdk-go-lambda-unit-testing,"['amazon-web-services', 'unit-testing', 'go', 'aws-lambda']",2093,True,1,1
Unit testing with Jest vs MQTT,"<p>I'm writing the test cases for API, using Jest and MQTT. I want to validate the response value of the message with my expected value. Currently, I cannot handle the response of function client.on. Please help me to resolve it, thanks so much</p>

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

<pre><code>    async doTest() {

        client.on('connect', async function () {
            await client.subscribe(topic + '/reply', function (err) {
                 if (!err) {
                   client.publish(topic, JSON.stringify(payload));
                 }
            });
        });

        await client.on('message', async function (topic, message) {
              // message is Buffer
              const res = await JSON.parse(message.toString());
              const { err, response } = res;
              this.result = JSON.stringify(response);
        });
}

    async getResult() {
         return this.result;
}
</code></pre>

<p>test.spec.ts</p>

<pre><code>it('should call api', async () =&gt; {
    await test.doTest();
    result = await test.getResult();
    console.log(result);
});
</code></pre>
",https://stackoverflow.com/questions/61676993/unit-testing-with-jest-vs-mqtt,"['unit-testing', 'jestjs', 'mqtt']",712,False,1,0
Unit Testing controller in laravel 8,"<p>I am very new to testing in Laravel, I'm working in laravel 8, the function that I want to test is :</p>
<p>When I run my test I get this error:</p>
<blockquote>
<p>ErrorException: Trying to get property 'id' of non-object</p>
</blockquote>
<p>Thank you for any help!</p>
",https://stackoverflow.com/questions/64685701/unit-testing-controller-in-laravel-8,"['php', 'laravel', 'phpunit', 'laravel-sanctum']",1046,True,1,1
Unit testing a PHP API client,"<p>I am writing an API client in php that sends request to an API server to get the details of a person based on his ID on the API server. The API server has a token based authentication and when queried with the correct ID and the token, the details of that person are returned as a JSON response. I am comfortable with the implementation of the class. However, when it comes to unit testing, I have not much idea about what all should be the best test cases that I should write. Unfortunately, I couldn't find any resources on the same. I have written a few test cases that validates the request parameters and the end point to query. Can anyone shed some more light on unit testing API clients?</p>
",https://stackoverflow.com/questions/63884833/unit-testing-a-php-api-client,"['php', 'api', 'unit-testing', 'phpunit', 'apiclient']",713,True,1,1
Unit Testing ASP.NET Core AAD Auth,"<p>I'm using Selenium to Unit Test an Azure AD application in ASP.NET Core MVC web app and I am looking for a better method of logging in the test user besides searching the DOM for login input elements. I'm Unit Testing in Azure DevOps so logging in with the browser UI is not an option. Any ideas?</p>
",https://stackoverflow.com/questions/63064896/unit-testing-asp-net-core-aad-auth,"['asp.net-core', 'asp.net-core-mvc', 'azure-active-directory', 'openid-connect']",627,True,1,1
Azure Unit testing with Input files,"<p>Migrating a project from TFS to Azure, and everything is working great except a few unit tests. These unit tests require input files that we previously hosted on a shared drive. Before I go down the path of mocking the data in code, is there anyway we can save the files in Azure, and reference them from our tests?</p>
",https://stackoverflow.com/questions/61483395/azure-unit-testing-with-input-files,"['c#', 'visual-studio', 'unit-testing', 'azure-devops']",428,True,1,2
Unit testing Kotlin Flows and toList(),"<p>I have this Unit test:</p>

<pre><code>@Test
    fun `should emit user repos on success`() = rule.dispatcher.runBlockingTest {
        // GIVEN
        val repo = Repo(name = ""someRepo1"", owner = RepoOwner(TEST_USERNAME), stars = 55)
        val channel = Channel&lt;Repo&gt;()
        val flow = channel.consumeAsFlow()

        doReturn(flow)
            .whenever(repository)
            .getUserRepos(TEST_USERNAME)

        // WHEN
        launch {
            channel.send(repo)
        }

        userDetailViewModel.lookupUserRepos(TEST_USERNAME)

        // THEN
        verify(userReposObserver).onChanged(listOf(repo))
    }
</code></pre>

<p>which tests this code in the view model:</p>

<pre><code>@ExperimentalCoroutinesApi
    fun lookupUserRepos(login: String) {

        viewModelScope.launch {
            val flow = userRepository.getUserRepos(login)
            _userRepos.value = flow
                .catch { _isUserReposError.value = true }
                .toList()
        }
    }
</code></pre>

<p>Debugging shows that the flow does get the <code>repo</code> but something about <code>toList()</code> breaks the test (I get test failure <code>Wanted but not invoked observer.onChanged...no interactions with this mock</code></p>

<p>Non-test works but test using <code>toList()</code> breaks. Any help is appreciated.</p>
",https://stackoverflow.com/questions/60783987/unit-testing-kotlin-flows-and-tolist,['kotlin-coroutines'],427,False,1,0
"Strapi unit testing with Jest, fails","<p>I have a Strapi api and trying to run a unit test</p>
<p>this is the error in the console I am getting</p>
<pre><code>yarn test
yarn run v1.22.5
$ jest --forceExit --detectOpenHandles
  ●  process.exit called with &quot;1&quot;

       8 |   if (!instance) {
       9 |     /** the follwing code in copied from `./node_modules/strapi/lib/Strapi.js` */
    &gt; 10 |     await Strapi().load();
         |     ^
      11 |     instance = strapi; // strapi is global now
      12 |     await instance.app
      13 |       .use(instance.router.routes()) // populate KOA routes

      at Strapi.stop (node_modules/strapi/lib/Strapi.js:263:13)
      at node_modules/strapi/lib/Strapi.js:391:16
          at async Promise.all (index 5)
      at Strapi.runBootstrapFunctions (node_modules/strapi/lib/Strapi.js:394:5)
      at Strapi.load (node_modules/strapi/lib/Strapi.js:326:5)
      at setupStrapi (tests/helpers/strapi.js:10:5)
      at Object.&lt;anonymous&gt; (tests/app.test.js:8:3)

 RUNS  tests/app.test.js
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 followed these instructions exactly.</p>
<p>How can I fix this issue?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/63776915/strapi-unit-testing-with-jest-fails,"['node.js', 'jestjs', 'strapi']",573,False,1,1
Unit testing express.js route with sinon,"<p>I am learning express and sinon (the hard way :) ). I'd like to unit test the following code:</p>

<pre><code>//  ./routers/root.js

var express = require('express');
var router = express.Router();

router
  .route('/')
  .get(function(req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.write(JSON.stringify({Application: ""NodeTours"", Version: ""2.0.0"", Host: host, Port: port}));
    res.end();
  });

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

<p>I've been trying different things without success. I'm back to the basic example. I realize it may seem like a complete newbie question but I'm clueless. Here's the latest try:</p>

<pre><code>//   ./test/test.js

var sinon = require('sinon')
var expect = require('chai').expect

describe('Routers', function() {

  context('/', function() {
    var rootRouter = require('../routers/root')
    var res = {Application: ""NodeTours"", Version: ""2.0.0"", Host: 'host', Port: 'port'};
    it('should call / router', function() {
      rootRouter.route('/').get(null, res);
      // TODO: expect...
    })
  })
})
</code></pre>

<p>It fails with:</p>

<pre><code>  Routers
    /
      1) should call / router


  0 passing (4ms)
  1 failing

  1) Routers
       /
         should call / router:
     Error: Route.get() requires a callback function but got a [object Null]
      at Route.&lt;computed&gt; [as get] (node_modules/express/lib/router/route.js:202:15)
      at Context.&lt;anonymous&gt; (test/test.js:10:29)
      at processImmediate (internal/timers.js:456:21)
</code></pre>

<p>I've tried multiple tutorials without success. I'd appreciate any pointers to how my code could be unit tested. Or how to adjust my code so unit testing is easier/possible.</p>

<p>My main app server.js file for context and reference (removed code not relevant for this question)</p>

<pre><code>//   ./server.js
// npm pacakages
var express = require('express');
var bodyParser = require('body-parser');

// app imports
var { rootRouter } = require('./routers');
// other cut out

//globals
app = express();
app.use(bodyParser.json());
app.use('/', rootRouter);
// other cut out

// Set up Mongo DB connection
// code to st up db connection

// Start server (only if connection to DB established)
var server = MongoClient(url, { useUnifiedTopology: true, poolSize: 10 }).connect().then(client =&gt; {
  const dbo = client.db(dbName);

  // some init code cut out

  // make connection available
  app.locals.dbo = dbo;

  // start server
  app = app.listen(process.env.PORT || 7777, function () {
    host = require('os').hostname();
    port = ""7777"";
    logger.verbose(""Startup: NodeTours listening at http://%s:%s"", host, port)
  });
}).catch(error =&gt; {
  logger.error(""Startup: Couldn't connect to the DB. The app will exit"")
  logger.error(""  Error: "" + error)
  process.exit();
  }
);

</code></pre>
",https://stackoverflow.com/questions/61503864/unit-testing-express-js-route-with-sinon,"['node.js', 'unit-testing', 'express', 'sinon']",989,True,1,1
Assert duplicate element in unit testing,"<p>How can I to make a unit test check that a list of object not contains a duplicate element based on some properties.</p>

<p>Here is what I tried to do:</p>

<pre><code>[Fact]
public void RecupererReferentielContactClient_CasNominal_ResultOk()
{
     // Arange
     var contactCoreService = Resolve&lt;IContactCoreService&gt;();
     int clientId = 56605;
     ICollection&lt;Personne&gt; listPersone = new List&lt;Personne&gt;();

     // Act
     WithUnitOfWork(() =&gt; listPersone = contactCoreService.RecupererReferentielDeContactClient(clientId));

      // Assert
     listPersone.ShouldSatisfyAllConditions(
            () =&gt; listPersone.ShouldNotBeNull(),
            () =&gt; listPersone.ShouldBeUnique());            
}
</code></pre>

<p>How can I make my unit test using shouldly?</p>
",https://stackoverflow.com/questions/60054115/assert-duplicate-element-in-unit-testing,"['c#', 'unit-testing', 'xunit', 'shouldly']",982,True,1,2
React unit testing const arrow function,"<p>I have the following code:</p>

<pre><code>render(){


        const nullValue = (
            &lt;span&gt;
                -
            &lt;/span&gt;
        )

        const value = (propValue) =&gt; {     //untested line
            if (propValue === null) {      //untested line
                return nullValue           //untested line
            } else {
                return (                   //untested line
                    &lt;span&gt;
                         {propValue}
                    &lt;/span&gt;
                )
            }
        }

        const percentageValue = (percentagePropValue) =&gt; {    //untested line
            if (percentagePropValue === null) {               //untested line
                return nullValue                              //untested line
            } else {
                return (                                      //untested line
                    &lt;span&gt;
                        {percentagePropValue * 100}%
                    &lt;/span&gt;
                )
            }
        }

       return (                                             //untested line
           &lt;div&gt;
              &lt;h1&gt;Object Name: {value(this.state.myObject.name)}&lt;/h1&gt;
              &lt;h2&gt;Object Percentage: {percentageValue(this.state.myObject.percentage)}&lt;/h2&gt;
           &lt;/div&gt;
       )
    }
</code></pre>

<p>The idea above is that the <code>value</code> and <code>percentageValue</code> functions use an object property as a parameter and then return a value to the user. If the value of property happens to be <code>null</code>, the value is replaced with a dash.</p>

<p>When running test coverage on the component, it says that <code>value</code> and <code>percentageValue</code> functions are not tested. I am assuming it is because of the if/else condition. What should I do in this situation? I don't really know how to deal with it.</p>
",https://stackoverflow.com/questions/61622176/react-unit-testing-const-arrow-function,"['reactjs', 'unit-testing', 'jestjs']",1394,True,0,1
routerLinkActive not working in unit testing,"<p>RouterLinkActive is not working during unit testing but It works when outside unit testing.</p>

<p>Here is HTML:</p>

<pre><code>&lt;header class=""site-tab""&gt;
  &lt;nav class=""c-tab l-wrap""&gt;
    &lt;div
      class=""c-tab__item""
      routerLink=""/companies""
      routerLinkActive=""c-tab__item--active""
    &gt;
      &lt;p class=""c-tab__text""&gt;Companies&lt;/p&gt;
    &lt;/div&gt;
    &lt;div
      class=""c-tab__item""
      routerLink=""/products""
      routerLinkActive=""c-tab__item--active""
    &gt;
      &lt;p class=""c-tab__text""&gt;Products&lt;/p&gt;
    &lt;/div&gt;
    &lt;div
      class=""c-tab__item""
      routerLink=""/invoices""
      routerLinkActive=""c-tab__item--active""
    &gt;
      &lt;p class=""c-tab__text""&gt;Invoices&lt;/p&gt;
    &lt;/div&gt;
  &lt;/nav&gt;
&lt;/header&gt;

</code></pre>

<p>and here is my spec file:</p>

<pre><code>import { ComponentFixture, TestBed, async } from '@angular/core/testing';

import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { TabsComponent } from './tabs.component';

describe('TabsComponent', () =&gt; {
  let component: TabsComponent;
  let fixture: ComponentFixture&lt;TabsComponent&gt;;
  let de: DebugElement;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [TabsComponent],
      imports: [RouterTestingModule]
    }).compileComponents();
  }));

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

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

  it('should set clicked tab to active', () =&gt; {
    de.queryAll(By.css('.c-tab__item'))[1].nativeElement.click();
    expect(
      de.query(By.css('.c-tab__item--active .c-tab__text')).nativeElement
        .innerHTML
    ).toContain('Product');
  });
</code></pre>

<p>I expect the tab to be active once I click on it but I am getting this error
<code>TypeError: de.query(...) is null in http://localhost:9876/_karma_webpack_/main.js (line 872)</code> which I believe means that no tab was set to active.</p>
",https://stackoverflow.com/questions/60953499/routerlinkactive-not-working-in-unit-testing,"['angular', 'jasmine', 'karma-jasmine']",821,True,0,2
unit testing iOS function with dispatch,"<p>I'm working with unit testing for the first time and I'm lost with some specific cases.</p>

<p>Despite reading a lot I'm confused about how to test a function like this in iOS:</p>

<pre><code>func myFunction() {

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
          // Tasks to do in background
            dispatch_async(dispatch_get_main_queue(), ^(void){
            // Get the results
            // Update UI
         });
    });
}
</code></pre>

<p>I've read about ""expectations"" (<a href=""https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations?language=objc"" rel=""nofollow noreferrer"">https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations?language=objc</a>), but I don't know how to use them. I guess I should have to call
expectation.fulfill(), but I don't know where.</p>
",https://stackoverflow.com/questions/62430118/unit-testing-ios-function-with-dispatch,"['ios', 'unit-testing', 'dispatch-async', 'expectations']",47,True,0,1
Android Java Unit Testing using ApplicationProiver,"<p>I am trying to use the new Androidx testing.  When I run the following unit test, I get the following error.  I don't know why the context package name is org.robolectric.default</p>

<p>junit.framework.ComparisonFailure:</p>

<p>Expected :com.example.test_game_java</p>

<p>Actual   :org.robolectric.default</p>

<pre><code>package com.example.test_game_java;
import android.content.Context;
import org.junit.Test;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.runner.RunWith;
import org.junit.Assert.*;

//import static androidx.test.core.app.ApplicationProvider.*;
import static junit.framework.TestCase.assertEquals;

@RunWith(AndroidJUnit4.class)
public class ExampleUnitTest {

    @Test
    public void applicationContextTest() {
        Context context = ApplicationProvider.getApplicationContext();
        assertEquals(""com.example.test_game_java"", context.getPackageName());
    }
}
</code></pre>
",https://stackoverflow.com/questions/61173552/android-java-unit-testing-using-applicationproiver,"['unit-testing', 'androidx']",72,False,0,1
Unit Testing Input Event in Angular6,"<p>I have an Input field in the UI</p>

<p><code>&lt;input matInput placeholder=""BLC"" id='blc' formControlName=""blc"" (change)=""onBLCChanged($event)"" /&gt;</code></p>

<p>I want to do unit testing for this, but this field send $event not any value to the function, how can I mock this.</p>

<pre><code>  it('some text', async(async() =&gt; {
    spyOn(component, 'onBLCChanged');
    // first round of change detection
    fixture.detectChanges();
    // get ahold of the input
    let input = debugElement.query(By.css('#blc'));
    let inputElement = input.nativeElement;

    //set input value
    inputElement.value = 'test';
    inputElement.dispatchEvent(new Event('change'));

    expect(component.onBLCChanged).toHaveBeenCalledWith({});
  }));
</code></pre>

<p>This is not working, <code>Expected spy onBLCChanged to have been called with [ Object({  }) ] but actual calls were [ [object Event] ].
</code></p>

<p>Please help, <code>onBLCChanged</code> is the method in the .ts file.</p>
",https://stackoverflow.com/questions/59824622/unit-testing-input-event-in-angular6,['angular'],45,True,0,2
Unit testing for service in Angular,"<p>I am trying to create unit testing for service I have import data service in spec file.</p>
<p>Then I am calling  in beforeach Method.</p>
<pre><code> providers: [
    { provide: dataservice}    
  ],
</code></pre>
<p>I am getting this error</p>
<pre><code>TypeError: Cannot read property 'setNumber' of undefined

this.dataService.setNumber(null);
</code></pre>
<p>As per the below user I added</p>
<pre><code>const spyDataService = jasmine.createSpyObj('DataService', ['setNumber '])
</code></pre>
<p>in before each</p>
<p>How to get rid of this error I am trying like below i am getting error and i modifed this into</p>
<pre><code>  it('should be create data service', () =&gt; {    
     expect(DataService).setNumber;
    });

  it('should be create data service', () =&gt; {
    expect(service.setBCNumber).toHaveBeenCalledWith(null);
  }); 
</code></pre>
<p>but still I am getting the same error.</p>
",https://stackoverflow.com/questions/63924847/unit-testing-for-service-in-angular,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",102,False,0,1
Unit testing in typescript with Jest,"<p>I'm trying to unit test a typescript class with dependencies as follows:</p>
<p><strong><strong>in collect.test.ts...</strong></strong></p>
<pre><code>import CollectAssets  from &quot;../../src/collect/assets.collect&quot;;

  
it('works', async ()=&gt;{

expect(await CollectAssets.collect().toBeTruthy()
  })
</code></pre>
<p><strong>in assets.collect.ts...</strong></p>
<pre><code>import * as util from '../utils/utils';


const debug = util.debugGenerator('Collect assets')
export default class CollectAssets extends Collect {

    static async collect(
        pageContext: PageContext
    ): Promise&lt;SA.Traces.CollectAssetsTraces | undefined&gt; {}
</code></pre>
<p><strong>in utils.ts...</strong></p>
<pre><code>import * as Debug from 'debug';

export function debugGenerator(namespace: string): Debug.IDebugger {
const debug = Debug(`${namespace}`);
return debug;
</code></pre>
<p>}</p>
<p>However when running jest it fails to run with the error:</p>
<blockquote>
<p>TypeError: util.debugGenerator is not a function</p>
</blockquote>
<pre><code>&gt;  8 | const debug = util.debugGenerator('Transfer collect')
</code></pre>
<p>My tsconfig.json config file is :</p>
<pre><code>{
&quot;compilerOptions&quot;: {
  &quot;rootDir&quot;: &quot;./src&quot;,
  &quot;outDir&quot;: &quot;./build&quot;,
  &quot;target&quot;: &quot;es2016&quot;,
  &quot;lib&quot;: [&quot;es2017&quot;, &quot;dom&quot;],
  &quot;module&quot;: &quot;commonjs&quot;,
  &quot;moduleResolution&quot;:&quot;Node&quot;,
  &quot;types&quot;: [
    &quot;node&quot;,
    &quot;jest&quot;
  ],
  &quot;strict&quot;: true,
  &quot;inlineSourceMap&quot;: true,
  &quot;noImplicitReturns&quot;:true,
  &quot;declaration&quot;: true,
  &quot;skipLibCheck&quot;:true,
},
&quot;include&quot;: [
    &quot;./src/**/*&quot;
]
</code></pre>
<p>}</p>
<p>My package.json is :</p>
<pre><code>    &quot;devDependencies&quot;: {
    &quot;@types/jest&quot;: &quot;^26.0.0&quot;,
    &quot;jest&quot;: &quot;^26.1.0&quot;,
    &quot;ts-jest&quot;: &quot;^26.1.1&quot;,
    &quot;typescript&quot;: &quot;^3.8.3&quot;,

  },
      &quot;jest&quot;: {
        &quot;setupFilesAfterEnv&quot;: [
          &quot;&lt;rootDir&gt;/test/config/setup.js&quot;
        ],
        &quot;transform&quot;: {
          &quot;^.+\\.tsx?$&quot;: &quot;ts-jest&quot;
        },
        &quot;testRegex&quot;: &quot;/test/.*\\.test\\.ts$&quot;,
        &quot;moduleFileExtensions&quot;: [
          &quot;ts&quot;,
          &quot;js&quot;,
          &quot;json&quot;
        ]
      }
</code></pre>
<p>and I'm extending this in a jest ts config file:</p>
<pre><code>{
&quot;extends&quot;: &quot;../../tsconfig.json&quot;,
&quot;include&quot;: [
    &quot;../../test/**/*&quot;
]
</code></pre>
<p>}</p>
<p>What I am doing wrong here?</p>
",https://stackoverflow.com/questions/62635561/unit-testing-in-typescript-with-jest,"['typescript', 'jestjs', 'ts-jest']",136,False,0,0
Redshift 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 make sure that it always returns something?</p>
",https://stackoverflow.com/questions/60415665/redshift-connection-unit-testing-in-python,"['python', 'python-3.x', 'python-2.7', 'unit-testing', 'amazon-redshift']",376,False,0,1
unit testing of class without dependencies,"<p>Imagine I have the following class:</p>

<pre><code>public class MyWeirdCollection
{
    private IList&lt;string&gt; _myTrueList;
    private IList&lt;string&gt; _myFalseList;

    public MyCollection()
    {
        _myTrueList = new List&lt;string&gt;();
        _myFalseList = new List&lt;string&gt;();
    }

    public void Add(string item, bool listType)
    {
        if (listType)
        {
            _myTrueList.Add(item);
        }
        else
        {
            _myFalseList.Add(item);
        }
    }

    public IList&lt;string&gt; Get(bool listType)
    {
        return listType ? _myTrueList : myFalseList;
    }
}
</code></pre>

<p>How would I go about unit testing the <code>Get</code> and <code>Add</code> methods? I'm doubting between 2 possible solutions:</p>

<ol>
<li>Making the 2 lists protected instead of private, so I can create an inheriting <code>TestableWeirdCollectionClass</code> that exposes the content of the lists to the test</li>
<li>Leave the class as it is and test <code>Add</code> and <code>Get</code> together? i.e. calling <code>Add</code> to add some elements and then <code>Get</code> to see if the correct values come back.</li>
</ol>

<p>I'm leaning towards option no. 2, but would like some more opinions. Thanks.</p>
",https://stackoverflow.com/questions/61216734/unit-testing-of-class-without-dependencies,"['c#', 'unit-testing']",91,True,0,2
Unit testing Angular with Karma/Jasmine:,"<p>I have inserted an if-else condition in my component so that after login I will be forwarded to a specific URL. However, my unit test now fails with the following error:</p>

<blockquote>
  <p>1) should create</p>
  
  <p>AnotherComponent</p>

<pre><code> Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'testroute'
</code></pre>
</blockquote>

<p>Without the if else condition everything is working fine, so I'm sure that this is the cause of my problem. The funny thing is, that I'm not testing anything that is related to the code inside my ngOnInit() lifecycle. More funny is, that not the test for MyComponent is failing but the test for another Component.</p>

<p>My Component (MyComponent) looks like this:</p>

<pre><code>export class MyComponent implements OnInit {

  routes = Constants.routes;

  constructor(private router: Router,
    private myService: MyService) {
  }

  ngOnInit() {
    if (this.myService.context === 'TEST') {
      this.router.navigate([routes.testroute + this.myService.context]);
    } else {
      this.router.navigate([routes.testroute]);
    }
  }
}
</code></pre>

<p>The Template looks like this:</p>

<pre><code>&lt;router-outlet&gt;&lt;/router-outlet&gt;
</code></pre>

<p>The unit test of the failing component looks like this:</p>

<pre><code>  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([]),
      ],
      providers: [
        PathLocationStrategy
      ],
      declarations: [AnotherComponent],
    }).compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
</code></pre>
",https://stackoverflow.com/questions/60319626/unit-testing-angular-with-karma-jasmine,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",125,True,-1,1
Unit testing not making any sense,"<p>I doing some unit tests using Jest for React.</p>

<p>For some reason, when I'm expecting it to not be null, it Received null in the response.</p>

<pre><code>describe('Components: FlightSummary', () =&gt; {
  it('should render local time by default', () =&gt; {
    const { queryByText } = render();

    ['18:10', '18:15', '18:18', '18:23', '18:30', '18:35'].forEach(
      timeValue =&gt; {
        expect(queryByText(timeValue)).not.toBeNull();
      }
    );
</code></pre>

<pre><code>expect(received).not.toBeNull()

Received: null

  62 |     ['18:10', '18:15', '18:18', '18:23', '18:30', '18:35'].forEach(
  63 |       timeValue =&gt; {
&gt; 64 |         expect(queryByText(timeValue)).not.toBeNull();
     |                                            ^
  65 |       }
  66 |     );
</code></pre>

<p>And when I change the code to expect null, it Received a value in the response.</p>

<pre><code>describe('Components: FlightSummary', () =&gt; {
  it('should render local time by default', () =&gt; {
    const { queryByText } = render();

    ['18:10', '18:15', '18:18', '18:23', '18:30', '18:35'].forEach(
      timeValue =&gt; {
        expect(queryByText(timeValue)).toBeNull();
      }
    );
</code></pre>

<pre><code>expect(received).toBeNull()

Received: &lt;div&gt;18:10&lt;/div&gt;

  62 |     ['18:10', '18:15', '18:18', '18:23', '18:30', '18:35'].forEach(
  63 |       timeValue =&gt; {
&gt; 64 |         expect(queryByText(timeValue)).toBeNull();
     |                                        ^
  65 |       }
  66 |     );
</code></pre>

<p>I have no idea what's going on; have never seen this before. ToT</p>
",https://stackoverflow.com/questions/60881060/unit-testing-not-making-any-sense,"['javascript', 'unit-testing', 'jestjs']",719,False,0,1
Jasmine Angular Unit testing with subscribe,"<p>------Service file ------- </p>

<pre><code>postStatus(status: String) {
    return this.http
        .post(url, null, {
          headers: new HttpHeaders({""Content-Type"": ""application/json""}),
          observe: ""response""
        })
        .subscribe(
            responseDate =&gt; {
              console.log(responseDate)
              this.statusUpdated.next(status);
            },
            error =&gt; {
              if (status === ""Z"") this.statusUpdated.next(""ZERROR"")
              else this.statusUpdated.next(""YERROR"")
            })
  }
</code></pre>

<p>----- Spec file ---------</p>

<pre><code>const errorResponse = new HttpErrorResponse({
  error: 'test 404 error',
  status: 404, statusText: 'Not Found'
});


it('postStatus should return error and update status to error to ZERROR' ,() =&gt;{
    httpCientSpyPost = jasmine.createSpyObj('http', ['post']);
    service  = new ChangelogService(&lt;any&gt;httpCientSpyPost,null,null,new PostMessageService());
    let updatedStatus:string = '';


    httpCientSpyPost.post.and.returnValue(of(errorResponse));
    service.statusUpdated.subscribe((status:string) =&gt; {updatedStatus=status});

    service.postStatus('Z');

    expect(httpCientSpyPost.post.calls.count()).toBe(1, 'one call');
    expect(updatedStatus).toBe('ZERROR');
});

</code></pre>

<p>---------Error I am getting ------------</p>

<p>Error: </p>

<pre><code>Expected 'Z' to be 'ZERROR'.
</code></pre>

<p>Its not going to error block. Am I missing something here?</p>
",https://stackoverflow.com/questions/62201245/jasmine-angular-unit-testing-with-subscribe,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-unit-test']",85,True,0,1
Unit testing base and derived class,"<p>So I have 2 classes. <code>ItemWithAttributes</code> and <code>ItemWithNameAndAttributes</code> (derives from 1st).</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Helpers;

namespace Objects.Base
{
    public class ItemWithAttributes
    {
        public IEnumerable&lt;string&gt; Attributes { get; }

        public ItemWithAttributes(IEnumerable&lt;string&gt; attributes)
        {
            if (attributes == null)
                throw new ArgumentNullException(nameof(attributes), ""Parameter can not be mull."");

            Attributes = attributes.ToArray();
        }

        public virtual string AttributesToParenthesesString(bool prependSpace)
        {
            return $""{Attributes.ToParenthesesString(prependSpace)}"";
        }

        public override string ToString()
        {
            return AttributesToParenthesesString(false);
        }
    }
}
</code></pre>

<pre><code>using System;
using System.Collections.Generic;

namespace Objects.Base
{
    public class ItemWithNameAndAttributes : ItemWithAttributes
    {
        public string Name { get; }

        public ItemWithNameAndAttributes(string name, IEnumerable&lt;string&gt; attributes) : base(attributes)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name), ""Parameter can not be null."");

            if (name.Length == 0)
                throw new ArgumentException(""Parameter can not be empty."", nameof(name));

            Name = name;
        }

        public override string ToString()
        {
            return $""{Name}{AttributesToParenthesesString(true)}"";
        }
    }
}
</code></pre>

<p>I want to get into unit testing so this is what I got so far for both my classes. I did some reading on naming convention for test method naming but I feel kind of stuck now.</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Objects.Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests.Objects.Base
{
    [TestClass]
    public class ItemWithAttributesTests
    {
        [TestMethod]
        public void Constructor_AttributesWithElements_PropertyEqualToInput()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            CollectionAssert.AreEqual(attributes, itemWithAttributes.Attributes.ToList());
        }

        [TestMethod]
        public void Constructor_AttributesWithoutElements_PropertyEqualToInput()
        {
            var attributes = new List&lt;string&gt;() { };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            CollectionAssert.AreEqual(attributes, itemWithAttributes.Attributes.ToList());
        }

        [TestMethod]
        public void Constructor_AttributesNull_ThrowArgumentNullException()
        {
            Assert.ThrowsException&lt;ArgumentNullException&gt;(() =&gt; new ItemWithAttributes(null));
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependFalse_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual(""(Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependTrue_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("" (Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependFalse_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() {  };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependTrue_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() {  };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void ToString_AttributesWithElements_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.ToString();

            Assert.AreEqual(""(Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void ToString_AttributesWithoutElements_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.ToString();

            Assert.AreEqual("""", result);
        }
    }
}
</code></pre>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Objects.Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests.Objects.Base
{
    [TestClass]
    public class ItemWithNameAndAttributesTests
    {
        [TestMethod]
        public void Constructor_NameAndAttributesWithElements_PropertiesAreEqualToInput()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            Assert.AreEqual(name, itemWithNameAndAttributes.Name);
            CollectionAssert.AreEqual(attributes, itemWithNameAndAttributes.Attributes.ToList());
        }

        [TestMethod]
        public void Constructor_NameAndAttributesWithoutElements_PropertiesAreEqualToInput()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            Assert.AreEqual(name, itemWithNameAndAttributes.Name);
            CollectionAssert.AreEqual(attributes, itemWithNameAndAttributes.Attributes.ToList());
        }


        [TestMethod]
        public void Constructor_NameEmpty_ThrowArgumentException()
        {
            var name = string.Empty;
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            Assert.ThrowsException&lt;ArgumentException&gt;(() =&gt; new ItemWithNameAndAttributes(name, attributes));
        }

        [TestMethod]
        public void Constructor_NameNull_ThrowArgumentNullException()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            Assert.ThrowsException&lt;ArgumentNullException&gt;(() =&gt; new ItemWithNameAndAttributes(null, attributes));
        }

        [TestMethod]
        public void Constructor_AttributesNull_ThrowArgumentNullException()
        {
            var name = ""Name"";
            Assert.ThrowsException&lt;ArgumentNullException&gt;(() =&gt; new ItemWithNameAndAttributes(name, null));
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependFalse_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual(""(Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependTrue_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("" (Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependFalse_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependTrue_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void ToString_AttributesArgumentIsListWithElements_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.ToString();

            Assert.AreEqual(""Name (Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void ToString_AttributesArgumentIsListWithoutElements_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.ToString();

            Assert.AreEqual(""Name"", result);
        }
    }
}
</code></pre>

<p>What I notice is that the unit tests for my derived class <code>ItemWithNameAndAttributes</code> are almost the same as for my base class <code>ItemWithAttributes</code> but just a little more and different because I also need to validate for the name argument. I'm not sure if this is the correct way to go or if there is some method to reuse the tests from my base class in my derived class. If I keep this current pattern up, when I derive from <code>ItemWithNameAndAttributes</code> I would have even more tests that are the same and retest the base classes. I got the feeling it got very complex very quickly for the small classes I have.</p>
",https://stackoverflow.com/questions/60128329/unit-testing-base-and-derived-class,"['c#', 'unit-testing']",114,True,0,1
Is unit testing just testing methods?,"<p>I'm a new software developer and the devs are going over the importance of Java Unit Testing. Is Unit Testing just testing the individual java methods? And what is integration testing in relation to unit testing in Java?</p>
",https://stackoverflow.com/questions/63362515/is-unit-testing-just-testing-methods,"['java', 'unit-testing', 'testing']",47,True,-1,1
How to unit testing angular jasmine,"<p>i have many components with angular 9, i want to test that the content and functions are ok but when i run tests on ""ng test"" they fail because they expect providers but found none.</p>

<p>This is one example component.ts</p>

<pre><code>import {Component}
import {AppComponent} 
import {AdminService}
import {GenUtil}
import {UserUtil} 
import {TableComponent} 
import {UserRole} 


export class AdminListComponent extends TableComponent&lt;any&gt; {

  currentUserRole: number = UserRole.USER.level;

  userRoles: UserRole = UserRole;

  constructor(
      private adminService: AdminService, 
      private app: AppComponent) {
    super();
    this.loadData();
    app.showBackoffice();
  }

  getTableSettings() {
    return [
      {
        objectKey: '_id',
        sort: 'desc'
      }, {
        objectKey: 'is_company'
      }, {
        objectKey: 'personal_id_type'
      }, {
        objectKey: 'personal_id_number'
      }, {
        objectKey: 'name'
      }, {
        objectKey: 'last_login_date'
      }, {
        objectKey: 'last_modification_date'
      }, {
        objectKey: 'enabled'
      }, {
        objectKey: 'accredited_accept_terms'
      }
    ]
  }

  getTableFields() {
    return [{
      name: 'Email',
      objectKey: '_id'
    }, {
      name: 'Tipo de usuario',
      objectKey: 'is_company',
      value: row =&gt; UserUtil.getUserTypeHumanized(row),
      render: row =&gt; UserUtil.getUserTypeHumanized(row)
    }, {
      name: 'Tipo de identificación',
      objectKey: 'personal_id_type',
      value: row =&gt; UserUtil.getPersonalIDTypeHumanized(row),
      render: row =&gt; UserUtil.getPersonalIDTypeHumanized(row)
    }, {
      name: 'Número de identificación',
      objectKey: 'personal_id_number',
      value: row =&gt; UserUtil.getPersonalIDHumanized(row),
      render: row =&gt; UserUtil.getPersonalIDHumanized(row)
    }, {
      name: 'Nombre',
      objectKey: 'name'
    }, {
      name: 'Último login',
      objectKey: 'last_login_date',
      value: row =&gt; row.last_modification_date ? row.last_login_date : ""Nunca"",
      render: row =&gt; row.last_modification_date ? GenUtil.formatTimestamp(new Date(row.last_login_date)) : ""Nunca""
    }, {
      name: 'Fecha de modificación',
      objectKey: 'last_modification_date',
      value: row =&gt; row.last_modification_date ? row.last_modification_date : ""Nunca"",
      render: row =&gt; row.last_modification_date ? GenUtil.formatTimestamp(new Date(row.last_modification_date)) : ""Nunca""
    }, {
      name: '',
      objectKey: 'enabled',
      render: row =&gt; this.currentUserRole == UserRole.USER.level ? '&lt;a class=""btn btn-success""&gt;Promocionar&lt;/a&gt;' : '&lt;a class=""btn btn-warning""&gt;Degradar&lt;/a&gt;',
      click: (row) =&gt; this.changeUserRole(row._id, this.currentUserRole == UserRole.USER.level ? ""30"" : ""00"")
    }, {
      name: '',
      objectKey: 'accredited_accept_terms',
      render: row =&gt; '&lt;a class=""btn btn-success""&gt;Ver usuario&lt;/i&gt;&lt;/a&gt;',
      click: (row) =&gt; {
        if (window.localStorage) {
          localStorage.setItem('id', row._id);
          let bd;
          switch (row.is_verified_bd) {
            case true:
              bd = 1;
              break;
            case false:
              bd = 0;
              break;
            case null:
              bd = 2;
              break;
            case undefined:
              bd = 2;
              break;
            default:
              bd = 2;
          }
          let accredited;
          switch (row.accredited_accept_terms) {
            case true:
              accredited = 1;
              break;
            case false:
              accredited = 0;
              break;
            default:
              accredited = 0;
          }
          localStorage.setItem('bd', bd);
          localStorage.setItem('accredited', accredited);
        }
        window.open(`user-history`)
      }
    }]
  }

  loadData() {
    let searchConditions = {
      role: UserRole.encodeRol(this.currentUserRole)
    };

    this.adminService.getAdminList(searchConditions)
      .then((response) =&gt; {

        if (response.status == ""ok"") {
          this.data = response.data.users_short_info;

          if (this.data.length == 0) {
            this.info(""No se han encontrado usuarios con rango de Administrador"")
          }

          this.buildTable();
        } else {
          this.error(""No ha sido posible recuperar los usuarios"", response)
        }

      })
  }

  changeUserRole(email, role) {
    this.adminService.changeToUserOrAdmin(email, role)
      .then((response) =&gt; {
        if (response.status == ""ok"") {
          this.success(`Se ha ${role == ""30"" ? 'promocionado' : 'degradado'} a ${email}`)
          this.loadData();
        } else {
          this.error(`Ha ocurrido un error ${role == ""30"" ? 'promocionando' : 'degradando'} a ${email}`)
        }
      });
  }

}

</code></pre>

<p>This is my AdminService.ts</p>

<pre><code>import { Injectable }
import { BaseService }
import { Http }
import { environment }
import { Router }

@Injectable()
export class AdminService extends BaseService {

  constructor(protected http: Http, public router: Router) {
    super(http, router)
  }

  getAllProjects(): Promise&lt;any&gt; {
    let url: string = `${this.BASE_URL}/api/`;
    return this.post(url, {})
  }
}

</code></pre>

<p>This is my spec.ts generated by angular</p>

<pre><code>import { async, ComponentFixture, TestBed } 

import { AdminListComponent } 
import { AdminService } 
import { HttpModule, Http } 
import { AppModule } 
import { Router }
import { AppComponent }

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

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

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

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

</code></pre>

<p>And when i run my test with ng test (selecting only this component) ive got:</p>

<ul>
<li>Should Create -> SuperAdminListComponent > should create
NullInjectorError: R3InjectorError(DynamicTestModule)[AdminService -> AdminService]: 
NullInjectorError: No provider for AdminService!  --- > Expected undefined to be truthy.</li>
<li>Should Create -> NullInjectorError: R3InjectorError(DynamicTestModule)[AdminService -> AdminService]: NullInjectorError: No provider for AdminService! --- > Expected undefined to be truthy.</li>
</ul>

<p>This is the image of the errors</p>

<p><a href=""https://i.stack.imgur.com/mSjn4.png"" rel=""nofollow noreferrer"">Karma errors</a></p>

<p>this is my package.json</p>

<pre><code>{
  ""name"": ""bdkfrontscss"",
  ""version"": ""0.0.0"",
  ""scripts"": {
    ""ng"": ""ng"",
    ""start"": ""ng serve"",
    ""build"": ""ng build"",
    ""test"": ""ng test"",
    ""lint"": ""ng lint"",
    ""e2e"": ""ng e2e""
  },
  ""private"": true,
  ""dependencies"": {
    ""@agm/core"": ""^1.1.0"",
    ""@angular-generic-table/core"": ""^4.17.1"",
    ""@angular/animations"": ""~9.0.3"",
    ""@angular/cdk"": ""^9.1.0"",
    ""@angular/common"": ""~9.0.3"",
    ""@angular/compiler"": ""~9.0.3"",
    ""@angular/core"": ""~9.0.3"",
    ""@angular/forms"": ""~9.0.3"",
    ""@angular/http"": ""^7.2.16"",
    ""@angular/platform-browser"": ""~9.0.3"",
    ""@angular/platform-browser-dynamic"": ""~9.0.3"",
    ""@angular/router"": ""~9.0.3"",
    ""@ngx-translate/core"": ""^12.1.2"",
    ""@ngx-translate/http-loader"": ""^4.0.0"",
    ""@swimlane/ngx-charts"": ""^13.0.2"",
    ""angular-froala-wysiwyg"": ""^3.1.0"",
    ""angular-generic-table"": ""^4.0.1"",
    ""angularx-qrcode"": ""^2.1.0"",
    ""aos"": ""^2.3.4"",
    ""bootstrap"": ""^3.4.1"",
    ""cookieconsent"": ""^3.1.1"",
    ""include-media"": ""^1.4.9"",
    ""jquery"": ""^3.4.1"",
    ""json-style-converter"": ""^1.0.3"",
    ""jspdf"": ""^1.5.3"",
    ""moment"": ""^2.24.0"",
    ""ng-recaptcha"": ""^5.0.0"",
    ""ng2-device-detector"": ""^1.0.1"",
    ""ng4-intl-phone"": ""^1.2.1"",
    ""ngx-bootstrap"": ""^5.5.0"",
    ""ngx-cookie-service"": ""^2.4.0"",
    ""ngx-cookieconsent"": ""^2.2.3"",
    ""ngx-currency"": ""^2.2.2"",
    ""ngx-currency-mask"": ""^4.3.2"",
    ""ngx-device-detector"": ""^1.3.20"",
    ""ngx-loading"": ""^8.0.0"",
    ""ngx-quill"": ""^8.0.0"",
    ""ngx-sharebuttons"": ""^4.1.4"",
    ""ngx-toastr"": ""^12.0.0"",
    ""rxjs"": ""~6.5.4"",
    ""rxjs-compat"": ""^6.5.4"",
    ""tether"": ""^1.4.7"",
    ""tslib"": ""^1.10.0"",
    ""zone.js"": ""~0.10.2""
  },
  ""devDependencies"": {
    ""@angular-devkit/build-angular"": ""~0.900.4"",
    ""@angular/cli"": ""~9.0.4"",
    ""@angular/compiler-cli"": ""~9.0.3"",
    ""@angular/language-service"": ""~9.0.3"",
    ""@types/node"": ""^12.11.1"",
    ""@types/jasmine"": ""~3.5.0"",
    ""@types/jasminewd2"": ""~2.0.3"",
    ""codelyzer"": ""^5.1.2"",
    ""jasmine-core"": ""~3.5.0"",
    ""jasmine-spec-reporter"": ""~4.2.1"",
    ""karma"": ""~4.3.0"",
    ""karma-chrome-launcher"": ""~3.1.0"",
    ""karma-coverage-istanbul-reporter"": ""~2.1.0"",
    ""karma-jasmine"": ""~2.0.1"",
    ""karma-jasmine-html-reporter"": ""^1.4.2"",
    ""protractor"": ""~5.4.3"",
    ""ts-node"": ""~8.3.0"",
    ""tslint"": ""~5.18.0"",
    ""typescript"": ""~3.7.5""
  }
}

</code></pre>

<p><strong>If i try to put on providers:[AdminService, Http, Router, ConnectionBackend, RequestOptions] i finally got another error ""Error: This constructor was not compatible with Dependency Injection.
""</strong></p>

<p>Thanks</p>
",https://stackoverflow.com/questions/60607534/how-to-unit-testing-angular-jasmine,"['angular', 'unit-testing', 'testing', 'jasmine', 'karma-runner']",1020,False,0,1
Write unit testing for Strapi APIs,"<p>Am trying to start writing Unit test for Strapi endpoint or APIs. Since it is way different from Express and does not have a app.route concept in my view. I am not sure on how to start with.</p>

<p>I have had experience in write unit test suits for APIs with Mocha, Sinon and Chai. But how do they work with Strapi APIs is my question.</p>

<p>If anyone having knowledge on unit testing Strapi API, it will be a great head start for me.</p>

<p>Updating the question with code under test</p>

<p>controllers/checkStatus.js</p>

<pre><code>module.exports = {

    checkStatus: async (ctx) =&gt; {
       return strapi.services.checkstatus.getStatus(ctx.request.body.id);
    }
};
</code></pre>

<p>services/checkstatus.js</p>

<pre><code>module.exports = {

    getStatus: (id) =&gt; {
       return id;
    }
};
</code></pre>
",https://stackoverflow.com/questions/61102055/write-unit-testing-for-strapi-apis,"['node.js', 'unit-testing', 'mocha.js', 'sinon', 'strapi']",557,False,0,1
Unit Testing RxJava Flowable using spock,"<p>I have below snippet for fetching data from MongoDB using <code>com.mongodb.reactivestreams.client.MongoClient</code> and <code>Flowable</code></p>
<p>The snippet goes like:</p>
<pre class=""lang-java prettyprint-override""><code>Flowable
  .fromPublisher(
     mongoClient
      .getDatabase(mydb)
      .getCollection(mycollection)
      .find()
      .limit()
  )
  .firstOrError()
  .toMaybe()
  .doOnError(error -&gt; { /* somecode */ })
</code></pre>
<p>I tried mocking every step of this fluent expression, e.g.</p>
<pre class=""lang-java prettyprint-override""><code>MongoDatabase someDb = Mock(MongoDatabase)
mongoClient.getDatabase(mydb) &gt;&gt; somedb
</code></pre>
<p>but on doing this somehow the test keeps running.</p>
<p>What is the correct way to unit test this using Spock?</p>
",https://stackoverflow.com/questions/65410331/unit-testing-rxjava-flowable-using-spock,"['unit-testing', 'rx-java', 'rx-java2', 'spock', 'reactive-streams']",235,False,0,2
unit testing AWS secret manager java,"<p>I need to unit test AWS secret manager that is in Java and am using Mockito and EasyMock to do that and whenever I call client.getSecretValue(), it is trowing the exception
<strong>Code to be tested</strong></p>
<pre><code>AWSSecretsManagerClient client =
            (AWSSecretsManagerClient) 
AWSSecretsManagerClientBuilder.standard().withRegion(region).build();

    String secret = null, decodedBinarySecret = null;
    GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest().withSecretId(secretName);
    GetSecretValueResult getSecretValueResult = null;
    AWSSecrets awsSecrets = null;
    try {
        getSecretValueResult = client.getSecretValue(getSecretValueRequest);
    } catch (DecryptionFailureException e) {
</code></pre>
<p><strong>Exception</strong></p>
<pre><code> &quot;com.amazonaws.SdkClientException: Unable to load AWS credentials from any provider in the chain: [EnvironmentVariableCredentialsProvider: Unable to load AWS credentials from environment variables (AWS_ACCESS_KEY_ID (or AWS_ACCESS_KEY) and AWS_SECRET_KEY (or AWS_SECRET_ACCESS_KEY)), SystemPropertiesCredentialsProvider: Unable to load AWS credentials from Java system properties (aws.accessKeyId and aws.secretKey), com.amazonaws.auth.profile.ProfileCredentialsProvider@28ce75ec: Unable to load credentials into profile [default]: AWS Access Key ID is not specified., WebIdentityTokenCredentialsProvider: To use assume role profiles the aws-java-sdk-sts module must be on the class path., com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper@4db728df: Unable to load credentials from service endpoint]&quot;.
</code></pre>
<p>Can anybody help me with this?</p>
",https://stackoverflow.com/questions/62959838/unit-testing-aws-secret-manager-java,"['java', 'amazon-web-services', 'unit-testing', 'secret-manager']",2225,False,0,1
Unit Testing ADF Pipeline with SpecFlow,"<p>I'm starting off with SpecFlow to test my Azure Data Factory pipelines. I'm using VS 2019 &amp; .NET Framework 4.7.2. When I try to run my test, it starts executing and then completes instantaneously. I've also observed that it doesn't hit the breakpoints which I've placed in the <code>feature file</code> as well as in the <code>binding</code>. This is my <code>packages.config</code> file:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;packages&gt;
  &lt;package id=""Microsoft.Azure.Management.DataFactory"" version=""4.8.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.IdentityModel.Clients.ActiveDirectory"" version=""5.2.7"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.NET.Test.Sdk"" version=""15.0.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.Rest.ClientRuntime"" version=""2.3.20"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.Rest.ClientRuntime.Azure"" version=""3.3.19"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.TestPlatform.TestHost"" version=""15.0.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""MSTest.TestAdapter"" version=""1.3.2"" targetFramework=""net472"" /&gt;
  &lt;package id=""MSTest.TestFramework"" version=""1.3.2"" targetFramework=""net472"" /&gt;
  &lt;package id=""Newtonsoft.Json"" version=""10.0.3"" targetFramework=""net472"" /&gt;
  &lt;package id=""SpecFlow"" version=""2.4.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""SpecRun.Runner"" version=""3.2.22"" targetFramework=""net472"" /&gt;
  &lt;package id=""SpecRun.SpecFlow.2-4-0"" version=""3.2.22"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.IO"" version=""4.3.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.Net.Http"" version=""4.3.4"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.Runtime"" version=""4.3.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.Security.Cryptography.Algorithms"" version=""4.3.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.Security.Cryptography.Encoding"" version=""4.3.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.Security.Cryptography.Primitives"" version=""4.3.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.Security.Cryptography.X509Certificates"" version=""4.3.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""System.ValueTuple"" version=""4.3.0"" targetFramework=""net472"" /&gt;
&lt;/packages&gt;
</code></pre>

<p>When I checked my log file, I could find this line in the log file that got generated: <code>No tests executed (activation needed)</code>. Can someone please tell me where I'm going wrong here? Note that my solution is building properly.</p>

<p>PFB the entire log for your reference:</p>

<pre><code>2020-04-21T23:25:19.8268118+05:30;VSTestExecutionThread;Info;SpecFlow+Runner execution started
2020-04-21T23:25:19.8268118+05:30;VSTestExecutionThread;Info;SpecFlow+Runner 3.2.22 in Framework clr40 in x86 mode execution started
2020-04-21T23:25:19.8268118+05:30;VSTestExecutionThread;Info;TestAdapter Location: C:\Users\ddc\source\repos\ADF.UnitTest\packages\SpecRun.Runner.3.2.22\tools\net45\TechTalk.SpecRun.VisualStudio.TestAdapter.dll
2020-04-21T23:25:20.0532065+05:30;VSTestExecutionThread;Info;SpecRun: running tests in C:\Users\ddc\source\repos\ADF.UnitTest\ADF.UnitTest\bin\Debug\ADF.UnitTest.dll
2020-04-21T23:25:20.0532065+05:30;VSTestExecutionThread;Info;Output folder configured to ""C:\Users\ddc\source\repos\ADF.UnitTest\TestResults"" (default)
2020-04-21T23:25:20.0542043+05:30;VSTestExecutionThread;Info;Profile: ADF.UnitTest
2020-04-21T23:25:20.1309989+05:30;VSTestExecutionThread;Info;Log file path: C:\Users\ddc\source\repos\ADF.UnitTest\TestResults\ADF.UnitTest_ADF.UnitTest_2020-04-21T232520.log
2020-04-21T23:25:20.1429665+05:30;Thread#14;Info;Checking activation
2020-04-21T23:25:21.6090483+05:30;Thread#14;Error;No tests executed (activation needed)
2020-04-21T23:25:21.6339842+05:30:Total: 0
2020-04-21T23:25:21.6369734+05:30:Succeeded: 0
2020-04-21T23:25:21.6369734+05:30:Ignored: 0
2020-04-21T23:25:21.6369734+05:30:Pending: 0
2020-04-21T23:25:21.6379706+05:30:Skipped: 0
2020-04-21T23:25:21.6379706+05:30:Failed: 0
2020-04-21T23:25:21.6449520+05:30;VSTestExecutionThread;Info;Adding attachments to VSTest
========== End of log file ==========
</code></pre>
",https://stackoverflow.com/questions/61350125/unit-testing-adf-pipeline-with-specflow,"['c#', 'asp.net', 'specflow', 'azure-data-factory']",789,False,0,1
TextView InflateException on Navigation Unit Testing,"<p>I'm trying to test the Navigation of my app.</p>
<pre><code>@RunWith(AndroidJUnit4::class)
class CreateAccountTest {

@Test
fun init(){
    val mockNavController = mock(NavController::class.java)

    val titleScenario = launchFragmentInContainer&lt;CreateAccountPage1&gt;()

    titleScenario.onFragment { fragment -&gt;
        Navigation.setViewNavController(fragment.requireView(), mockNavController)
    }

    // Verify that performing a click prompts the correct Navigation action
    onView(withId(R.id.bt_create_accont)).perform(click())
    verify(mockNavController).navigate(R.id.action_createAccountPage1_to_createAccountPage2)
 }
}
</code></pre>
<p>XML:</p>
<pre><code>&lt;androidx.constraintlayout.widget.ConstraintLayout android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;

&lt;ImageView
    android:id=&quot;@+id/imageView19&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;240dp&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:src=&quot;@drawable/ic_ilu_account_creation&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

&lt;TextView
    android:id=&quot;@+id/textView226&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:text=&quot;...&quot;
    android:textColor=&quot;?text_color_dark&quot;
    android:textSize=&quot;18sp&quot;
    android:gravity=&quot;center&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/imageView19&quot; /&gt;

&lt;TextView
    android:id=&quot;@+id/textView227&quot;
    android:layout_width=&quot;0dp&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginStart=&quot;16dp&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:layout_marginEnd=&quot;16dp&quot;
    android:text=&quot;...&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/textView226&quot; /&gt;

&lt;Button
    app:layout_constraintVertical_bias=&quot;0.35&quot;
    app:backgroundTint=&quot;?button_link_color&quot;
    android:id=&quot;@+id/bt_create_accont&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;...&quot;
    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/textView227&quot; /&gt;

&lt;Button
    android:id=&quot;@+id/bt_voltar&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:text=&quot;...&quot;
    android:textColor=&quot;?text_color_dark&quot;
    app:backgroundTint=&quot;?backgroundColor&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/bt_create_accont&quot; /&gt;

&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
</code></pre>
<p>Stack tarce:</p>
<pre><code>java.lang.RuntimeException: android.view.InflateException: Binary XML file line #16 in 
.../fragment_create_account_page1: Binary XML file line #16 in 
.../fragment_create_account_page1: Error inflating class &lt;unknown&gt;

...

Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 5: TypedValue{t=0x2/d=0x7f04045d a=-1}
</code></pre>
<br>
Looks like the problem is on this line `android:textColor=""?text_color_dark""` 
<p>Why is this not supported? I use attributes to set the colors/icons of my app for both light and dark themes, the default is set in the manifest as the light theme.</p>
<pre><code>testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:core:1.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'org.mockito:mockito-core:2.23.4'
androidTestImplementation 'org.mockito:mockito-android:2.23.4'
debugImplementation 'androidx.fragment:fragment-testing:1.3.0-alpha06'
debugImplementation 'androidx.fragment:fragment-ktx:1.3.0-alpha06'
</code></pre>
",https://stackoverflow.com/questions/62544752/textview-inflateexception-on-navigation-unit-testing,"['android', 'unit-testing', 'navigation', 'expresso']",70,True,0,1
Override python statement during unit testing,"<p>I have 2 python program. one is main.py and another one is test_main.py
This is my main program(folder location ut3/ut)</p>
<pre><code>ut3/ut$ vi main.py
def functiona():
    print(&quot;function a  ***&quot;)
    functionb()
 
 
def functionb():
    print(&quot;function b  ***&quot;)
    functionc()
 
 
def functionc():
    print(&quot;function c  ***&quot;)
 
 
def fn_main():
    functiona()
 
</code></pre>
<p>This is my unit test file (folder location: ut3)</p>
<pre><code>ut3$ vi test_main.py
 
from ut import main
 
main.fn_main()
</code></pre>
<p>When I execute the test_main.py, it execute all the functions in the main.py program.
My requirement is :</p>
<p>first function: I want to call and execute only functiona(). Is there a way to override (or to remove the statement for functionb) ?
second function: Need to call only functionc. I can achieve this in the next statement using main.functionc().</p>
",https://stackoverflow.com/questions/64998702/override-python-statement-during-unit-testing,"['python-3.x', 'python-unittest']",63,False,0,1
Unit Testing coverage socket.io with mocha,"<p>Hi I am writing unit test cases for socket.io, test cases are passing but not reflecting in coverage how should I solve this issue. for more reference I posted code below
here is my code <strong>Index.js</strong></p>
<pre><code>const app = require('express')();
const server = require('http').Server(app);
const redis = require('redis');

var client = redis.createClient(process.env.redisPort,process.env.redisHost);
var client1 = redis.createClient(process.env.redisPort,process.env.redisHost);
var client2 = redis.createClient(process.env.redisPort,process.env.redisHost);
var client3 = redis.createClient(process.env.redisPort,process.env.redisHost);
const io = require('socket.io')(server);
const port = parseInt(process.env.PORT, 10) || 35082;
server.listen(port);

app.get('/', function (req, res) {
  res.send('ws server');
});

io.sockets
  .on('connection', 
  (socket) =&gt; {
    console.log(&quot;Socket Connected&quot;);
    client.on('message',function(channel,msg){
      socket.emit('pickedup',msg);
    });
    client.subscribe('pickedup');

    client1.on('message',function(channel,msg){
      socket.emit('order-da-issue',msg);
    });
    client1.subscribe('da-issue');

    client2.on('message',function(channel,msg){
      socket.emit('crew-issue',msg);
    });
    client2.subscribe('crew-issue');

    client3.on('message',function(channel,msg){
      socket.emit('da-break',msg);
    });
    client3.subscribe('da-break');
  });
</code></pre>
<p>Here is my <strong>index.test.js</strong> Actually it's not doing any core testing it's testing only socket connection.</p>
<pre><code>var io = require('socket.io-client'),
    assert = require('assert'),
    expect = require('expect.js');
describe('Suite of unit tests', function () {
    var socket;

    beforeEach(function (done) {
        socket = io.connect('http://localhost:35082', {
            'reconnection delay': 0,
            'reopen delay': 0,
            'force new connection': true
        });
        socket.on('connect', function () {
            console.log('worked...');
            done();
        });
        socket.on('disconnect', function () {
            console.log('disconnected...');
        })
    });
    afterEach(function (done) {
        if (socket.connected) {
            console.log('disconnecting...');
            socket.disconnect();
        } else {
            console.log('no connection to break...');
        }
        done();
    });

    describe('First (hopefully useful) test', function () {
        it('Doing something else with indexOf()', function (done) {
            expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
            expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
            done();
        });

    });

});
</code></pre>
<p>Here is my <strong>package.json</strong></p>
<pre><code>&quot;test&quot;: &quot;NODE_ENV=test mocha ./test/*.test.js --exit&quot;,
&quot;coverage&quot;: &quot;NODE_ENV=test nyc --reporter=json-summary --all --reporter=text --reporter=html --report-dir=./coverage npm test&quot;,
&quot;nyc&quot;: &quot;nyc --reporter=json-summary --reporter=text --reporter=html --report-dir=./coverage npm run test&quot;
</code></pre>
<p>Here is test coverage result</p>
<pre><code>Suite of unit tests
    First (hopefully useful) test
worked...
      ✓ Doing something else with indexOf()
disconnecting...
disconnected...


  1 passing (144ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |       0 |        0 |       0 |       0 |                   
 index.js |       0 |        0 |       0 |       0 | 1-124             
----------|---------|----------|---------|---------|-------------------
</code></pre>
<p>Thanks</p>
",https://stackoverflow.com/questions/63135158/unit-testing-coverage-socket-io-with-mocha,"['node.js', 'unit-testing', 'redis', 'socket.io', 'mocha.js']",558,False,0,0
Unit testing with @SpringBootTest(classes = Application.class),"<p>Currently a colleague is arguing that </p>

<p>My test written as below: </p>

<pre><code>@SpringBootTest(classes = App.class)
public class ServiceTest {

    private Integer a;
    private String str;


    @Before
    public void prepareTestData() {
       //
    }

    @Test
    public void test_scenario_1() {
        //
    } 
}
</code></pre>

<p>is not a unit test for my Service class because I am pulling through all the application using </p>

<pre><code>@SpringBootTest(classes = App.class)
</code></pre>

<p>I understand that unit tests should be testing the service code in complete isolation, but I am not having a autowire service depdency injection of any sort in my test code.</p>

<p>My question is what is the @SpringBootTest(classes = App.class) annotation doing behind the scenes is it really bootstraping the complete application before the test code is run? </p>

<p>Is the test above really an integration test?</p>
",https://stackoverflow.com/questions/59813055/unit-testing-with-springboottestclasses-application-class,"['java', 'spring-boot', 'testing']",2460,False,0,0
Javascript unit testing in Jasmin framework,"<p>I am new in JavaScript and unit testing. I have the following binary search code and I wanted to see if I can create some simple unit test cases for it in the Jasmine unit testing framework. However, for some reason my unit test is not working. 
&lt;</p>

<pre><code>script&gt; 
let Searching = function (array, x, start, end) { 

    // Base Condition 
    if (start &gt; end) return false; 

    // Find the middle index 
    let mid=Math.floor((start + end)/2); 

    // Compare mid with given key x 
    if (array[mid]===x) return true; 

    // If element at mid is greater than x, 
    // search in the left half of mid 
    if(array[mid] &gt; x) 
        return Searching(array, x, start, mid-1); 
    else

        // If element at mid is smaller than x, 
        // search in the right half of mid 
        return Searching(array, x, mid+1, end); 
} 

// Driver code 
let array = [1, 3, 5, 7, 8, 9]; 
let x = 5; 

if (Searching(array, x, 0, array.length-1)) 
    document.write(""Element found!&lt;br&gt;""); 
else document.write(""Element not found!&lt;br&gt;""); 

x = 6; 

if (Searching(array, x, 0, array.length-1)) 
    document.write(""Element found!&lt;br&gt;""); 
else document.write(""Element not found!&lt;br&gt;""); 
&lt;/script&gt;                                    

//unit testing

Describe ('Search Binary Algorithm', function () {
    var search = new Searching();
  it('should search in binary', function(){
      console.log (search ());
       expect(search (x).toEqual(5));
   });

});
</code></pre>

<p>When I run this one syntax error unexpected identifier. </p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/62378682/javascript-unit-testing-in-jasmin-framework,"['javascript', 'unit-testing']",26,False,0,0
unit testing Android function with handler,"<p>I'm working with unit testing for the first time and I'm lost with some specific cases.</p>

<p>Despite reading a lot I'm confused about how to test a function like this in Android:</p>

<pre><code>void myFunction() {

    MyThread myThread = new MyThread();
    myThread();
}

class MyThread extends Thread {

    public void run() {
        Looper.prepare();
        // Tasks to do in background
        handler.sendEmptyMessage(101);
    }
}

Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 101:
            // Get the results
            // Update UI        
        }
    }
};
</code></pre>

<p>I've read about ""CountDownLatch"" as in this SO answer <a href=""https://stackoverflow.com/a/5722193/1639825"">https://stackoverflow.com/a/5722193/1639825</a> but I don't know how to use this.</p>
",https://stackoverflow.com/questions/62430251/unit-testing-android-function-with-handler,"['android', 'unit-testing', 'android-handler', 'countdownlatch']",189,False,0,1
Azure Function Unit Testing with FunctionStartup,"<p>I am writing a unit test project for the azure functions which is using Startup class inheriting the FunctionStartUp. In this Startup class I am loading my all dependencies and configuration with Enviornment variables loading.</p>

<p>Problem is while running the unit test method I am getting the Enviornment variables values as null (because Startup class was not called hence Enviornment variables are not Set).</p>

<p>Can anyone suggest me how load Enviornment variables which are set in local.Setting.json and appsetting.json file?</p>
",https://stackoverflow.com/questions/60202346/azure-function-unit-testing-with-functionstartup,"['unit-testing', 'azure-functions']",1698,False,0,2
Unit Testing Graph API SDK c#,"<p>I am trying to mock this graph API SDK code.</p>
<pre><code> private readonly GraphServiceClient _client;
 IMailFolderMessagesCollectionPage msgs = await _client.Users[userEmailAddress].MailFolders[folderNameId]
                .Messages.Request().WithMaxRetry(5).WithMaxRetry(new TimeSpan(0, 0, 0, 5, 0)).Filter(emailFilter).GetAsync();
</code></pre>
<p>I am not sure how to mock a chained of index properties and method in a single line. I tried to do the following but does not work. Any advices? Thanks.</p>
<pre><code>  private Mock&lt;IGraphServiceClient&gt; mockGsc;
  mockGsc = new Mock&lt;IGraphServiceClient&gt;();
  mockGsc.Setup(x =&gt; x.Users[It.IsAny&lt;string&gt;()].MailFolders[It.IsAny&lt;string&gt;].Messages.Request().WithMaxRetry(It.IsAny&lt;int&gt;).WithMaxRetry(It.IsAny&lt;TimeSpan&gt;).Filter(It.IsAny&lt;string&gt;).GetAsync()).Returns&lt; IMailFolderMessagesCollectionPage&gt;();
</code></pre>
",https://stackoverflow.com/questions/64853318/unit-testing-graph-api-sdk-c,"['c#', 'unit-testing', '.net-core', 'microsoft-graph-api']",1149,True,0,1
Android Unit Testing using Navigation Architecture,"<p>i am using Android Navigation Component which has 1 activity named as <strong>Authentication Activity</strong> which contains 3 fragments named <strong>SplashFragment</strong>, <strong>Login Fragment</strong>, <strong>OTP Fragment</strong>.</p>
<p>I want to do Unit Testing for Login Fragment which contains different fields like Mobile Number, Name, Email, State dropDown.</p>
<p>Please help me out how to write Unit test cases for Mobile number field, Name, email. I had attached sample unit test code of mine, gradle dependency.</p>
<p>Framework tried:- <strong>Mockito</strong>, <strong>Espresso</strong>, <strong>Roboelectric</strong></p>
<p>Thanks in advance.</p>
<pre><code>@Test
fun vmInitialization() {
    val state1 = State(&quot;DL&quot;, &quot;Delhi&quot;)
    val state2 = State(&quot;UP&quot;, &quot;Uttar Pradesh&quot;)
    val list: ArrayList&lt;State&gt; = ArrayList()
    list!!.add(state1)
    list!!.add(state2)
    val bundle = Bundle().putParcelableArrayList(&quot;stateList&quot;, list as ArrayList&lt;Parcelable&gt;)
    launchFragment(R.id.loginFragment, bundle as Bundle)
    val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
    navController.setGraph(R.navigation.nav_graph_auth)
    val scenario = launchFragmentInContainer&lt;LoginFragment&gt;()
    navController.setViewModelStore(ViewModelStore())
    scenario.onFragment { fragment -&gt;
        Navigation.setViewNavController(fragment.requireView(), navController)
    }
    onView(ViewMatchers.withId(R.id.btn_proceed)).perform(ViewActions.click())
    val navGraph = navController.navigatorProvider.navigation(
        id = R.id.nav_graph_auth,
        startDestination = R.id.otpFragment
    ) {
    }
    navController.setGraph(navGraph, null)
    scenario.onFragment { fragment -&gt;
        assertNotNull(fragment)
        assertThat(fragment).isNotNull()
        assertThat(fragment.savedStateViewModel).isNotNull()
    }
}
</code></pre>
<p>Gradle dependencies:-</p>
<pre><code>debugImplementation &quot;androidx.navigation:navigation-testing:2.3.0-alpha06&quot;
debugImplementation &quot;androidx.test:runner:1.2.0&quot;
debugImplementation &quot;androidx.test:core:1.2.0&quot;
debugImplementation(&quot;androidx.test:rules:1.2.0&quot;)
debugImplementation(&quot;androidx.fragment:fragment-ktx:1.1.0-beta01&quot;)
debugImplementation &quot;androidx.test.ext:junit-ktx:1.1.1&quot;
debugImplementation('androidx.fragment:fragment-testing:1.1.0') {
    // exclude androidx.test:core while fragment_testing depends on 1.1.0
    exclude group: 'androidx.test', module: 'core'
}
</code></pre>
",https://stackoverflow.com/questions/63788257/android-unit-testing-using-navigation-architecture,"['android', 'unit-testing', 'kotlin', 'junit']",869,False,0,1
Unit testing an array converted set,"<p>I have an array. I am required to convert it into set and then unit test. I successfully did the array to set conversation. But the unit test is not working. I am a new learner specially in unit testing. Please help.</p>
<pre><code>public class ArrToSet {

    public static void main(String[] args) {
        String[] array = {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;};
        System.out.println(&quot;Original Array: &quot; + Arrays.toString(array));
    
        System.out.println(&quot;Array converted to Set: &quot; + Arrays.stream(array).collect(Collectors.toSet()));
    
    }
}
</code></pre>
<p>The unit test case I have written:</p>
<pre><code>class ArrToSetTest {
    @Test
    void test() {

        ArrToSet ar = new ArrToSet();
    
         Set&lt;String&gt; set = new HashSet&lt;&gt;();
            set.add(&quot;a&quot;);
            set.add(&quot;b&quot;);
            set.add(&quot;c&quot;);

        String actual[] = {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;};
    
        assertEquals(set,actual);
   }
}
</code></pre>
",https://stackoverflow.com/questions/63019542/unit-testing-an-array-converted-set,['java'],477,True,-2,1
Angular Custom Validator Unit Testing Failing,"<p>The validator is as follows :</p>
<pre><code>import { AbstractControl } from &quot;@angular/forms&quot;;



export function ValidateInt(control: AbstractControl): { [key: string]: boolean } | null {
 
  function countPlaces(value) {
    var text = value.toString();
    var index = text.indexOf(&quot;.&quot;);
    return index == -1 ? 0 : (text.length - index - 1);
   }

  function checkNumeric(value) {
    return !isNaN(parseFloat(value)) &amp;&amp; isFinite(value);
  }
  let controlValue = control.value.toString();
  let trailingDec = controlValue.indexOf('.') == -1 ;
  let decimalCount = countPlaces(control.value) ;
  let isNumeric = checkNumeric(control.value) ;

 if(isNumeric == false ){
    return { 'int': true };
  }else if(trailingDec == false){
    return { 'int': true };
  }else{ return null}

}
</code></pre>
<p>The Test File is as follows :</p>
<pre><code>import * as intValid from './intValidator.validator' ;
import { AbstractControl, FormControl, Validators} from &quot;@angular/forms&quot;;


describe('validate int', () =&gt; {
    var intControl : AbstractControl = new FormControl('', Validators.required);
        intControl.setValue(23) ; 
    
    fit('returns true', () =&gt; {
      let actual = intValid.ValidateInt(intControl);
      expect(actual).toEqual(null);
    });
});

describe('validate int', () =&gt; {
  var intControl : AbstractControl = new FormControl('', Validators.required);
      intControl.setValue(23.) ; 
    let badReturn = { 'int': true};
    fit('returns false', () =&gt; {
      let actual = intValid.ValidateInt(intControl);
      expect(actual).toEqual(badReturn);
    });
});
</code></pre>
<p>The error is :</p>
<pre><code>validate int returns false FAILED
        Error: Expected null to equal Object({ int: true }).
</code></pre>
<p>I cannot for the life of me figure out why the test fails, when I follow the control flow in the debugger with breakpoints as the solution is running, the proper control with 'INVALID' is returning.</p>
",https://stackoverflow.com/questions/63093657/angular-custom-validator-unit-testing-failing,"['angular', 'unit-testing', 'karma-jasmine', 'customvalidator']",79,False,0,1
Unit testing with EasyMock and Spring,"<p>In my project i have UtilClass for example A(all method static, private constructor). I need to test one of this static method a(13 parameters). This class have one dependencies(another class B). Class B - static field in class A. In code smth like that:</p>

<pre><code>public class A{
    private static B b = AppContext.getBean(B.class);

    public static C a(""14 parameters"") throw MyException{
        try{
        b.call(""13 parameters"");
        }catch(MyExceptionSecond e){
            MyException newException = new MyException(msg,e);
            if(e.getCode() == smth){
                //do smth
            }
            throw privateMethodClassA(newException);
        }
    }
}
</code></pre>

<p>I need to test how working privateMethodClassA, for that i mocked class B in config-test.xml:</p>

<pre><code>&lt;bean class=""org.easymock.EasyMock"" factory-method=""createMock"" primary=""true"" id=""classB""&gt;
    &lt;constructor-arg value=""com.my.package.B""/&gt;
&lt;/bean&gt;
</code></pre>

<p>That is my test and setUp method:</p>

<pre><code>public class MyTest {
   private B b;

@Before
public void setUp() throws Exception {

    b = AppContext.getBean(B.class);
    expect(b.call(""13 paramaters""))
        .andThrow(
            new MyExceptionSecond(""some error code"", ""testMessage"", new Object()))
        .anyTimes();
    replay(b);
}

@Test(expected = MyException.class)
public void testExceptionMethod() throws Exception {
    A.a(""13 parametrs"");
}
}
</code></pre>

<p>If I evaluating in debug b.call(""13 parameters"") everything all right(in context test), but in the same debug going into context call class A and evaluate b.call(""13 parameters
"") with the same parameters mocked object return null, instead of MyExceptionSecond as in the first case. The problem is - i can't get the MyException error all my attempts led to : 
<code>java.lang.AssertionError: Expected exception: com.my.package.MyException</code>
What do you think about this issue? </p>

<p>P.S My guess is that this is a problem in the attachment of expect() to the context of the test and not to the moсk itself.</p>

<p>P.P.S java8, EasyMock 4.2, spring 4.2.8, AppContext == org.springframework.context.ApplicationContext.</p>
",https://stackoverflow.com/questions/60623490/unit-testing-with-easymock-and-spring,"['java', 'spring', 'unit-testing', 'junit', 'easymock']",119,False,0,0
.Net Core Unit Testing With Url.Action,"<p>I am currently running unit tests on a controller that utilizes Url.Action to get the absolute path of two different routes. I am using Moq to set up the mock Action. The test is currently failing with the message 'Object reference not set to an instance of an object.' </p>

<p>[Edit - Clarifying the question]</p>

<p>When I debug the test, the Url shows to as a <code>Mock&lt;IUrlHelper&gt;</code> with an <code>ActionContext</code> property, but on the line where it calls the <code>Url.Action</code>, the <code>Action</code> property shows as null. What am I missing when setting up the <code>Mock&lt;IUrlHelper&gt;</code> that way the <code>Url.Action</code> doesn't come back as null?</p>

<p>I've checked multiple options for setting up Mock Url Actions, but nothing has seemed to work for me. </p>

<p>Here is the setup for the test</p>

<pre><code>[Fact]
public async void SendGroup_PassesDetailsToNotificationService()
{
    UrlActionContext actualContext = null;
    var criteria = new NotificationCriteria { Section = 1, Subsection = 2 };
    userSvc.GetNotificationGroupReturnValue = new List&lt;NotificationRecipient&gt;
        {
            new NotificationRecipient{ SmsAuth = true } 
        };
    var actionContext = new ActionContext
        {
            ActionDescriptor = new ActionDescriptor(),
            RouteData = new RouteData(),
        };
    var urlHelper = new Mock&lt;IUrlHelper&gt;();
    urlHelper.SetupGet(h =&gt; h.ActionContext).Returns(actionContext);
    urlHelper.Setup(h =&gt; h.Action(It.IsAny&lt;UrlActionContext&gt;()))
             .Callback((UrlActionContext context) =&gt; actualContext = context);
    controller.Url = urlHelper.Object;

    var dummy = await controller.SendGroup(criteria);

    Assert.Same(criteria, notificationSvc.SendGroupNotificationDetailUsed);
}
</code></pre>

<p>This is the code for the controller</p>

<pre><code>[HttpPost]
public async Task&lt;IActionResult&gt; SendGroup([FromBody]NotificationCriteria criteria)
{
    List&lt;NotificationRecipient&gt; recipients = (await userSvc.GetNotificationGroup(
                                              criteria.Section, criteria.Subsection)).ToList();

    if (!recipients.Any())
    {
        return BadRequest();
    }

    var uro = Url;
    var sectionUrl = Url.Action(""Index"", ""ReportHome"", new {sectionId = criteria.Section}, Request.Scheme);
    var profileUrl = Url.Action(""Index"", ""Profile"", null, Request.Scheme);
    var detail = new NotificationDetail
    {
        SectionUrl = sectionUrl,
        ProfileUrl = profileUrl,
        Recipients = recipients
    };
    try
    {
        await notificationSvc.SendGroupNotification(detail);
    }
    catch 
    {
        return StatusCode(500);
    }

    return Ok();
}
</code></pre>
",https://stackoverflow.com/questions/61703395/net-core-unit-testing-with-url-action,"['c#', 'unit-testing', 'asp.net-core-mvc', 'moq', 'url-action']",425,False,0,0
Unit Testing a @Query Repository Class,"<p>I've got a Repo class in a java spring project, that interacts with a DB (neo4j).</p>

<p>The methods look like this:</p>

<pre><code>@Query(""call example.method({0})"")
String getExampleResult(String id);
</code></pre>

<p>Since this is a unit test, I will need to mock out the call, but I have no idea how to do this. Anyone with experience here?</p>
",https://stackoverflow.com/questions/61637681/unit-testing-a-query-repository-class,"['java', 'spring', 'unit-testing']",40,False,0,0
unit testing spring boot with mockito,"<p>So i have searched all related questions here and found no answer that worked on mine. With that being said I am trying to unit test my spring-boot application with Mockito. </p>

<p>Here is my controller and the function i am trying to test.</p>

<pre><code>@RestController
public class UserController {

   @Autowired
   UserRepository userRepository;


   @GetMapping(""/user"")
   public List&lt;User&gt; getAllUsers() {
       return userRepository.findAll();
   }

   @GetMapping(""/user/{id}"")
   public User getUser(@PathVariable Integer id) {
       return userRepository.findById(id).get();
   }
</code></pre>

<p>I am trying to test <code>getUser</code> function </p>

<p>here is my Test Controller</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)

public class UserControllerTest {

    private MockMvc mockMvc;

    @MockBean
    private UserController userController;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
    }
    @Test
    public void getUserTest() throws Exception{

  mockMvc.perform(get(""/user/100"").contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(""application/json""))
                .andExpect(jsonPath(""$.role"").value(""deliverer""));

    }
</code></pre>

<p>So firstly when I run this i get following error</p>

<pre><code>java.lang.AssertionError: Content type not set

    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:37)
    at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:70)
    at org.springframework.test.util.AssertionErrors.assertNotNull(AssertionErrors.java:106)
    at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$contentTypeCompatibleWith$1(ContentResultMatchers.java:103)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at eldercare.RESTapi.controller.UserControllerTest.getUserTest(UserControllerTest.java:57)
    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:567)
    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:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    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.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>

<p>with following data being printed </p>

<pre><code>MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
</code></pre>

<p>I have tested putting <code>@ResponseBody</code> in my Controller does not make any difference. I have also tested as stated in other post <code>@RequestMapping(value=""/user/{id}"", method= RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)</code> that doesn't work either still get the same error.</p>

<p>If I dont have this check <code>.andExpect(content().contentTypeCompatibleWith(""application/json""))</code> then i get the error stating <code>java.lang.AssertionError: No value at JSON path ""$.role""</code></p>
",https://stackoverflow.com/questions/61784337/unit-testing-spring-boot-with-mockito,"['java', 'spring', 'spring-boot', 'junit', 'mockito']",213,True,0,1
Jasmine unit testing on transient property,"<p>I have a controller class whose constructor returns a completely separate object, but whose instance is ""attached"" to one of its own properties via members of the object it returns, like this:</p>

<pre><code>//the controller class
define('myControllerClass', 
    ['myOtherClass'], function (myOtherClass) {
    //constructor
    function myControllerClass() {
        var that = this;
        this.renderingModule = null;
        this.aProperty = false;

        return {
            action1: function() {
                that.aProperty = true;
                that.renderingModule = new myOtherClass({
                    controller: that
                });
            },
            action2: function() {
                that.renderingModule = new myOtherClass({
                    controller: that
                });
            }
        }
    };
    return myControllerClass;
});

define('myOtherClass', [], function () {
    function myOtherClass(params) {
        this.controller = params.controller;

        if(this.controller.aProperty) doSomething();
    }

    return myOtherClass;
});

define('myTest' ['myControllerClass'], function(myControllerClass){
    //the test
    describe('test my controller class', function() {
        beforeEach(function() {
            this.controller = new myControllerClass();
        });

        it('Should set aProperty to true on action 1', function(done) {
            this.controller.action1();

            expect(this.controller.aProperty).toBe(true); // does not work because this.controller is an object containing the 2 actions
        })
    });
})

</code></pre>

<p>So the rendering module can access properties from the controller, but from the test I don't have any means to do so without instantiating a separate redering module.
Are there any tricks in Jasmine that would allow me to test on the value of aProperty?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/61940971/jasmine-unit-testing-on-transient-property,"['javascript', 'unit-testing', 'karma-jasmine']",57,False,0,0
Mock dutchcoders/goftp for unit testing,"<p>I'm using <a href=""https://github.com/dutchcoders/goftp"" rel=""nofollow noreferrer"">dutchcoders/goftp</a> in my code, and for unit testing purpose, I need to mock it.</p>

<p>Thing is this component doesn't have interface, nor avaible mocks, so I tried to create some:</p>

<p>in <code>goftp/ftp.go</code>, </p>

<p>I added interface:</p>

<pre><code>type FTPIface interface {
    Close() error
    Walk(path string, walkFn WalkFunc) (err error)
    Rename(from string, to string) (err error)
    Login(username string, password string) (err error)
}
</code></pre>

<p>Now I can mock all the methods I use but <code>Connect()</code>, because connect has no receiver.</p>

<p>You use like like that:</p>

<pre><code>if client, err = goftp.Connect(Host); err != nil {
        return nil, err
    }
</code></pre>

<p>So I tried to change it to be able to mock it:</p>

<pre><code>func NewMyFTP(ftpIface goftp.FTPIface, host, user, password, name string) (*MyFTP, error) 
{ 
    if Client, err = ftpIface.Connect(Host); err != nil {
        return nil, err
    }
    if err = Client.Login(user, password); err != nil {
        return nil, err
    }
}
</code></pre>

<p>and added <code>Connect()</code> to interface definition</p>

<pre><code>Connect(addr string) (*FTP, error)
</code></pre>

<p>Thing is I can mock connect, but it will return a FTP object, and I will not be able to mock <code>Login()</code></p>

<p>So, what should I do ?</p>

<ol>
<li>Change go client ? I wouldn't like to do that, as I have implemented it in all my code.</li>
<li>Implement a dev ftp server: Can be a good and simple idea, but I will mix Unit test and functional test, keeping an external dependency.</li>
<li>Finding a technical solution to my problem and mock it ?</li>
</ol>
",https://stackoverflow.com/questions/61059717/mock-dutchcoders-goftp-for-unit-testing,"['unit-testing', 'go', 'ftp', 'mocking']",346,False,0,0
Unit testing WPF FrameworkElement loading problems,"<p>I am trying to make unit tests for a WPF application via rendering the window in the test thread and examining components to make sure everything's there and working. I am able to get the window to load on an STA thread and show the content correctly on visual inspection, but the main window loads in a custom panel, and that panel's FrameworkElement.Loaded event does not fire as it should when I call Show and Activate, but it does fire in the main code. I have tried this on MSTest, Xunit, and Nunit. From looking around I'm assuming the issue is some part of WPF that is not being set up in test threads, but I don't know which, not familiar enough with the workings of WPF. What do I need to add to make it so my tests properly fire the Loaded event, and how can I do that in the unit test format(s)?</p>
",https://stackoverflow.com/questions/62826939/unit-testing-wpf-frameworkelement-loading-problems,"['c#', 'wpf', 'unit-testing']",242,False,0,0
Swift unit testing view model interface,"<p>As I understand, it is best to only test public methods of a class.</p>

<p>Let's have a look at this example. I have a view model for the view controller.</p>

<pre><code>protocol MyViewModelProtocol {

   var items: [SomeItem] { get }
   var onInsertItemsAtIndexPaths: (([IndexPath]) -&gt; Void)? { get set }

   func viewLoaded()
}

class MyViewModel: MyViewModelProtocol {

   func viewLoaded() {
        let items = createDetailsCellModels()
        updateCellModels(with: items)
        requestDetails()
   }
}

</code></pre>

<p>I want to test class viewLoaded(). This class calls two other methods - updateItems() and requestDetails()
One of the methods sets up the items and the other one call API to retrieve data and update those items. Items array us updated two times and onInsertItemsAtIndexPaths are called two times - when setting up those items and when updating with new data.</p>

<p>I can test whether after calling viewLoaded() expected items are set up and that onInsertItemsAtIndexPaths is called.  </p>

<p>However, the test method will become rather complex. </p>

<p>What is your view, should I test those two methods separately or just write this one huge test?</p>

<p>By testing only viewLoaded(), my idea is that the implementation can change and I only care that results are what I expect. </p>
",https://stackoverflow.com/questions/61279675/swift-unit-testing-view-model-interface,"['swift', 'unit-testing', 'testing', 'mvvm']",1566,True,0,1
Unit testing with Codeception: parsing error,"<p>I'm trying to write some Unit Tests for my simple website (for study).</p>
<p>Project structure:</p>
<p><a href=""https://i.stack.imgur.com/ePcBp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ePcBp.png"" alt=""project"" /></a></p>
<p>Inside index.php I have a <code>namespace Main</code> defined.</p>
<p>Functions lie in <code>namespace Main\Logic</code> and Classes lie in <code>namespace Main\Logic\Classes</code>.</p>
<p>Code for <code>tests/unit/BuildGalleryTest.php</code>:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php

namespace Tests\Unit;

use Codeception\Test\Unit as TestCase;

use function Main\Logic\galleryBuilder;

require &quot;/Users/l.marder/Homeworks/php-study/lesson4/logic/galleryBuilder.php&quot;;

class BuildGalleryTest extends TestCase
{

    /**
     * @dataProvider buildGalleryDataProvider
     * @param string $imgPack
     * @param string $expectedResponse
     */
    public function testBuildGallery(string $imgPack, string $expectedResponse): void
    {
        $actualResponse = galleryBuilder(&quot;tests/unit/test_data/img/$imgPack&quot;);
        self::assertEquals($expectedResponse, $actualResponse);
    }

    public function buildGalleryDataProvider(): array
    {
        return
            [
                &quot;Data pack 1: one pic&quot; =&gt; [
                    &quot;1&quot;,
                    $this-&gt;buildTestGallery(&quot;1&quot;)
                ],
                &quot;Data pack 2: two pics with folder and text.txt file&quot; =&gt; [
                    &quot;2&quot;,
                    $this-&gt;buildTestGallery(&quot;2&quot;)
                ],
                &quot;Data pack 3: no images&quot; =&gt; [
                    &quot;3&quot;,
                    $this-&gt;buildTestGallery(&quot;3&quot;)
                ]
            ];
    }

    private function buildTestGallery(string $dataPack): string
    {
        if ($dataPack === &quot;1&quot;) {
            return &quot;
            &lt;a href=\&quot;picture.php?img=tests/unit/test_data/img/1/1.img\&quot; target=\&quot;_blank\&quot;&gt;
                &lt;div class=\&quot;small-pic\&quot;&gt;
                    &lt;img class=\&quot;img-small-kit\&quot; src= alt=\&quot;Kitty 2\&quot;&gt;
                &lt;/div&gt;
            &lt;/a&gt;&quot;;
        }
        if ($dataPack === &quot;2&quot;) {
            return &quot;
            &lt;a href=\&quot;picture.php?img=tests/unit/test_data/img/2/1.img\&quot; target=\&quot;_blank\&quot;&gt;
                &lt;div class=\&quot;small-pic\&quot;&gt;
                    &lt;img class=\&quot;img-small-kit\&quot; src=tests/unit/test_data/img/2/1.img alt=\&quot;Kitty 2\&quot;&gt;
                &lt;/div&gt;
            &lt;/a&gt;
            &lt;a href=\&quot;picture.php?img=tests/unit/test_data/img/2/2.img\&quot; target=\&quot;_blank\&quot;&gt;
                &lt;div class=\&quot;small-pic\&quot;&gt;
                    &lt;img class=\&quot;img-small-kit\&quot; src=tests/unit/test_data/img/2/2.img alt=\&quot;Kitty 3\&quot;&gt;
                &lt;/div&gt;
            &lt;/a&gt;&quot;;
        }
        if ($dataPack === &quot;3&quot;) {
            return &quot;&lt;img class=\&quot;img-big-pic\&quot; src=tests/unit/test_data/3/404.gif alt=\&quot;Kitty Pic\&quot;&gt;&quot;;
        }

        return &quot;&quot;;
    }
}

</code></pre>
<p>When running <code>php vendor/bin/codecept run</code> I'm getting the following error:</p>
<pre><code>In Parser.php line 128:
                                                                                                                     
  Couldn't parse test '/Users/l.marder/Homeworks/php-study/lesson4/tests/unit/logic/BuildGalleryTest.php' on line 9  
  syntax error, unexpected 'int' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)      
</code></pre>
<p>What am I doing wrong? What can be done to resolve this problem?</p>
",https://stackoverflow.com/questions/62820989/unit-testing-with-codeception-parsing-error,"['php', 'automated-tests', 'phpunit', 'codeception']",234,True,0,1
Unit Testing Exceptions in Dart/Flutter,"<p>I'm trying to unit test using the given code.</p>
<pre><code>test('Given Employee When employeeName less than 5 then throws Exception', () async {
    final employee = EmployeesCompanion.insert(
        employeeName: 'Tony',
        employeeCode: 'HR-121',
        address: '5th Floor, Park Avenue',
        contact: '1234567890',
        hiringDate: DateTime.now());
    expectLater(await employeesDB.createEmployee(employee),
        throwsA((f) =&gt; f.toString().contains('employeeName: Must at least be 5 characters long')));
  });
</code></pre>
<p>My unit test includes a predicate <code>throwsA((f) =&gt; f.toString().contains('employeeName: Must at least be 5 characters long'))</code> as given but dart fails this test with the exception:</p>
<pre><code>package:moor/src/runtime/data_verification.dart 74:5                  VerificationContext.throwIfInvalid
package:moor/src/runtime/query_builder/statements/insert.dart 197:51  InsertStatement._validateIntegrity
package:moor/src/runtime/query_builder/statements/insert.dart 96:5    InsertStatement.createContext
package:moor/src/runtime/query_builder/statements/insert.dart 64:17   InsertStatement.insert
package:moor_ex/src/db/employees.dart 79:76                           EmployeesDB.createEmployee
test\employee_dept_test.dart 28:35                                    main.&lt;fn&gt;

InvalidDataException: Sorry, EmployeesCompanion(id: Value.absent(), employeeName: Value(Tony), employeeCode: Value(HR-121), address: Value(5th Floor, Park Avenue), contact: Value(1234567890), hiringDate: Value(2020-08-18 13:26:34.435349)) cannot be used for that because: 
• employeeName: Must at least be 5 characters long.
</code></pre>
<p>So what's the correct way to write this test in Dart?</p>
",https://stackoverflow.com/questions/63464412/unit-testing-exceptions-in-dart-flutter,"['dart', 'flutter-test']",483,True,0,1
TextView InflateException on Navigation Unit Testing,"<p>I'm trying to test the Navigation of my app.</p>
<pre><code>@RunWith(AndroidJUnit4::class)
class CreateAccountTest {

@Test
fun init(){
    val mockNavController = mock(NavController::class.java)

    val titleScenario = launchFragmentInContainer&lt;CreateAccountPage1&gt;()

    titleScenario.onFragment { fragment -&gt;
        Navigation.setViewNavController(fragment.requireView(), mockNavController)
    }

    // Verify that performing a click prompts the correct Navigation action
    onView(withId(R.id.bt_create_accont)).perform(click())
    verify(mockNavController).navigate(R.id.action_createAccountPage1_to_createAccountPage2)
 }
}
</code></pre>
<p>XML:</p>
<pre><code>&lt;androidx.constraintlayout.widget.ConstraintLayout android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;

&lt;ImageView
    android:id=&quot;@+id/imageView19&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;240dp&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:src=&quot;@drawable/ic_ilu_account_creation&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

&lt;TextView
    android:id=&quot;@+id/textView226&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:text=&quot;...&quot;
    android:textColor=&quot;?text_color_dark&quot;
    android:textSize=&quot;18sp&quot;
    android:gravity=&quot;center&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/imageView19&quot; /&gt;

&lt;TextView
    android:id=&quot;@+id/textView227&quot;
    android:layout_width=&quot;0dp&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginStart=&quot;16dp&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:layout_marginEnd=&quot;16dp&quot;
    android:text=&quot;...&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/textView226&quot; /&gt;

&lt;Button
    app:layout_constraintVertical_bias=&quot;0.35&quot;
    app:backgroundTint=&quot;?button_link_color&quot;
    android:id=&quot;@+id/bt_create_accont&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;...&quot;
    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/textView227&quot; /&gt;

&lt;Button
    android:id=&quot;@+id/bt_voltar&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_marginTop=&quot;16dp&quot;
    android:text=&quot;...&quot;
    android:textColor=&quot;?text_color_dark&quot;
    app:backgroundTint=&quot;?backgroundColor&quot;
    app:layout_constraintEnd_toEndOf=&quot;parent&quot;
    app:layout_constraintStart_toStartOf=&quot;parent&quot;
    app:layout_constraintTop_toBottomOf=&quot;@+id/bt_create_accont&quot; /&gt;

&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
</code></pre>
<p>Stack tarce:</p>
<pre><code>java.lang.RuntimeException: android.view.InflateException: Binary XML file line #16 in 
.../fragment_create_account_page1: Binary XML file line #16 in 
.../fragment_create_account_page1: Error inflating class &lt;unknown&gt;

...

Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 5: TypedValue{t=0x2/d=0x7f04045d a=-1}
</code></pre>
<br>
Looks like the problem is on this line `android:textColor=""?text_color_dark""` 
<p>Why is this not supported? I use attributes to set the colors/icons of my app for both light and dark themes, the default is set in the manifest as the light theme.</p>
<pre><code>testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:core:1.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'org.mockito:mockito-core:2.23.4'
androidTestImplementation 'org.mockito:mockito-android:2.23.4'
debugImplementation 'androidx.fragment:fragment-testing:1.3.0-alpha06'
debugImplementation 'androidx.fragment:fragment-ktx:1.3.0-alpha06'
</code></pre>
",https://stackoverflow.com/questions/62544752/textview-inflateexception-on-navigation-unit-testing,"['android', 'unit-testing', 'navigation', 'expresso']",70,True,0,1
Override python statement during unit testing,"<p>I have 2 python program. one is main.py and another one is test_main.py
This is my main program(folder location ut3/ut)</p>
<pre><code>ut3/ut$ vi main.py
def functiona():
    print(&quot;function a  ***&quot;)
    functionb()
 
 
def functionb():
    print(&quot;function b  ***&quot;)
    functionc()
 
 
def functionc():
    print(&quot;function c  ***&quot;)
 
 
def fn_main():
    functiona()
 
</code></pre>
<p>This is my unit test file (folder location: ut3)</p>
<pre><code>ut3$ vi test_main.py
 
from ut import main
 
main.fn_main()
</code></pre>
<p>When I execute the test_main.py, it execute all the functions in the main.py program.
My requirement is :</p>
<p>first function: I want to call and execute only functiona(). Is there a way to override (or to remove the statement for functionb) ?
second function: Need to call only functionc. I can achieve this in the next statement using main.functionc().</p>
",https://stackoverflow.com/questions/64998702/override-python-statement-during-unit-testing,"['python-3.x', 'python-unittest']",63,False,0,1
Unit Testing coverage socket.io with mocha,"<p>Hi I am writing unit test cases for socket.io, test cases are passing but not reflecting in coverage how should I solve this issue. for more reference I posted code below
here is my code <strong>Index.js</strong></p>
<pre><code>const app = require('express')();
const server = require('http').Server(app);
const redis = require('redis');

var client = redis.createClient(process.env.redisPort,process.env.redisHost);
var client1 = redis.createClient(process.env.redisPort,process.env.redisHost);
var client2 = redis.createClient(process.env.redisPort,process.env.redisHost);
var client3 = redis.createClient(process.env.redisPort,process.env.redisHost);
const io = require('socket.io')(server);
const port = parseInt(process.env.PORT, 10) || 35082;
server.listen(port);

app.get('/', function (req, res) {
  res.send('ws server');
});

io.sockets
  .on('connection', 
  (socket) =&gt; {
    console.log(&quot;Socket Connected&quot;);
    client.on('message',function(channel,msg){
      socket.emit('pickedup',msg);
    });
    client.subscribe('pickedup');

    client1.on('message',function(channel,msg){
      socket.emit('order-da-issue',msg);
    });
    client1.subscribe('da-issue');

    client2.on('message',function(channel,msg){
      socket.emit('crew-issue',msg);
    });
    client2.subscribe('crew-issue');

    client3.on('message',function(channel,msg){
      socket.emit('da-break',msg);
    });
    client3.subscribe('da-break');
  });
</code></pre>
<p>Here is my <strong>index.test.js</strong> Actually it's not doing any core testing it's testing only socket connection.</p>
<pre><code>var io = require('socket.io-client'),
    assert = require('assert'),
    expect = require('expect.js');
describe('Suite of unit tests', function () {
    var socket;

    beforeEach(function (done) {
        socket = io.connect('http://localhost:35082', {
            'reconnection delay': 0,
            'reopen delay': 0,
            'force new connection': true
        });
        socket.on('connect', function () {
            console.log('worked...');
            done();
        });
        socket.on('disconnect', function () {
            console.log('disconnected...');
        })
    });
    afterEach(function (done) {
        if (socket.connected) {
            console.log('disconnecting...');
            socket.disconnect();
        } else {
            console.log('no connection to break...');
        }
        done();
    });

    describe('First (hopefully useful) test', function () {
        it('Doing something else with indexOf()', function (done) {
            expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
            expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
            done();
        });

    });

});
</code></pre>
<p>Here is my <strong>package.json</strong></p>
<pre><code>&quot;test&quot;: &quot;NODE_ENV=test mocha ./test/*.test.js --exit&quot;,
&quot;coverage&quot;: &quot;NODE_ENV=test nyc --reporter=json-summary --all --reporter=text --reporter=html --report-dir=./coverage npm test&quot;,
&quot;nyc&quot;: &quot;nyc --reporter=json-summary --reporter=text --reporter=html --report-dir=./coverage npm run test&quot;
</code></pre>
<p>Here is test coverage result</p>
<pre><code>Suite of unit tests
    First (hopefully useful) test
worked...
      ✓ Doing something else with indexOf()
disconnecting...
disconnected...


  1 passing (144ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |       0 |        0 |       0 |       0 |                   
 index.js |       0 |        0 |       0 |       0 | 1-124             
----------|---------|----------|---------|---------|-------------------
</code></pre>
<p>Thanks</p>
",https://stackoverflow.com/questions/63135158/unit-testing-coverage-socket-io-with-mocha,"['node.js', 'unit-testing', 'redis', 'socket.io', 'mocha.js']",558,False,0,0
Unit testing with @SpringBootTest(classes = Application.class),"<p>Currently a colleague is arguing that </p>

<p>My test written as below: </p>

<pre><code>@SpringBootTest(classes = App.class)
public class ServiceTest {

    private Integer a;
    private String str;


    @Before
    public void prepareTestData() {
       //
    }

    @Test
    public void test_scenario_1() {
        //
    } 
}
</code></pre>

<p>is not a unit test for my Service class because I am pulling through all the application using </p>

<pre><code>@SpringBootTest(classes = App.class)
</code></pre>

<p>I understand that unit tests should be testing the service code in complete isolation, but I am not having a autowire service depdency injection of any sort in my test code.</p>

<p>My question is what is the @SpringBootTest(classes = App.class) annotation doing behind the scenes is it really bootstraping the complete application before the test code is run? </p>

<p>Is the test above really an integration test?</p>
",https://stackoverflow.com/questions/59813055/unit-testing-with-springboottestclasses-application-class,"['java', 'spring-boot', 'testing']",2460,False,0,0
Javascript unit testing in Jasmin framework,"<p>I am new in JavaScript and unit testing. I have the following binary search code and I wanted to see if I can create some simple unit test cases for it in the Jasmine unit testing framework. However, for some reason my unit test is not working. 
&lt;</p>

<pre><code>script&gt; 
let Searching = function (array, x, start, end) { 

    // Base Condition 
    if (start &gt; end) return false; 

    // Find the middle index 
    let mid=Math.floor((start + end)/2); 

    // Compare mid with given key x 
    if (array[mid]===x) return true; 

    // If element at mid is greater than x, 
    // search in the left half of mid 
    if(array[mid] &gt; x) 
        return Searching(array, x, start, mid-1); 
    else

        // If element at mid is smaller than x, 
        // search in the right half of mid 
        return Searching(array, x, mid+1, end); 
} 

// Driver code 
let array = [1, 3, 5, 7, 8, 9]; 
let x = 5; 

if (Searching(array, x, 0, array.length-1)) 
    document.write(""Element found!&lt;br&gt;""); 
else document.write(""Element not found!&lt;br&gt;""); 

x = 6; 

if (Searching(array, x, 0, array.length-1)) 
    document.write(""Element found!&lt;br&gt;""); 
else document.write(""Element not found!&lt;br&gt;""); 
&lt;/script&gt;                                    

//unit testing

Describe ('Search Binary Algorithm', function () {
    var search = new Searching();
  it('should search in binary', function(){
      console.log (search ());
       expect(search (x).toEqual(5));
   });

});
</code></pre>

<p>When I run this one syntax error unexpected identifier. </p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/62378682/javascript-unit-testing-in-jasmin-framework,"['javascript', 'unit-testing']",26,False,0,0
Mat Table - renderRows Unit Testing error,"<p>I'm using a mat table in a component and call renderRows after updating the table, which works perfectly.
However, in my unit tests, I'm getting the below error.</p>
<p><em>An error was thrown in afterAll
Failed: Cannot read property 'renderRows' of undefined
error properties: Object({ longStack: 'TypeError: Cannot read property 'renderRows' of undefined
at SafeSubscriber._next (http://localhost:9876/<em>karma_webpack</em>/src/app/product-management/tax-configuration/tax-configuration.component.ts:80:23)</em></p>
<p>spec.ts file -&gt;</p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TaxConfigurationComponent } from './tax-configuration.component';
import { MatTableModule } from '@angular/material/table';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NotificationService } from 'src/app/services/custom/notification.service';
import { TaxConfigurationService } from 'src/app/services/products/tax-configuration.service';
import { MockTaxConfigurationService } from 'src/app/services/products/tax-configuration.service.mock.spec';
import { throwError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';

describe('TaxConfigurationComponent', () =&gt; {
    let component: TaxConfigurationComponent;
    let fixture: ComponentFixture&lt;TaxConfigurationComponent&gt;;
    let _notificationService: NotificationService;
    let _taxService: TaxConfigurationService;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [TaxConfigurationComponent],
            imports: [
                BrowserAnimationsModule,
                MatTableModule,
                MatFormFieldModule,
                MatInputModule,
                FormsModule,
                ReactiveFormsModule,
                HttpClientTestingModule,
                MatButtonModule,
            ],
            providers: [{ provide: TaxConfigurationService, useClass: MockTaxConfigurationService }],
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(TaxConfigurationComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        _taxService = TestBed.inject(TaxConfigurationService);
        _notificationService = TestBed.inject(NotificationService);
    });

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

    it('should populate tax table on init', () =&gt; {
        expect(component.dataSource.length).toBeGreaterThan(0);
    });

    it('should show an error notification when &quot;getTaxConfig()&quot; errors out', () =&gt; {
        spyOn(_notificationService, 'startNotification').and.callThrough();
        spyOn(_taxService, 'getTaxConfig').and.returnValue(throwError('Error'));
        component.ngOnInit();
        expect(_notificationService.startNotification).toHaveBeenCalledWith(
            'An error occurred while fetching data.',
            'nc-notification--error',
            'priority_high'
        );
    });
});
</code></pre>
<p>component.ts file -&gt;</p>
<pre><code>ngOnInit(): void {
        this.state = true;
        this.taxForm = new FormGroup({});
        this.populateTaxConfigTable();
    }

    populateTaxConfigTable(): void {
        this._taxService.getTaxConfig().subscribe((results) =&gt; {
            results.forEach((result) =&gt; {
                const rowEntry = {
                    name: result.resourceName,
                    category: result.resourceCategory,
                    id: result.resourceId,
                    tsc: new FormControl(result.taxTsc, [
                        Validators.required,
                        Validators.pattern(regexPattern),
                        Validators.max(100),
                        Validators.min(0),
                    ]),
                    ot: new FormControl(result.taxOt, [
                        Validators.required,
                        Validators.pattern(regexPattern),
                        Validators.max(100),
                        Validators.min(0),
                    ]),
                    vat: new FormControl(result.taxVat, [
                        Validators.required,
                        Validators.pattern(regexPattern),
                        Validators.max(100),
                        Validators.min(0),
                    ]),
                };
                const tscControlName = rowEntry.id + 'tsc';
                const otControlName = rowEntry.id + 'ot';
                const vatControlName = rowEntry.id + 'vat';
                this.taxForm.addControl(tscControlName, rowEntry.tsc);
                this.taxForm.addControl(otControlName, rowEntry.ot);
                this.taxForm.addControl(vatControlName, rowEntry.vat);
                this.dataSource.push(rowEntry);
            });
            this.table.renderRows();
            this.state = false;
        }, (error) =&gt; {
            this._notificationService.startNotification('An error occurred while fetching data.',
            'nc-notification--error', 'priority_high');
        });
    }
</code></pre>
<p>When I comment the <code>this.table.renderRows</code>, unit tests are running without any issues. Any idea about the issue here?</p>
<p>Edit:</p>
<p>MockTaxCongfigurationService</p>
<pre><code>export class MockTaxConfigurationService {
    getTaxConfig(): Observable&lt;ResourceTaxes[]&gt; {
        return of([mockResourceTaxes, mockResourceTaxes]);
    }

    updateTaxConfig(data: TaxPostData[]): Observable&lt;TaxResponseData[]&gt; {
        return of([mockTaxResponseData]);
    }
}
</code></pre>
<p>Using viewChild -&gt;</p>
<pre><code>export class TaxConfigurationComponent implements OnInit {
    @ViewChild(MatTable) table: MatTable&lt;any&gt;;
    displayedColumns: string[] = ['name', 'tsc', 'ot', 'vat'];
    taxForm: FormGroup;
    dataSource: TaxTableData[] = [];
    state = false; // Loading state
    shouldDisableSave = false;

    constructor(
        private _notificationService: NotificationService,
        private _taxService: TaxConfigurationService) {}

    ngOnInit(): void {
        this.state = true;
        this.taxForm = new FormGroup({});
        this.populateTaxConfigTable();
    }

   ...
}
</code></pre>
",https://stackoverflow.com/questions/64202807/mat-table-renderrows-unit-testing-error,"['angular', 'unit-testing', 'karma-jasmine', 'mat-table']",2742,True,0,1
Unit testing using nose in python,"<p>I have been trying to solve this for a long now ,but somewhere i got wrong i think and i can't identify the error.</p>

<blockquote>
  <p>Problem :</p>
</blockquote>

<p>Define a class '<strong>Circle</strong>' with the following specifications:</p>

<ul>
<li>Define the class method '<strong>init</strong>', which initializes a circle with attribute 'radius', having the following restrictions:

<ul>
<li>'<strong>radius</strong>' must be a numeric value. If not, raise TypeError with error message ""radius must be a number"".</li>
<li>'<strong>radius</strong>' must be between 0 and 1000, inclusive on both sides. If not, raise ValueError with error message ""radius must be between 0 and 1000 inclusive"".</li>
</ul></li>
<li>Define the class method '<strong>area</strong>', which computes the area of the circle, and returns the value rounded off to 2 decimals. Hint: Make use of the 'pi' value from the 'math' module.</li>
<li>Define the class method '<strong>circumference</strong>', which computes the circumference of the circle, and returns the value rounded off to 2 decimals. Hint: Make use of the 'pi' value from the 'math' module.</li>
</ul>

<p>Define a nose test class '<strong>TestingCircleCreation</strong>' which tests the behavior of the '<strong>__init__</strong>' method with the following tests:</p>

<ul>
<li>Define a nose test method '<strong>test_creating_circle_with_numeric_radius</strong>', which creates a circle with radius 2.5, and check if its radius value is 2.5.</li>
<li>Define a nose test method '<strong>test_creating_circle_with_negative_radius</strong>', which checks if the ValueError exception is raised with the error message ""radius must be between 0 and 1000 inclusive"", while creating a circle of radius -2.5. Hint: Use assert_raises and with.</li>
<li>Define a nose test method '<strong>test_creating_circle_with_greaterthan_radius</strong>', which checks if the ValueError exception is raised with the error message ""radius must be between 0 and 1000 inclusive"" , while creating circle of radius 1000.1 . Hint: Use assert_raises and with</li>
<li>Define a nose test method '<strong>test_creating_circle_with_nonnumeric_radius</strong>', which checks if the TypeError exception is raised with the error message ""radius must be a number"", while creating circle of radius 'hello' . Hint: Use assert_raises and with.</li>
</ul>

<blockquote>
  <p>I have tried this but its showing error .</p>
</blockquote>

<pre class=""lang-py prettyprint-override""><code>class Circle:

def __init__(self, radius):
    # Define the initialization method below
    self.radius=radius
    if not isinstance(self.radius,(int,float)):
        raise TypeError(""radius must be a number"")
    elif(self.radius&gt;1000 or self.radius&lt;0):
        raise ValueError(""radius must be between 0 and 1000 inclusive"")
    else:
        pass
def area(self):
    # Define the area functionality below
    return math.pi*(self.radius**2)
def circumference(self):
    return 2*math.pi*self.radius
    # Define the circumference functionality below
</code></pre>

<pre class=""lang-py prettyprint-override""><code>class TestingCircleCreation:
def test_creating_circle_with_numeric_radius(self):
    c1=Circle(2.5)
    assert c1.radius==2.5

def test_creating_circle_with_negative_radius(self):
    c1=Circle(2.5)
    assert c1.radius==2.5
    with assert_raises(ValueError):
        Circle(-2.5)


def test_creating_circle_with_greaterthan_radius(self):
    c1=Circle(2.5)
    assert c1.radius==2.5
    with assert_raises(ValueError):
        Circle(1000.1)

def test_creating_circle_with_nonnumeric_radius(self):
    c1=Circle(2.5)
    assert c1.radius==2.5
    with assert_raises(TypeError):
        Circle('hello')
</code></pre>
",https://stackoverflow.com/questions/60728065/unit-testing-using-nose-in-python,"['unit-testing', 'nose']",1015,False,0,1
Xcode Unit Testing run function correctly,"<p>Let's say I have this test code</p>

<pre><code>class MyTests: XCTestCase {

    // I want to call this func first when I run class test.
    func testLoginUser() {
        ... do some test
        ... expectation.fulfiil() // jump to the next testGetUserProfile func.
    }

    // I want to run this func after testLoginUser fulfill expectation
    func testGetUserProfile() {

    }
}
</code></pre>

<p>Questions:</p>

<ol>
<li>As I understood that all functions which started from prefix test will be called automatically by pressing this button on the image below with undefined queue of calls. So <code>testGetUserProfile</code> func can be called before actually <code>testLoginUser</code> fulfilled am I right?</li>
<li>If so then does it mean that I need to rename <code>testGetUserProfile</code> to <code>getUserProfile</code> function and call it from <code>testLoginUser</code> after expectation fulfilled?
<a href=""https://i.stack.imgur.com/gplqL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gplqL.png"" alt=""enter image description here""></a></li>
</ol>

<p>Is there a way to program a queue of test func calls one by one after each of them fulfilled?</p>
",https://stackoverflow.com/questions/61352254/xcode-unit-testing-run-function-correctly,"['swift', 'xcode', 'unit-testing']",76,True,0,1
Android unit testing flow with multiple emit,"<p>I have my use case that talks to repository and emits multiple data as below -</p>

<pre><code>class MyUseCase(private val myRepoInterface: MyRepoInterface) : MyUseCaseInterface {

    override fun performAction(action: MyAction) = flow {
        emit(MyResult.Loading)
        emit(myRepoInterface.getData(action))
    }
}
</code></pre>

<p>The unit test for the same looks like this below -</p>

<pre><code>class MyUseCaseTest {

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    @Mock
    private lateinit var myRepoInterface: MyRepoInterface

    private lateinit var myUseCaseInterface: MyUseCaseInterface

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        myUseCaseInterface = MyUseCase(myRepoInterface)
    }

    @After
    fun tearDown() {
    }

    @Test
    fun test_myUseCase_returnDataSuccess() {
        runBlocking {
            `when`(myRepoInterface.getData(MyAction.GetData))
                .thenReturn(MyResult.Data(""data""))

            // Test
            val flow = myUseCaseInterface.performAction(MyAction.GetData)

            flow.collect { data -&gt;
                Assert.assertEquals(data, MyResult.Loading)
                Assert.assertEquals(data, MyResult.Data(""data""))
            }
        }
    }
}
</code></pre>

<p>After running the test I get this error -</p>

<pre><code>java.lang.AssertionError: 
Expected : MyResult$Loading@4f32a3ad
Actual   : MyResult.Data(""data"")
</code></pre>

<p>How do I test the use case that emits multiple things?</p>
",https://stackoverflow.com/questions/60946460/android-unit-testing-flow-with-multiple-emit,"['android', 'junit', 'android-livedata', 'kotlin-coroutines']",2744,True,6,1
Xamarin.Essentials.NotImplementedInReferenceAssemblyException thrown when Unit Testing Xamarin.Forms app,"<p>I am running Unit Tests for my Xamarin.Forms application, and the Unit Tests throw <code>Xamarin.Essentials.NotImplementedInReferenceAssemblyException</code>:</p>
<p><a href=""https://i.stack.imgur.com/0sSzA.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0sSzA.png"" alt=""enter image description here"" /></a></p>
<p>I have created a Unit Test project for the app (using NUnit 3.12.0) and have written the below code to test the functionality.</p>
<pre><code>[TestFixture()]
public class Test
{
    [Test()]
    public void TestCase()
    {
        AutoResetEvent autoEvent = new AutoResetEvent(true);

        SomeClass someClass = new SomeClass();
        someClass.SomeFunction((response) =&gt;
        {
            Assert.AreEqual(response, &quot;Hello&quot;)
            autoEvent.Set();
        });

        autoEvent.WaitOne(); //** Xamarin.Essentials.NotImplementedInReferenceAssemblyException thrown here**
    }
}
</code></pre>
<p>Below is the code under test from the Xamarin.Forms app:</p>
<pre><code>public class SomeClass
{
    
    public void SomeFunction(Action&lt;string&gt; callback)
    {
        // asynchronous code...
        callback(&quot;Hello&quot;);
    }
}
</code></pre>
<p>The above functionality works fine in the Xamarin.Forms app.</p>
<p><strong>Note</strong>: I read that await/async can be used, however, I will have to make changes in the entire project. This is not a feasible solution for now.</p>
<hr />
<p><strong>Edit 1:</strong>
I have created a sample Xamarin.Forms project with Unit Tests in it. The project is available <a href=""https://drive.google.com/drive/folders/1Lg2bQd_qN8xOYmgbglDY0WYv-RWEiREC?usp=sharing"" rel=""nofollow noreferrer"">here</a></p>
",https://stackoverflow.com/questions/64423004/xamarin-essentials-notimplementedinreferenceassemblyexception-thrown-when-unit-t,"['c#', 'unit-testing', 'xamarin.forms', 'nunit', 'xamarin.essentials']",1970,True,6,4
NestJs request and response interceptor unit testing,"<p>I would like to log the incoming requests and outgoing responses for my API. I created a request interceptor and a response interceptor as described here</p>

<p><a href=""https://docs.nestjs.com/interceptors"" rel=""noreferrer"">https://docs.nestjs.com/interceptors</a></p>

<p>So the request interceptor only logs the request object</p>

<pre><code>@Injectable()
export class RequestInterceptor implements NestInterceptor {
  private readonly logger: Logger = new Logger(RequestInterceptor.name, true);

  public intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const { originalUrl, method, params, query, body } = context.switchToHttp().getRequest();

    this.logger.debug({ originalUrl, method, params, query, body }, this.intercept.name);

    return next.handle();
  }
}
</code></pre>

<p>and the response interceptor waits for the outgoing response and logs the status code and response object later on</p>

<pre><code>@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  private readonly logger: Logger = new Logger(ResponseInterceptor.name, true);

  public intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const { statusCode } = context.switchToHttp().getResponse();

    return next.handle().pipe(
      tap((responseData: any) =&gt;
        this.logger.debug({ statusCode, responseData }, this.intercept.name),
      ),
    );
  }
}
</code></pre>

<p>I would like to test them but unfortunately have almost no experience in testing. I tried to start with the request interceptor and came up with this</p>

<pre><code>const executionContext: any = {
  switchToHttp: jest.fn().mockReturnThis(),
  getRequest: jest.fn().mockReturnThis(),
};

const nextCallHander: CallHandler&lt;any&gt; = {
  handle: jest.fn(),
};

describe('RequestInterceptor', () =&gt; {
  let interceptor: RequestInterceptor;

  beforeEach(() =&gt; {
    interceptor = new RequestInterceptor();
  });

  describe('intercept', () =&gt; {
    it('should fetch the request object', (done: any) =&gt; {
      const requestInterception: Observable&lt;any&gt; = interceptor.intercept(executionContext, nextCallHander);

      requestInterception.subscribe({
        next: value =&gt; {
          // ... ??? ...
        },
        error: error =&gt; {
          throw error;
        },
        complete: () =&gt; {
          done();
        },
      });
    });
  });
});
</code></pre>

<p>I currently don't know what to pass into the next callback but when I try to run the test as it is it says that the requestInterception variable is undefined. So the test fails before reaching the next callback. So the error message I get is</p>

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

<p>I also tried to test the response interceptor and came up with this</p>

<pre><code>const executionContext: any = {
  switchToHttp: jest.fn().mockReturnThis(),
  getResponse: jest.fn().mockReturnThis()
};

const nextCallHander: CallHandler&lt;any&gt; = {
  handle: jest.fn()
};

describe(""ResponseInterceptor"", () =&gt; {
  let interceptor: ResponseInterceptor;

  beforeEach(() =&gt; {
    interceptor = new ResponseInterceptor();
  });

  describe(""intercept"", () =&gt; {
    it(""should fetch the statuscode and response data"", (done: any) =&gt; {
      const responseInterception: Observable&lt;any&gt; = interceptor.intercept(
        executionContext,
        nextCallHander
      );

      responseInterception.subscribe({
        next: value =&gt; {
          // ...
        },
        error: error =&gt; {
          throw error;
        },
        complete: () =&gt; {
          done();
        }
      });
    });
  });
});
</code></pre>

<p>This time I get an error at the interceptor</p>

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

<p>Would some mind helping me to test those two interceptors properly?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/59624156/nestjs-request-and-response-interceptor-unit-testing,"['jestjs', 'nestjs']",6461,True,5,1
Unit Testing an ngx-formly Custom Template,"<p>I am working with <a href=""https://formly.dev/"" rel=""nofollow noreferrer"">Formly</a> and created a couple Custom Templates. The only code included in the component is a call to a general error handling service, so there is really almost nothing to test other than that the component can be created. I am using only Jest for unit testing, but cannot figure out what I need to include to have the component compile successfully.</p>
<p>The error I am getting is: TypeError: Cannot read property 'formControl' of undefined. I am not sure what I am missing in my test.</p>
<p>For the simplest component (mainly styling and a directive - removed for now), I have the following:</p>
<p>Component:</p>
<pre><code>@Component({
  selector: 'my-formly-field-input',
  templateUrl: './formly-field-input.component.html',
  styleUrls: ['./formly-field-input.component.scss']
})
export class FormlyFieldInputComponent extends FieldType {

  constructor(private formErrorService: FormErrorHandlerService) {
    super();
  }

  getError(formItem: FormControl | FormGroup | FormArray): string {
    return this.formErrorService.getFormError(formItem);
  }

}
</code></pre>
<p>View:</p>
<pre><code>&lt;mat-form-field [floatLabel]=&quot;'always'&quot; 
                class=&quot;w-100&quot; 
                [appearance]=&quot;'fill'&quot;&gt;
    &lt;mat-label&gt;{{field.templateOptions.label}}&lt;/mat-label&gt;
    &lt;input matInput 
           [formControl]=&quot;formControl&quot;
           [type]=&quot;field.templateOptions.type || 'text'&quot;
           [step]=&quot;field.templateOptions.step || 1&quot;
           [max]=&quot;field.templateOptions.max || undefined&quot;/&gt;
    &lt;mat-error *ngIf=&quot;formControl.errors&quot;&gt;
        {{getError(formControl)}}
    &lt;/mat-error&gt;
&lt;/mat-form-field&gt;
</code></pre>
<p>Unit Test:</p>
<pre><code> describe('FormlyFieldInputComponent', () =&gt; {
  let component: FormlyFieldInputComponent;
  let fixture: ComponentFixture&lt;FormlyFieldInputComponent&gt;;

  const formHelperServiceStub: Partial&lt;FormErrorHandlerService&gt; = {
    getFormError: (formItem) =&gt; 'Error Happened'
  };

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        FormlyFieldInputComponent
      ],
      imports: [
        MyHelpersModule,
        BrowserAnimationsModule,
        FormlyModule.forRoot(),
        FormlyMaterialModule,
        MatFormFieldModule,
        MatInputModule,
        ReactiveFormsModule,
      ],
      providers: [
        { provide: FormErrorHandlerService, useValue: formHelperServiceStub }
      ],
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p>Thanks in advance!!</p>
",https://stackoverflow.com/questions/64380872/unit-testing-an-ngx-formly-custom-template,"['angular', 'angular-material', 'jestjs', 'ngx-formly']",2532,True,4,1
Mocking express-rate-limit for unit testing,"<p>I have implemented 'express-rate-limit' into my application as a middleware for specific endpoints. When it comes to unit testing I am finding trouble when attempting to stub this middleware to appropriately control the responses.</p>
<p>For example, I have a route that allows 3 requests every 15 minutes, however, I have 10 unit tests for this route. The first 3 tests pass as expected and the following 7 return a <em>'429 Too Many Requests'</em> response.</p>
<p>The <em>'express-rate-limit'</em> library seems to be highly suggested for rate limiting, however, I cannot find any information regarding how it would be utilized in a testing environment.</p>
<p>The following shows the simplified implementation attempt.</p>
<p><strong>ratelimit.js</strong></p>
<pre><code>exports.createUser = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minute
    max: 3,
    message: 'Too many requests',
    statusCode: 429
})
</code></pre>
<p><strong>route.js</strong></p>
<pre><code>const rateLimits = require('./ratelimit')

let incorrect = function (res, msg) {
    res.status(401)
    res.send({
        status: 'err',
        payload: {
            msg: msg
        }
    })
}

router.post('/create', rateLimits.createUser, (req, res) =&gt; {
    if (!req.body.email) return incorrect(res, 'Email not provided')
    userController
        .createUser(req.body.email)
        .then(user =&gt; {
            if (!user) incorrect(res, 'User not created')
            else correct(res)
        })
        .catch(() =&gt; incorrect(res, 'Internal Error'))
})
</code></pre>
<p><strong>test.js</strong></p>
<p>This should stub the rate limit to only allow a single request to be made, meaning the second test should fail. However the second test will pass as this is never called (rate limit is still 3 as per the <em>'real'</em> implementation)</p>
<pre><code>const rateLimits = require('./ratelimit')
const userController = require('./usercontroller')
let server
let limiter

describe('Users', () =&gt; {
  before(() =&gt; {
    limiter = sinon.stub(rateLimits, 'createUser').callsFake(() =&gt; rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minute
      max: 1,
      message: 'Too many requests',
      statusCode: 429
  }))
    server = require('../app')
  })
  

  it('should return an error for invalid email', done =&gt; {
    chai.request(server)
    .post('/users/create')
    .send({
      email: 'notanemail'
    })
    .end((err, res) =&gt; {
      res.should.have.status(401)
      res.body.status.should.equal('err')
      done()
    })
  })

  it('should return an error for missing parameter', done =&gt; {
    chai.request(server)
    .post('/users/create')
    .send({})
    .end((err, res) =&gt; {
      res.should.have.status(401)
      res.body.status.should.equal('err')
      done()
    })
  })

})
</code></pre>
<p>This question <a href=""https://stackoverflow.com/questions/55434041/stubbing-out-middleware"">Stubbing Out Middleware</a> highlighted that the App itself should be initialized after the stubbing has been executed to ensure that is loaded correctly. This does not appear to work, nor does the standard .implementation where the import is created at the top of the file.</p>
<p>Alternatively, for testing purposes, I have attempted to log some text to the console on execution to ensure that the stub function is called. The function appears to never be called as the log is never printed to console.</p>
<pre><code>  limiter = sinon.stub(rateLimits, 'createUser').callsFake(() =&gt; console.log(&quot;I was executed&quot;))
</code></pre>
<p>Another failed alternative I have attempted is to call the <em>express-rate-limit</em> module directly with</p>
<pre><code>const rateLimit = require('express-rate-limit')

limiter = sinon.stub(rateLimit.prototype, 'constructor').callsFake(() =&gt; rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minute
      max: 1,
      message: 'Too many requests',
      statusCode: 429
  }))
</code></pre>
",https://stackoverflow.com/questions/63160152/mocking-express-rate-limit-for-unit-testing,"['javascript', 'node.js', 'unit-testing']",2440,True,4,2
Spark scala mocking spark.implicits for unit testing,"<p>When trying to simplify unit testing with Spark and Scala, I am using scala-test and mockito-scala (and mockito sugar). This simply lets you do something like this:</p>
<pre><code>val sparkSessionMock = mock[SparkSession]
</code></pre>
<p>Then you can usually do all the magic with &quot;when&quot; and &quot;verify&quot;.</p>
<p>But if you have some implementations that has the necessary import of</p>
<pre><code>import spark.implicits._
</code></pre>
<p>in its code, then the simplicity of unit testing seems to be gone (or at least I didn't find the most proper way to solve this, yet).</p>
<p>I end up in getting this error:</p>
<pre><code>org.mockito.exceptions.verification.SmartNullPointerException: 
You have a NullPointerException here:
-&gt; at ...
because this method call was *not* stubbed correctly:
-&gt; at scala.Option.orElse(Option.scala:289)
sparkSession.implicits();
</code></pre>
<p>Simply mocking the call on the &quot;implicits&quot; object inside SparkSession won't help due to typing issues:</p>
<pre><code>val implicitsMock = mock[SQLImplicits]
when(sparkSessionMock.implicits).thenReturn(implicitsMock)
</code></pre>
<p>will not let you pass, since it says it will require the type of the object inside your mock:</p>
<pre><code>require: sparkSessionMock.implicits.type
found: implicitsMock.type
</code></pre>
<p>And please don't tell me that I should rather do SparkSession.builder.getOrCreate()... since then this isn't a unit-test anymore but a more heavy weight integration test.</p>
<p>(Edit): here is a complete reproducible example:</p>
<pre><code>import org.apache.spark.sql._
import org.mockito.Mockito.when
import org.scalatest.{ FlatSpec, Matchers }
import org.scalatestplus.mockito.MockitoSugar

case class MyData(key: String, value: String)

class ClassToTest()(implicit spark: SparkSession) {
    import spark.implicits._

    def read(path: String): Dataset[MyData] = 
         spark.read.parquet(path).as[MyData]
}

class SparkMock extends FlatSpec with Matchers with MockitoSugar {

     it should &quot;be able to mock spark.implicits&quot; in {
         implicit val sparkMock: SparkSession = mock[SparkSession]
         val implicitsMock = mock[SQLImplicits]
         when(sparkMock.implicits).thenReturn(implicitsMock)
         val readerMock = mock[DataFrameReader]
         when(sparkMock.read).thenReturn(readerMock)
         val dataFrameMock = mock[DataFrame]
         when(readerMock.parquet(&quot;/some/path&quot;)).thenReturn(dataFrameMock)
         val dataSetMock = mock[Dataset[MyData]]
         implicit val testEncoder: Encoder[MyData] = Encoders.product[MyData]
         when(dataFrameMock.as[MyData]).thenReturn(dataSetMock)

         new ClassToTest().read(&quot;/some/path/&quot;) shouldBe dataSetMock
    }
 }
</code></pre>
",https://stackoverflow.com/questions/64539412/spark-scala-mocking-spark-implicits-for-unit-testing,"['scala', 'unit-testing', 'apache-spark', 'mockito', 'implicit']",2980,True,4,1
Vue.js - Unit testing component with complex children,"<p>Let's assume a basic <a href=""https://getbootstrap.com/"" rel=""nofollow noreferrer"">Bootstrap</a> driven HTML form as part of a custom Vue component <code>MyForm.vue</code></p>

<pre><code>&lt;template&gt;
  &lt;form&gt;
    &lt;div class=""form-group""&gt;
      &lt;label for=""email""&gt;Email address&lt;/label&gt;
      &lt;input type=""email"" class=""form-control"" id=""email""&gt;
    &lt;/div&gt;
    &lt;button type=""submit"" class=""btn btn-primary""&gt;Submit&lt;/button&gt;
  &lt;/form&gt;
&lt;/template&gt;
</code></pre>

<p>A unit test for testing if the template is rendered successfully is pretty simple</p>

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

  let wrapper;

  beforeEach(...);

  it('Should be rendered', () =&gt; {

    let field = wrapper.find('#email');
    expect(field.element.value).toEqual('');
  });
});
</code></pre>

<p>This line works <code>field.element.value</code> works because <code>field.element</code> is of native type <code>HtmlInputElement</code> with <code>value</code> attribute.</p>

<p>What if I want access an attribute of a complex component let's say of <a href=""https://bootstrap-vue.js.org/docs/components/form-input"" rel=""nofollow noreferrer"">b-form-input</a>, the Bootstrap-Vue's default input element? <code>b-form-input</code> is of type <code>BFormInput</code> how to deal with it? Just cast the <code>HtmlElement</code> to <code>BFormInput</code>?</p>

<pre><code>&lt;template&gt;
  &lt;b-form&gt;
    &lt;b-form-group label=""Email""&gt;
      &lt;b-form-input type=""email"" id=""email""&gt;&lt;/b-form-input&gt;
    &lt;/b-form-group&gt;
    &lt;b-button type=""submit"" variant=""primary""&gt;Submit&lt;/button&gt;
  &lt;/b-form&gt;
&lt;/template&gt;
</code></pre>

<p>How to test non-native components? Specially with type-safety means TypeScript. Any ideas?</p>

<p><strong>Edit 03/01/2020</strong></p>

<p>Following up to <a href=""https://stackoverflow.com/users/2316540/muka-gergely"">muka.gergely</a>'s answer I found <a href=""https://medium.com/js-dojo/when-to-unstub-a-component-in-a-vue-js-unit-test-608c7d1c646"" rel=""nofollow noreferrer"">this</a> article. <code>shallowMount</code> is stubbing all child components by default which prevents also event handling. Moreover <code>shallowMount</code> allows to manually <em>unstub</em> components, in my case to unstub <code>b-form</code> and <code>b-button</code> for submit event testing.</p>

<pre><code>const stubs = { // Originally intended to provide custom stubs, here used to unstub components
  BButton,
  BForm,
};

wrapper = shallowMount&lt;MyComponent&gt;(MyComponent, {stubs});
</code></pre>

<p>This effects that these components are rendered instead of stubbed. All remaining components like the <code>b-form-input</code> are still automatically stubbed.</p>
",https://stackoverflow.com/questions/60401840/vue-js-unit-testing-component-with-complex-children,"['javascript', 'typescript', 'unit-testing', 'vue.js', 'bootstrap-4']",1486,True,4,1
InjectMocks object is null in Unit testing,"<p>This is my first junit tests using Mockito. I'm facing the issue of NPE for the service that was used in @InjectMocks. I looked at the other solutions, but even after following them, it shows same. Here is my code.</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)

public class CustomerStatementServiceTests {

    @InjectMocks
    private BBServiceImpl bbService;

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

    }

/**
 *  This test is to verify SUCCESS response
 */

@Test
public void testSuccess() { 

    BBResponse response = bbService.processDetails(txs);
    assertEquals(""SUCCESSFUL"" ,response.getResult());
}
}
</code></pre>

<h2>BBServiceImpl</h2>

<pre><code>@Service
public class BBServiceImpl implements BBService {

final static Logger log = Logger.getLogger(BBServiceImpl.class);



public BBResponse process(List&lt;Customer&gt; customers) { 
  // My business logic goes here
}
}
</code></pre>

<h2>Pom.xml</h2>

<pre><code>        &lt;!-- https://mvnrepository.com/artifact/org.mockito/mockito-core --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.mockito&lt;/groupId&gt;
        &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
        &lt;version&gt;2.23.4&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;




    &lt;!-- https://mvnrepository.com/artifact/junit/junit --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;version&gt;4.12&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
</code></pre>

<p>My ""bbService"" object is null here </p>

<p>Am I missing anything here? </p>
",https://stackoverflow.com/questions/60478285/injectmocks-object-is-null-in-unit-testing,"['java', 'junit', 'mockito']",7931,True,3,2
How to freeze datetime.now for unit testing,"<p>I have a model that uses a function to return a default datetime:</p>
<pre><code>class Company(models.Model):
    q1_results_date = models.DateField(
        verbose_name='Q1 financial results',
        default=quarter_results_date(1),
        blank=False,
        null=False,
    )

def quarter_results_date(month):
    return datetime.datetime(
        datetime.datetime.now().year,
        month,
        calendar.monthrange(datetime.datetime.now().year, month)[1]
    )
</code></pre>
<p>I want to unit test this, which requires me to set datetime.now() to a known value. To do this I am using <a href=""https://github.com/spulec/freezegun"" rel=""nofollow noreferrer""><code>freezegun.freeze_time</code></a>:</p>
<pre><code>def test_quarter_results_date(self):
    with freeze_time(&quot;2012-01-14&quot;):
        print('check datetime.now()', datetime.now())
        c = Company.objects.create()
    ...
</code></pre>
<p>However, although the <code>print</code> statement shows <code>2012-01-14</code>, the datetime is not frozen as it still uses today's date when evaluating <code>c1.q1_results_date</code>.</p>
<p>How can I correct this?</p>
",https://stackoverflow.com/questions/62837395/how-to-freeze-datetime-now-for-unit-testing,"['python', 'django', 'python-unittest', 'django-testing']",760,True,3,1
Jest unit testing a function throwing error,"<p>I was trying to unit test a function in node which throws an error regardless of any condition. Here is my node function definition.</p>

<pre><code>public testFunction() {
    throw new Error('Test Error');
}
</code></pre>

<p>As you can see this function always throws an error whenever it has been called. I tried to execute unit testing to this function using jest <a href=""https://jestjs.io/docs/en/expect#tothrowerror"" rel=""nofollow noreferrer"">.toThrow(error?)</a> method. I was not able to unit test the function as expected.</p>

<p>The below mentioned are the test cases that I wrote and have attached the screenshot of the errors that I faced while executing the same.</p>

<p><strong>Test Case #1</strong></p>

<pre><code>it('Should throw test error', (done) =&gt; {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction()).toThrow();
});
</code></pre>

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

<p><strong>Test Case #2</strong></p>

<pre><code>it('Should throw test error', (done) =&gt; {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction).toThrow();
});
</code></pre>

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

<p><strong>Test Case #3</strong></p>

<p>From <a href=""http://eloquentcode.com/expect-a-function-to-throw-an-exception-in-jest"" rel=""nofollow noreferrer"">this</a> blog, it was mentioned that</p>

<blockquote>
  <p>If we want to expect a function to throw an exception for certain
  input parameters, the key point is that we must pass in a function
  definition and not call our function inside the expect.</p>
</blockquote>

<p>So I updated my test case as</p>

<pre><code>it('Should throw test error', (done) =&gt; {
    const testClass = TestClassService.getInstance();
    expect(() =&gt; testClass.testFunction()).toThrow();
});
</code></pre>

<p>But it was throwing error like</p>

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

<p>What is the issue with my implementation? What is the correct method to unit test a function which throws an error object back?</p>
",https://stackoverflow.com/questions/61285655/jest-unit-testing-a-function-throwing-error,"['javascript', 'node.js', 'unit-testing', 'jestjs']",7508,True,3,1
What type of unit testing is this?,"<p>Try as I might, I can't remember the name of this type of testing, and therefore am having a hard time finding the library I'm looking for.</p>
<pre><code>The test runner randomly changes variable values and if-block execution, and if your existing tests still pass, then a warning/failure is displayed.
</code></pre>
<p>Note that I'm not talking about monkey testing. This library doesn't use random inputs for your code, but rather <strong>changes your code</strong> to ensure that your tests go red when your code is broken. If on the other hand all tests pass, it can signal that your tests are inadequate.</p>
",https://stackoverflow.com/questions/63928108/what-type-of-unit-testing-is-this,"['javascript', 'typescript', 'unit-testing', 'web-frontend']",52,True,3,1
Unit Testing Abstract Base and Child Classes,"<p>Unit testing newbie here. I have an abstract base class with one concrete, public method and one abstract, private method. Several child classes implement this private method:</p>

<pre><code>@add_metaclass(ABCMeta)
class Base(object):

    def concrete(self, x, y):
        x = self._abstract(x)
        return x, y

    @abstractmethod
    def _abstract(self, x):
        pass


class Child(Base):

    def _abstract(self, x):
        return x + 1
</code></pre>

<p>What is the best way to unit test the methods in these classes? In my initial attempt I created a <code>MockBase</code> and a set of tests in <code>BaseTests</code> common to all children of the original base class (<code>BaseTests</code> skips tests to avoid redundancy on execution). Child tests inherit from <code>BaseTests</code>. </p>

<pre><code>class MockBase(Base):

    def _abstract(self, x):
        return x


class BaseTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        if cls is BaseTests:
            raise unittest.SkipTest(""Skipping BaseTests."")
        super(BaseTests, cls).setUpClass()

    def setUp(self):
        super(BaseTests, self).setUp()
        self.class_ = MockBase()

    def test_concrete_returns_y(self):
        _, y = self.class_.concrete(1, 1)
        self.assertEqual(y, 1)


class TestChild(BaseTests):

    def setUp(self):
        super(TestChild, self).setUp()
        self.class_ = Child()

    def test_concrete_returns_x_plus_1(self):
        x, _ = self.class_.concrete(1, 1)
        self.assertEqual(x, 2)
</code></pre>

<p>This approach seems to work, but I'm wondering if it's the most elegant and scalable option. </p>
",https://stackoverflow.com/questions/59595330/unit-testing-abstract-base-and-child-classes,"['python', 'unit-testing', 'inheritance']",361,False,2,0
Django - Unit testing a form containing recaptcha,"<p>I am trying to write a unit test for a form containing recaptcha:</p>
<p>My contact view looks like this:</p>
<pre class=""lang-py prettyprint-override""><code>@check_recaptcha
def contact(request):
    if request.method == 'POST':
        f = ContactForm(request.POST)
        if f.is_valid() and request.recaptcha_is_valid:

            f.save(request)
            messages.add_message(request, messages.INFO, &quot;Thanks for submitting feedback!&quot;)


            return redirect('contact')
    else:
        f = ContactForm()

    return render(request, 'cms/contact.html', {'form': f})
</code></pre>
<p>The decorator <code>check_recaptcha()</code> is defined like this:</p>
<pre class=""lang-py prettyprint-override""><code>def check_recaptcha(view_func):
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        request.recaptcha_is_valid = None

        if settings.DEBUG:
            request.recaptcha_is_valid = True
            return view_func(request, *args, **kwargs)

        if request.method == 'POST':
            recaptcha_response = request.POST.get('g-recaptcha-response')
            data = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': recaptcha_response
            }
            r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
            result = r.json()
            if result['success']:
                request.recaptcha_is_valid = True
            else:
                request.recaptcha_is_valid = False
                messages.error(request, 'Invalid reCAPTCHA. Please try again.')

        return view_func(request, *args, **kwargs)
    return _wrapped_view
</code></pre>
<p>And the code to test the contact form looks like this:</p>
<pre class=""lang-py prettyprint-override""><code>class TestContactForm(TestCase):

    def test_can_send_feedback(self):
        data = {
            &quot;name&quot;: &quot;tom&quot;,
            &quot;email&quot;: &quot;tom@test.com&quot;,
            &quot;subject&quot;: &quot;A test subject&quot;,
            &quot;message&quot;: &quot;Hello jerry&quot;,
        }

        response = self.client.post(reverse('contact'), data=data)
        self.assertEqual(Feedback.objects.count(), 1)
        self.assertEquals(response.status_code, 302)
        self.assertRedirects(response, reverse('contact'))

</code></pre>
<p>The test run perfectly fine if I remove <code>request.recaptcha_is_valid</code> condition in the <code>contact</code> view. Is there a way to get rid of captcha during testing?</p>
",https://stackoverflow.com/questions/63054829/django-unit-testing-a-form-containing-recaptcha,"['python', 'django', 'unit-testing', 'recaptcha', 'captcha']",1060,False,2,2
Unit Testing for Javascripts in Dynamics 365,"<p>I am looking for some references related to javascript unit testing for D365. Since the new object model ExecutionContext.getFormContext has replaced the old Xrm.Page model, I am unable to find some info on this new object model which has been used for writing unit test case. Has anyone tried or post something related to this.</p>
",https://stackoverflow.com/questions/61633987/unit-testing-for-javascripts-in-dynamics-365,"['javascript', 'dynamics-crm-365']",113,False,2,0
Unit testing for useSubscription hook - React - Apollo,"<p>I am trying to write a Jest unit test for React component 'Dashboard'.</p>

<p>The 'Dashboard' integrates a <strong>'useSubscription'</strong> hook that return some data from the server.</p>

<p><strong>Dashboard.js component:</strong></p>

<pre class=""lang-js prettyprint-override""><code>// imports ...

const Dashboard = mainData =&gt; {
  // States declations ...

  const {
    loading: meLoading,
    error: meErrorMe,
    data: meData
  } = useQuery(GET_MYSELF);

  const { data: newNotificationData } = useSubscription(
    NOTIFICATION_SUBSCRIPTION,
    {
      variables: { userId: me &amp;&amp; me.id }
    }
  );

  // ...

  // return some JSX ...
};
</code></pre>

<p><strong>Unit test:</strong></p>

<pre class=""lang-js prettyprint-override""><code>import TestRenderer, { act } from ""react-test-renderer"";
import { MockedProvider } from ""@apollo/react-testing"";
import React from ""react"";
import wait from ""waait"";

import Dashboard, { NOTIFICATION_SUBSCRIPTION } from ""../dashboard"";
import { GET_MYSELF } from ""../../gqls/queries"";

const mocks = [
  {
    request: {
      query: GET_MYSELF
    },
    result: {
      data: {
        me: {
          id: ""5e42d97c86530405f4028ab4"",
          name: ""Montacer Dkhilali"",
          email: ""montacer.dkhilali@gmail.com"",
          roles: [""ADMIN""],
          __typename: ""User""
        }
      }
    }
  },
  {
    request: {
      query: NOTIFICATION_SUBSCRIPTION,
      variables: {
        userId: ""5e42d97cx5x30405f405azs5""
      }
    },
    result: {
      data: {
        newNotificationData: {
          id: ""5e42d97cx5x30405f405azs5"",
          read: false,
          title: ""Notification 1"",
          __typename: ""Notification""
        }
      }
    }
  }
];

describe(""Dashboard page"", () =&gt; {
  it(""should render without error"", async () =&gt; {
    await act(async () =&gt; {
      TestRenderer.create(
        &lt;MockedProvider mocks={mocks}&gt;
          &lt;Dashboard /&gt;
        &lt;/MockedProvider&gt;
      );
    });
  });
</code></pre>

<p>I got some errors after launching the unit test :</p>

<pre><code>Dashboard page
    ✕ should render without error (47ms)

  ● Dashboard page › should render without error

    No more mocked responses for the query: subscription onNotificationsAdded($userId: ID!) {      notificationsAdded(userId: $userId) {
        id
        read
        title
        __typename
      }
    }
    , variables: {}

      90 |   } = mainData;
      91 | 
    &gt; 92 |   const { data: newNotificationData } = useSubscription(
         |                                         ^
      93 |     NOTIFICATION_SUBSCRIPTION,
      94 |     {
      95 |       variables: { userId: me &amp;&amp; me.id }

      at MockLink.request (node_modules/@apollo/react-testing/lib/react-testing.cjs.js:85:13)
      ...
      at act (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:17271:14)
      at Object.&lt;anonymous&gt; (src/pages/__tests__/dashboard.js:63:11)

console.warn node_modules/ts-invariant/lib/invariant.js:33
    Found @client directives in a query but no ApolloClient resolvers were specified. This means ApolloClient local resolver handling has been disabled, and @client directives will be passed through to your li
nk chain.

  console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11958
    The above error occurred in the &lt;Dashboard&gt; component:
        in Dashboard (created by Query)
        in Query (created by Apollo(Dashboard))
        in Apollo(Dashboard) (created by Query)
        in Query (created by Apollo(Apollo(Dashboard)))
        in Apollo(Apollo(Dashboard)) (at dashboard.js:66)
        in ApolloProvider (created by MockedProvider)
        in MockedProvider (at dashboard.js:65)

    Consider adding an error boundary to your tree to customize error handling behavior.
    Visit [url](fb.me/react-error-boundaries) to learn more about error boundaries.

</code></pre>

<p>In order the fix this, should I change the way that I am mocking the data ?</p>
",https://stackoverflow.com/questions/60264918/unit-testing-for-usesubscription-hook-react-apollo,"['reactjs', 'unit-testing', 'graphql', 'apollo', 'react-apollo']",630,False,2,0
Unit testing of react component having useEffect,"<p>I am trying to test useEffect and function calls inside useEffect in below code.
It has useEffect and useState hooks.</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 App = () =&gt; {
  const [search, setSearch] = useState("""");
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const getImageData = async () =&gt; {
    console.log(getImages());
    const { data, error } = await getImages();
    handleData(data, error);
  };

  const searchImageData = async (search) =&gt; {
    const { data, error } = await searchImages(search);
    handleData(data, error);
  };

  const handleData = (data, error) =&gt; {
    setLoading(true);
    if (data) {
      setImages(data);
    } else if (error) {
      setError(error);
    }
    setLoading(false);
  };

  // get images using hooks
  useEffect(async () =&gt; {
    if (search.length &gt; 0) {
      searchImageData(search);
    } else {
      getImageData();
    }
  }, [search]);

  return (
    &lt;center&gt;
      &lt;h1&gt;Photo Search App&lt;/h1&gt;
      &lt;SearchBox search={search} setSearch={setSearch} /&gt;
      &lt;div className=""photo-container""&gt;
        {loading ? (
          &lt;p&gt;Loading&lt;/p&gt;
        ) : error ? (
          &lt;p&gt;Error loading data&lt;/p&gt;
        ) : images.length &gt; 0 ? (
          &lt;Gallery images={images} /&gt;
        ) : (
          &lt;p&gt;No photos found&lt;/p&gt;
        )}
      &lt;/div&gt;
    &lt;/center&gt;
  );
};</code></pre>
</div>
</div>
</p>
<p>I am not sure how to mock the things related to hooks.
Any suggestion of testing the hook and async function calls?</p>
",https://stackoverflow.com/questions/65447737/unit-testing-of-react-component-having-useeffect,"['reactjs', 'jestjs', 'react-hooks', 'enzyme', 'react-16']",419,False,2,0
Mock unit testing with Kafka - callback mockproducer,"<p>I would like to setup some tests around calling Kafka. I have the following callback setup with my Kafka call, see below: </p>

<pre><code>@Async // allows function to be async. the config also has to be set
@Override
public void publishEventToTopic() {
        ListenableFuture&lt;SendResult&lt;String, KafkaRequest&gt;&gt; future = kafkaTemplate.send(topic, request);

        future.addCallback(new ListenableFutureCallback&lt;SendResult&lt;String, KafkaRequest&gt;&gt;() {
            @Override
            public void onSuccess(SendResult&lt;String, KafkaRequest&gt; result) {
                log.info(""Success"");
            }

            @Override
            public void onFailure(Throwable ex) {
                log.info(""Failure"");
            }
        });
}
</code></pre>

<p>What I would like to do is test both scenarios (onSuccess &amp; onFailure). I tried following this <a href=""https://stackoverflow.com/questions/56248612/how-to-write-unit-test-case-for-adding-callback-for-listenablefuture"">SO question</a> but I'm running into an error where it says that ""the topic can not be null"". Here's what I tried: </p>

<pre><code>@Test
public void test2() {
    String key = ""test1"";
    String topic = ""sender.t"";
    long offset = 1;
    int partition = 0;

    SendResult&lt;String, Object&gt; sendResult = mock(SendResult.class);
    ListenableFuture&lt;SendResult&lt;String, KafkaRequest&gt;&gt; responseFuture = mock(ListenableFuture.class);
    RecordMetadata recordMetadata = new RecordMetadata(new TopicPartition(topic, partition), offset, 0L, 0L, 0L, 0, 0);
    ProducerRecord producerRecord = new ProducerRecord(topic, partition, key, """");

    given(sendResult.getRecordMetadata()).willReturn(recordMetadata);
    given(sendResult.getProducerRecord()).willReturn(producerRecord);

    when(template.send(any(), any())).thenReturn(responseFuture);

    doAnswer(invocationOnMock -&gt; {
        ListenableFutureCallback listenableFutureCallback = invocationOnMock.getArgument(0);
        listenableFutureCallback.onFailure(throwable);
        return null;
    })
    .when(responseFuture).addCallback(any()); //this is the line that is throwing an error when trying to debug.


    publisher.publishEventToTopic();
}
</code></pre>

<p>I wasn't too sure what that meant so after a few hours, I decided to try a different path - using the <a href=""https://kafka.apache.org/20/javadoc/org/apache/kafka/clients/producer/MockProducer.html"" rel=""nofollow noreferrer"">MockProducer</a> class. It seemed to work but not consistently: </p>

<pre><code>@Test
public void test3() throws InterruptedException {
    ListenableFuture&lt;SendResult&lt;String, KafkaRequest&gt;&gt; responseErrorFuture = mock(ListenableFuture.class);
    MockProducer mockProducer = new MockProducer(Cluster.empty(), false, null, null, null);
    mockProducer.clear();
    mockProducer.errorNext(new RuntimeException(""Offset commit failed on partition my-topic-2-9 at offset 0"")); //this doesn't work anymore.

    publisher.publishEventToTopic();
}
</code></pre>

<p>So then I tried adding this to it but it complains that I'm not mocking the correct thing: </p>

<pre><code>        doAnswer(invocation -&gt; {
        ListenableFutureCallback listenableFutureCallback = invocation.getArgument(0);
        mockProducer.errorNext(new RuntimeException(""Offset commit failed on partition my-topic-2-9 at offset 0""));
        return null;
    }).when(mockProducer).send(any(), any());
</code></pre>

<p>My question is, does anyone have an idea on what I'm doing wrong to unt test the onFailure method of the callback when I send a Kafka request? </p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/60939136/mock-unit-testing-with-kafka-callback-mockproducer,"['apache-kafka', 'callback', 'future', 'spring-kafka', 'spring-kafka-test']",3129,False,2,0
Unit testing swift timer function using nimble,"<p>I am using Quick, Nimble, and RxSwift. </p>

<p>My goal is to write unit test that test some function with Timer on it which will be executed repeatedly after some time interval.</p>

<p>My pseudo class</p>

<pre><code>final class TestingTimerClass {
    let counter: BehaviorRelay&lt;Int&gt; = BehaviorRelay&lt;Int&gt;(value: 0)
    private var timer: Timer?

    ....

    func startTimer() {

        timer = Timer.scheduledTimer(
            timeInterval: 8,
            target: self as Any,
            selector: #selector(self.executeFunction),
            userInfo: nil,
            repeats: true
        )
    }

    @objc private func executeFunction() {
        let currentValue = counter.value
        counter.accept(currentValue + 1)
    }
}
</code></pre>

<p>My testing class</p>

<pre><code>class TestingTimerClass: QuickSpec {

    override func spec() {
        var testingClass: TestingTimerClass!

        describe(""executing"") {

            context(""startTimer()"") {

                beforeEach {
                    testingClass = TestingTimerClass()
                }

                afterEach {
                    testingClass = nil
                }

                it(""should update counter value after a period of time"") {

                    testingClass.startTimer()
                    expect(testingClass.counter.value).toEventually(equal(1), timeout: TimeInterval(9), pollInterval: TimeInterval(2), description: nil)
                }
            }
        }
    }
}
</code></pre>

<p>I expect that <code>executeFunction()</code> will be called after 8 second, however it is never called and my test suite is failed.</p>

<p>Any idea what went wrong?</p>
",https://stackoverflow.com/questions/61789977/unit-testing-swift-timer-function-using-nimble,"['ios', 'swift', 'rx-swift', 'quick-nimble']",891,True,2,1
Unit testing classes that instantiate other classes,"<p>I'm trying to write unit tests for a class that instantiates other classes within it, but am struggling with how to instantiate those classes in a testable way. I'm aware of dependency injection, but this is somewhat different as the instantiation doesn't happen in the constructor.</p>

<p>This question really isn't specific to MVVM and C#, but that's what my example will use. Note that I've simplified this and it will not compile as-is - the goal is to show a pattern.</p>

<pre><code>class ItemListViewModel
{
  ItemListViewModel(IService service)
  {
    this.service.ItemAdded += this.OnItemAdded;
  }

  List&lt;IItemViewModel&gt; Items { get; }

  OnItemAdded(IItemModel addedItem)
  {
    var viewModel = new ItemViewModel(addedItem);
    this.Items.Add(viewModel);
  }
}

class ItemViewModel : IItemViewModel
{
  ItemViewModel(IItem) {}
}
</code></pre>

<p>As can be seen above, there is an event from the model layer. The ViewModel listens to that event and, in response, adds a new child ViewModel. This fits with standard Object Oriented programming practices that I'm aware of, as well as the MVVM pattern, and feels like quite a clean implementation to me.</p>

<p>The problem comes when I want to unit test this ViewModel. While I can easily mock out the service using dependency injection, I'm unable to mock out items added through the event. This leads to my primary question: <strong>is it OK to write my unit tests depending on the real version of ItemViewModel, rather than a mock?</strong></p>

<p>My gut feel: that isn't OK because I'm now inherently testing more than ItemListViewModel, particularly if ItemListViewModel calls any methods on any of the items internally. I should have ItemListViewModel depend on mock IItemViewModels during testing.</p>

<p>There's a few tactics I've considered for how to do this:</p>

<ol>
<li><em>Have ItemListViewModel's owning class listen to the event and add mocked out items.</em> This just moves the problem around, though, as now the owning class can't be fully mocked out.</li>
<li><em>Pass an ItemViewModel factory into ItemListViewModel and use that instead of new.</em> This would definitely work for mocking as it moves things to be based on dependency injection...but does that mean I need a factory for every class I ever want to mock in my app? This feels wrong, and would be a pain to maintain.</li>
<li><em>Refactor my model and how it communicates with the ViewModel.</em> Perhaps the eventing pattern I'm using isn't good for testing; though I don't see how I would get around needing to ultimately construct an ItemViewModel somewhere in code that needs to be tested.</li>
</ol>

<p>Additionally, I've searched online and looked through the book Clean Code, but this really hasn't been covered. Everything talks about dependency injection, which doesn't clearly solve this.</p>
",https://stackoverflow.com/questions/60330954/unit-testing-classes-that-instantiate-other-classes,"['c#', 'unit-testing', 'testing', 'mvvm', 'tdd']",1381,True,2,2
Angular UNIT Testing method with .subscribe misunderstanding,"<p>I start to learn Angular testing recently and faced with a misunderstanding of the UNIT testing concept. 
For example, 
I have a dialog with with 2 buttons: Confirm delete and Cancel. When user click Confirm Delete button the http-service method is called and dialog closes. Sounds simple. Here is the code:</p>

<pre><code>confirmDelete() {
   this.httpService.delete(item)
       .subscribe(() =&gt; this.dialogRef.close(),
                  (err) =&gt; this.message = 'Some text');
} 
</code></pre>

<p>And my test for this function is:</p>

<pre><code>it('should call service delete method and close the dialog', async( () =&gt; {
   spyOn(dialogRef, 'close'); // I have mockDialogRef;
   component.confirmDelete();
   fixture.whenStable().then(() =&gt; {
      fixture.detectChanges();
      expect(deleteSpy.calls.any().toBe(true)); // Spy on delete method
      expect(dialogRef.close).toHaveBeenCalled();
   });
}));
</code></pre>

<p>And it worked fine. Seems to be the delete method has been called and dialog has been closed. But my question is. What we should test in such methods? Should we always test the stuff inside subscribe method or only that service methods is called? And should I Test here the case if server return error? 
So, ..sorry for stupid question, but I'm really confused. Hope you guys will help me(   </p>
",https://stackoverflow.com/questions/61439518/angular-unit-testing-method-with-subscribe-misunderstanding,"['angular', 'unit-testing']",187,False,1,0
Mocha Chai unit testing run specific folder,"<p>I have a application where it contains the test folder in main directory to maintain the <code>*test.js</code> files inside test folder. This test folder contains multiple sub folder representing each functionality and these sub folder conatains many <code>*test.js</code> files. How to run the specific testcase from selected folder in Mocha unit testing.</p>
",https://stackoverflow.com/questions/63153627/mocha-chai-unit-testing-run-specific-folder,"['node.js', 'mocha.js', 'chai']",454,False,1,1
"Jasmine: Jodit is not defined, Unit testing","<p>I'm trying to test our customized Jodit editor in app but even automatic 'should create' test is failed. Failure message is 'Jodit is not defined'. </p>

<p><em>jodit.component.ts</em></p>

<pre><code>import { Component, OnInit, AfterViewInit, OnDestroy, Input, Output, } from '@angular/core';

declare var Jodit: any;

@Component({
  selector: 'app-jodit',
  templateUrl: './jodit.component.html',
  styleUrls: ['./jodit.component.css']
})

export class JoditComponent implements AfterViewInit, OnDestroy {

  @Input() ... ;
  @Output() ... ;

  ngAfterViewInit() {
    this.editor = new Jodit('#' + this.elementId, ...
      });
</code></pre>

<p><em>jodit.component.spec.ts</em></p>

<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { JoditComponent } from './jodit.component';

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

  let fixture: ComponentFixture&lt;JoditComponent&gt;;
  let component: JoditComponent;


  beforeEach(() =&gt; {

    TestBed.configureTestingModule({
      declarations: [ JoditComponent ]
    })

    fixture = TestBed.createComponent(JoditComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  }); 
});
</code></pre>

<p>I'm really new in Angular and testing at all but i'm wondering may be i've declared Jodit variable false or someting from imports is missed. I'd really appreciate it if someone could help me out with this.</p>
",https://stackoverflow.com/questions/61206886/jasmine-jodit-is-not-defined-unit-testing,"['angular', 'typescript', 'unit-testing', 'jasmine', 'jodit']",699,True,1,1
Laravel unit testing assert functions always failing,"<p>I have created a very basic unit testing class under Laravel root-->tests-->Unit-->SimpleTest.php</p>

<p>Inside the file i have import the controller class that i need to test. And test function is like this.</p>

<pre><code>class SimpleTest extends TestCase
{
   public function testLoadUsers()
   {
     $controller_obj = new UsersController;
     $data_status = $controller_obj-&gt;load_users();
        if($data_status != null){
           $this-&gt;assertTrue(true);
         }
        else{
           $this-&gt;assertTrue(false);
         }
    }

  }
</code></pre>

<p>I executed this test case in Artisan console like this,</p>

<pre><code>php vendor/phpunit/phpunit/phpunit tests/Unit/SimpleTest.php
</code></pre>

<p>Always this fails. My controller function returning data as well without an issue. I tested without defining any condition and just,</p>

<pre><code>$this-&gt;assertTrue(true);
</code></pre>

<p>Then it works. So i assume there is no any issue with the phpunit test command as well.</p>
",https://stackoverflow.com/questions/60312026/laravel-unit-testing-assert-functions-always-failing,"['laravel', 'unit-testing', 'phpunit', 'laravel-unit-test']",598,False,1,1
Expectations Error while unit testing Got Client,"<p>I need your help with this issue that I am having while unit testing a Got client hook
where I do logging of HTTP requests. I am using Jest.
I am getting an expectations error that is seeing the argument to .toBeCalledWith as object whereas it is a string when I console log it. Maybe I am doing something wrong here. Please let me know.</p>
<blockquote>
<p>got-client.js below</p>
</blockquote>
<pre><code>const http = require('http');
const https = require('https');
const got = require('got');
const _ = require('lodash');

const { name: packageName, version: packageVersion } = require('../../package.json');

const keepAliveOptions = { keepAlive: true, keepAliveMsecs: 20000 };
let clients = {};


const allowedHeaders = ['user-agent', 'x-forwarded-for', 'referer', 'content-length'];
const filterHeaders = headers =&gt; _.pick(headers, allowedHeaders);

const gotLoggingHooks = (name, logger) =&gt; ({
  hooks: {
    beforeRequest: [
      options =&gt; {
        const { url, method, headers } = options;
        logger.debug({
          message: `${name} request ${options.method} ${options.url}`,
          http_request: {
            method,
            target: url,
            direction: 'OUT',
            headers: filterHeaders(headers)
          },
          request: _.pick(options, ['url', 'method', 'headers', 'body', 'json'])
        });
      }
    ],
    beforeRetry: [
      (options, error, retryCount) =&gt; {
        const {
          response: { statusCode, ip } = {},
          request: { options: { method, headers = {} } = {}, requestUrl: url } = {},
          timings: {
            // eslint-disable-next-line camelcase
            phases: { total: duration_ms } = {}
          } = {}
        } = error;
        logger.warn({
          message: `${name} will retry request, attempt ${retryCount}/${options.retry.limit} ${method} ${url} (${error.code} ${error.message})`,
          err: error,
          http_request: {
            method,
            target: url,
            status: statusCode,
            server_ip: ip,
            duration_ms,
            direction: 'OUT',
            protocol: headers.via,
            headers: filterHeaders(headers)
          }
        });
      }
    ],
    beforeError: [
      error =&gt; {
        const {
          response: { statusCode, ip } = {},
          request: { options: { method, headers } = {}, requestUrl: url } = {},
          timings: {
            // eslint-disable-next-line camelcase
            phases: { total: duration_ms } = {}
          } = {}
        } = error;
        if (!statusCode) {
          logger.error({
            message: `${name} request error ${method} ${url} (${error.code} ${error.message})`,
            err: error,
            http_request: {
              method,
              target: url,
              status: statusCode,
              server_ip: ip,
              duration_ms,
              direction: 'OUT',
              protocol: headers.via,
              headers: filterHeaders(headers)
            }
          });
        }
        // eslint-disable-next-line no-param-reassign
        error.serviceName = name;
        return error;
      }
    ],
    afterResponse: [
      response =&gt; {
        const {
          statusCode,
          body,
          url,
          ip,
          headers = {},
          request: { options: { method } = {} } = {},
          timings: {
            // eslint-disable-next-line camelcase
            phases: { total: duration_ms } = {}
          } = {},
          retryCount
        } = response;
        logger.debug({
          message: `${name} response ${method} ${url}`,
          response: { body, retryCount, headers },
          http_request: {
            method,
            target: url,
            status: statusCode,
            server_ip: ip,
            duration_ms,
            direction: 'OUT',
            protocol: headers.via,
            headers: filterHeaders(_.get(response, 'request.options.headers'))
          }
        });
        return response;
      }
    ]
  }
});

const gotClient = ({ name, logger, keepAlive = true, gotOptions = {} }) =&gt; {
  if (!clients[name]) {
    clients[name] = got
      .extend({
        headers: {
          'user-agent': `${packageName} ${packageVersion}`
        },
        ...(keepAlive &amp;&amp; {
          agent: {
            http: new http.Agent(keepAliveOptions),
            https: new https.Agent(keepAliveOptions)
          }
        }),
        responseType: 'json',
        timeout: 5000
      })
      .extend(gotLoggingHooks(name, logger))
      .extend(gotOptions);
  }

  return clients[name];
};

gotClient.clearAll = () =&gt; {
  clients = {};
};

module.exports = gotClient;

</code></pre>
<blockquote>
<p>got-client.spec.js below</p>
</blockquote>
<pre><code>const nock = require('nock');
const { name: packageName, version: packageVersion } = require('../../../package.json');
const gotClient = require('../../../src/lib/got-client');

const BASE_URL = 'https://subdomain.domain.com/';
const BASE_ENDPOINT = 'path';

const logger = {
  error: jest.fn(),
  debug: jest.fn(),
  info: jest.fn(),
  log: jest.fn(),
  warn: jest.fn(),
};
describe('got client', () =&gt; {

  afterEach(gotClient.clearAll);

  test('should log requests', async () =&gt; {
    const client = gotClient({
      name: 'test',
      logger,
      gotOptions: {
        prefixUrl: BASE_URL,
      },
    });

    nock(BASE_URL).get(`/${BASE_ENDPOINT}`).reply(200, { success: true });
    await client.get(BASE_ENDPOINT);
    // console.log('mock call 0', logger.debug.mock.calls[0][0]);
    // TODO: match message
    expect(logger.debug).toBeCalled();

    expect(logger.debug).toBeCalledWith(
      expect.objectContaining({
        message: expect.stringContaining(`request GET ${BASE_URL}${BASE_ENDPOINT}`),
      })
    );

    expect(logger.debug).toBeCalledWith(
      expect.objectContaining({
        message: expect.stringContaining(`response GET ${BASE_URL}${BASE_ENDPOINT}`),
      })
    );

    nock(BASE_URL).get(`/${BASE_ENDPOINT}/error`).reply(500, { success: false });
    try {
      await client.get(`${BASE_ENDPOINT}/error`, { retry: 0 });
    } catch (e) {}
    expect(logger.error).toBeCalledWith(
      expect.objectContaining({
        message: expect.stringContaining(`request error GET ${BASE_URL}${BASE_ENDPOINT}/error`),
      })
    );
  });
});

</code></pre>
<blockquote>
<p>Failing Test Error below</p>
</blockquote>
<pre><code>Error: expect(jest.fn()).toBeCalledWith(...expected)

Expected: ObjectContaining {&quot;message&quot;: StringContaining &quot;request error GET https://subdomain.domain.com/path/error&quot;}

Number of calls: 0

    at Object.&lt;anonymous&gt; (/Users/user/Documents/company/teams/team/project/test/unit/lib/got-clients.spec.js:62:26)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

</code></pre>
<p>I will really appreciate help with this. Thank you very much in advance.</p>
",https://stackoverflow.com/questions/64242643/expectations-error-while-unit-testing-got-client,"['javascript', 'unit-testing', 'jestjs', 'nock']",567,True,1,1
How to mock NSUbiquitousKeyValueStore for unit testing?,"<p>So I have a class I'm trying to unit test that uses both UserDefaults and NSUbiquitousKeyValueStore.  I can easily mock UserDefaults using UserDefaults(suiteName: #file) (for example), but I can't figure out how to mock NSUbiquitousKeyValueStore. I can't seem to find any thread about it here on SO, and my google-fu is lacking.</p>

<p>Here's the beginning of my test class just for reference:</p>

<pre><code>class ReviewTests: XCTestCase {

    private var userDefaults: UserDefaults = UserDefaults(suiteName: #file)!
    private var ubiquitousKeyValueStore: NSUbiquitousKeyValueStore = // How do I mock this?
    private var reviewPromptController: ReviewPromptController!
</code></pre>
",https://stackoverflow.com/questions/61533139/how-to-mock-nsubiquitouskeyvaluestore-for-unit-testing,"['ios', 'swift', 'xcode', 'unit-testing', 'nsubiquitouskeyvaluestore']",240,True,1,1
Unit Testing with the material-ui/picker,"<p>I am utilizing the material-ui/picker in my application and would like to have full unit test coverage.  I am using both the KeyboardDatePicker and KeyboardTimePicker to give the users the option to type the date and time in if they do not like using the pickers.</p>

<p>Where should I be declaring a 'data-testid' in order to be able to either do a fireEvent.change or a userEvent.type (or something else if there is a different recommended way of triggering this type of event)?</p>

<p>I have tried adding the data-testid as part of the props on the pickers themselves, as part of the inputProps, and as part of the InputAdornmentProps but then when I try running either:</p>

<p><code>fireEvent.change(getByTestId('keyboardtimepicker-testid'), { target: { value: '12:00' } })</code></p>

<p>and</p>

<p><code>await userEvent.type(getByTestId('keyboardtimepicker-testid'), '12:00')</code></p>

<p>both throw an error.</p>

<p>If I put the data-testid in the KeyboardButtonProps, I don't see an error but the onChange function is not getting triggered.</p>

<p>How should I be unit testing with components from material-ui/picker?</p>
",https://stackoverflow.com/questions/60396075/unit-testing-with-the-material-ui-picker,"['unit-testing', 'testing', 'jestjs', 'material-ui']",2733,True,1,2
Unit Testing failures from Futures in Scala,"<p>I'm trying to test the error handling in a script I'm writing. If the async function fetchBar fails I pattern match the failure case and then return a successful future containing the failed result.</p>

<pre><code>val fetchedBar = Try(fooClient.fetchBar(params))

fetchedBar match {
  case Success(bar) =&gt; foobar(bar)
  case Failure(e) =&gt; Future.successful(FooResult(success = false))
}
</code></pre>

<p>However when I unit test this flow I'm having trouble testing the failure case. I have stubbed fetchBar to return a failed future as shown below.</p>

<pre><code>val fetchedBar = Try(Future.failed(new Exception()))

</code></pre>

<p>But I noticed that fetchedBar returns a Success rather than a Failure. Why is that and how can I stub the fetchBar function to create a failed Try?</p>
",https://stackoverflow.com/questions/59779887/unit-testing-failures-from-futures-in-scala,"['scala', 'unit-testing', 'future']",1446,True,1,1
Android - Issues with Awaitility and Unit Testing,"<p>I have a pretty simple test. I'm waiting for a list of transactions to be received and assigned to a list view.</p>

<pre><code>@Test
fun testTransactionsLoad(){
    val listView: ListView? = fragment!!.findView(R.id.listView)

    assertNotNull(listView)

    await().atMost(20, TimeUnit.SECONDS).until(transactionsLoad(listView!!))

    assert(listView.adapter.count &gt; 0)
}
</code></pre>

<p>But for some reason, awaitability always send false for this callable:</p>

<pre><code>private fun transactionsLoad(listView: ListView): Callable&lt;Boolean&gt; {
    return if (listView.adapter == null){
        Callable { false }
    } else {
        Callable { true }
    }
}
</code></pre>

<p>It's not the first time Awaitility returns the wrong thing. On my device, the list view loads, proving it should also have an adapter. The adapter still appears as null in the callable though.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/59866744/android-issues-with-awaitility-and-unit-testing,"['android', 'testing', 'junit']",288,False,1,1
Patching python class constructor for unit testing,"<p>How can I test the constructor of my class, and subsequent objects created by it? I tried different combinations, and patching the <code>__init__</code> function of <code>MyClass</code>, but I get different errors depending on what I try, for example <code>__init__() should return None, not 'Mock'</code>.</p>
<p>How should I patch to make the below test pass?</p>
<p><strong>test_mystuff.py</strong></p>
<pre><code>import unittest.mock as mock
import unittest
from unittest.mock import Mock

from my_package.my_functions import do_something


class MyTestCase(unittest.TestCase):

    @mock.patch('my_package.my_classes.MyClass')
    def test_object_is_created_and_does_action(self, mock_class):
        arg1 = Mock()
        arg2 = Mock()
        
        mock_object = Mock()
        mock_class.return_value = mock_object
        
        do_something(arg1, arg2)
        mock_class.assert_called_with(arg1, arg2)

        mock_object.do_action.assert_called_once()
        
        
</code></pre>
<p><strong>my_functions</strong></p>
<pre><code>from my_package.my_classes import MyClass


def do_something(arg1, arg2):
    my_object = MyClass(arg1, arg2)
    my_object.do_action()


        
</code></pre>
<p><strong>my_classes.py</strong></p>
<pre><code>class MyClass(object):
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def do_action(self):
        print(self.arg1)
</code></pre>
",https://stackoverflow.com/questions/63033210/patching-python-class-constructor-for-unit-testing,"['python', 'unit-testing', 'python-unittest']",190,False,1,0
How to construct org.jooq.Result for unit testing,"<p>I am writing unit tests for fetching records from Oracle DB using JOOQ library and I need to mock data returned by <code>DSLContext</code>'s <code>fetch()</code> function. How can I create sample <code>Result&lt;Record&gt;</code> to be returned by mocked function? I googled it for few hours and could not find an answer.</p>
",https://stackoverflow.com/questions/62073697/how-to-construct-org-jooq-result-for-unit-testing,"['java', 'jooq']",759,True,1,2
unit testing ListenableFuture kafkaTemplate.send always returns null,"<p>I'm trying to unit test the callbacks from the kafkaTemplate.send() but its not working as expected. here's the code snippet of the code im trying to test.</p>

<pre><code>    @Override
    public void sendMessage(String topicName, String message) {

        ListenableFuture&lt;SendResult&lt;String, String&gt;&gt; future = kafkaTemplate.send(topicName, message);
        future.addCallback(new ListenableFutureCallback&lt;SendResult&lt;String, String&gt;&gt;() {

            @Override
            public void onSuccess(SendResult&lt;String, String&gt; result) {
                System.out.print(""Success"")
            }
            @Override
            public void onFailure(Throwable ex) {
                System.out.print(""Failed"")
            }
        });
    }
</code></pre>

<p>and this is the unit test code</p>

<pre><code>
    private KafkaTemplate&lt;String, String&gt; kafkaTemplate;
    private KafkaService kafkaService;
    private SendResult&lt;String, String&gt; sendResult;
    private ListenableFuture&lt;SendResult&lt;String, String&gt;&gt; future;
    private RecordMetadata recordMetadata
    private String topicName
    private String message



    def setup() {
        kafkaTemplate = Mock(KafkaTemplate.class)
        kafkaService = new KafkaService(kafkaTemplate);
        topicName = ""test.topic""
        message = ""test message""
        sendResult = Mock(SendResult.class);
        future = Mock(ListenableFuture.class);
        recordMetadata = new RecordMetadata(new TopicPartition(topicName, 1), 1L, 0L, 0L, 0L, 0, 0);
    }

    def ""Test success send message method""() {
        given:
        sendResult.getRecordMetadata() &gt;&gt; recordMetadata
        kafkaTemplate.send(_ as String, _ as String) &gt;&gt; future

        when:
        kafkaService.sendMessage(topicName, message)

        then:
        // catch success or failed here.

        1 * kafkaTemplate.send(_,_) &gt;&gt; {arguments -&gt;
            final String topicNameParam = arguments.get(0)
            final String messageParam = arguments.get(1)

            assert topicNameParam == topicName
            assert messageParam == message
        }
    }
</code></pre>

<p>based on the debugger future is null on this scenario</p>

<pre><code>ListenableFuture&lt;SendResult&lt;String, String&gt;&gt; future = kafkaTemplate.send(topicName, message); // future null
 future.addCallback(new ListenableFutureCallback&lt;SendResult&lt;String, String&gt;&gt;() { // future null
</code></pre>

<p>i already read a lot of answers here but it does not solved the issue or havent they explain it well that i would understand where the problem is. like this one <a href=""https://stackoverflow.com/a/56677098"">https://stackoverflow.com/a/56677098</a></p>

<p>thanks for the help in advance!</p>
",https://stackoverflow.com/questions/61100974/unit-testing-listenablefuture-kafkatemplate-send-always-returns-null,"['spring-boot', 'unit-testing', 'groovy', 'spock', 'spring-kafka']",7340,True,1,2
Spark Unit testing breaking the transformation chaining?,"<p>This is my transformation function. I want to test it.
Should I break(move) each transformation chain into separate functions and test them separately or just test the whole function or both?</p>

<pre><code>private def transform[T](
      spark: SparkSession,
      data: DataFrame
  ) = {
    val beefData = data
      .filter(col(""ingredients"").contains(""beef"") || col(""name"").contains(""beef""))
      .withColumn(""total_cook_time"", col(""cookTime"") + col(""prepTime""))
      .withColumn(
        ""difficulty"",
        when(col(""total_cook_time"") &lt; 30, ""easy"")
          .when(col(""total_cook_time"") between (30, 60), ""medium"")
          .when(col(""total_cook_time"") &gt; 60, ""hard"")
      )

    beefData.createOrReplaceTempView(""BeefRecipes"")
    spark
      .sql(
        ""select difficulty, avg(total_cook_time) as avg_total_cooking_time from BeefRecipes group by difficulty""
      )
      .show()

  }
</code></pre>
",https://stackoverflow.com/questions/62030988/spark-unit-testing-breaking-the-transformation-chaining,"['scala', 'apache-spark']",99,False,1,0
Unit testing using a CSV for arguments,"<p>I am testing a function and have written unit tests to assert if the result matches what I expect when I input certain arguments into the function.</p>
<p>Instead of writing many unit tests, I want to read a csv file that has, row by row, all the possible permutations of arguments and an expected result. The test should loop through each row of arguments, compare expected result with actual result and give me the pass or fail.</p>
<p>I am very new to python and testing with python.</p>
",https://stackoverflow.com/questions/63946195/unit-testing-using-a-csv-for-arguments,['python'],83,False,1,0
C# unit testing mocking service ignoring return,"<p>I am writing some unit tests to test a controller. In that controller there is a call to a service.  In my test I want to mock the service call and obviously specify the desired return.</p>
<p>When the code runs it goes into the controller and when it reaches the service I can clearly see that it is using my mock.  However, the return value of the mock is always null and not the return that I specified (i.e. <code>expectedItem</code>). Any idea?</p>
<h3>Unit test against controller's action</h3>
<pre class=""lang-cs prettyprint-override""><code>public class SearchIATeamControllerTests : IDisposable
{
    private readonly SearchIATeamController _sut;
    private IFixture _fixture;

    public SearchIATeamControllerTests()
    {
        _fixture = new Fixture().Customize(new AutoMoqCustomization());
        _sut = _fixture.Create&lt;SearchIATeamController&gt;();
    }


    [Fact]
    public async Task Get_team_name_with_ia_team_name_returns_ok()
    {
        // Arrange
        var expectedResultItem = _fixture.Create&lt;SearchIATeamResponse&gt;();

        var expectedItem = new List&lt;SearchIATeamResponse&gt;
        {
            expectedResultItem
        };

        var mockIATeamService = _fixture.Create&lt;Mock&lt;IIATeamSearchService&gt;&gt;();
        mockIATeamService.Setup(m =&gt; m.GetIATeamName(It.IsAny&lt;string&gt;())).ReturnsAsync(expectedItem);

        // Act
        var result = await _sut.Get(&quot;test&quot;).ConfigureAwait(false);
    }
} 
</code></pre>
<p>Names have been abbreviated for brevity.</p>
<h3>System Under Test</h3>
<pre><code>public async Task&lt;ActionResult&lt;SearchIATeamResponse&gt;&gt; Get([FromQuery] string iATeamName)
{   
    if (iATeamName == null)
    {
        return BadRequest();
    }

    try
    {
        var result = await _searchIATeamService.GetIATeamName(iATeamName);

        if (!result.Any())
        {
            return NotFound();
        }

        return Ok(result);

     }
     catch (ArgumentException ex)
     {
         return BadRequest(ex.Message);
     }      
}
</code></pre>
",https://stackoverflow.com/questions/63177081/c-unit-testing-mocking-service-ignoring-return,"['c#', 'moq', 'autofixture']",1153,True,1,2
Unit testing void controller and service methods,"<p>I have built a REST API that does basic CRUD operations on a product database and I am now unit testing all the methods within the controller and service layer. I have realised that methods such as addProduct, updateProduct or deleteProduct return void on both of the layers.</p>
<p>How do I go about mocking the repository when testing the service layer and mocking the service while testing controller layer for these methods?</p>
<p>Controller method:</p>
<pre><code>@RequestMapping(method= RequestMethod.POST,value =&quot;/products&quot;)
public void addProduct(@RequestBody Product product){
    productService.addProduct(product);
}
</code></pre>
<p>Service method:</p>
<pre><code>public void addProduct(Product product){
    productRepository.save(product);
}
</code></pre>
<p>I have commented in the fields where I need help for the addProduct() methods.</p>
<p>Controller tests:</p>
<pre><code>package com.product.controllers;

import com.product.entities.Product;
import com.product.services.ProductService;
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 org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class ProductControllerTest {

@InjectMocks
ProductController productController;

@Mock
ProductService productService;

@Test
public void getHomePage(){
    String homePageText = &quot;Welcome to the home page!&quot;;
    assertEquals(homePageText,productController.getHomePage());
}

@Test
public void getAllProducts(){
    
    Product product1 = new Product();
    product1.setId(&quot;001&quot;);
    product1.setName(&quot;TV&quot;);
    product1.setPrice(999.99);

    Product product2 = new Product();
    product2.setId(&quot;002&quot;);
    product2.setName(&quot;Mobile&quot;);
    product2.setPrice(300D);

    List&lt;Product&gt; listOfProducts = new ArrayList&lt;&gt;();
    listOfProducts.add(product1);
    listOfProducts.add(product2);

    when(productService.getAllProducts()).thenReturn(listOfProducts);
    assertEquals(listOfProducts,productController.getAllProducts());
}

@Test
public void getProductById(){
    
    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    when(productService.getProductById(&quot;001&quot;)).thenReturn(product);
    assertEquals(new ResponseEntity&lt;Product&gt; (product, HttpStatus.OK),productController.getProductById(&quot;001&quot;));
}

@Test
public void addProduct() {
    
    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    // need help with this
}
}
</code></pre>
<p>Service tests:</p>
<pre><code>package com.product.services;

import com.product.entities.Product;
import com.product.repositories.ProductRepository;
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 java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class ProductServiceTest {

@InjectMocks
ProductService productService;

@Mock
ProductRepository productRepository;

@Test
public void getAllProducts() {

    Product product1 = new Product();
    product1.setId(&quot;001&quot;);
    product1.setName(&quot;TV&quot;);
    product1.setPrice(999.99);

    Product product2 = new Product();
    product2.setId(&quot;002&quot;);
    product2.setName(&quot;Mobile&quot;);
    product2.setPrice(300D);

    List&lt;Product&gt; listOfProducts = new ArrayList&lt;&gt;();
    listOfProducts.add(product1);
    listOfProducts.add(product2);

    when(productRepository.findAll()).thenReturn(listOfProducts);
    assertEquals(listOfProducts, productService.getAllProducts());
}

@Test
public void getProductById() {

    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    when(productRepository.findById(&quot;001&quot;)).thenReturn(java.util.Optional.of(product));
    assertEquals(product, productService.getProductById(&quot;001&quot;));


}

@Test
public void addProduct() {

    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    // need help with this
}
}
</code></pre>
",https://stackoverflow.com/questions/63774801/unit-testing-void-controller-and-service-methods,"['java', 'maven', 'junit', 'rest']",3492,True,1,1
Unit Testing the NestJS Routes are defined,"<p>I found <a href=""https://stackoverflow.com/questions/58255000/how-can-i-get-all-the-routes-from-all-the-modules-and-controllers-available-on"">this question</a> about determine the routes.  While the first answer is exactly what I need, and it works</p>
<pre><code>import { Controller, Get, Request } from &quot;@nestjs/common&quot;;
import { Request as ExpressRequest, Router } from &quot;express&quot;;

@Get()
root(@Request() req: ExpressRequest) {
    const router = req.app._router as Router;
    return {
        routes: router.stack
            .map(layer =&gt; {
                if(layer.route) {
                    const path = layer.route?.path;
                    const method = layer.route?.stack[0].method;
                    return `${method.toUpperCase()} ${path}`
                }
            })
            .filter(item =&gt; item !== undefined)
    }
}
</code></pre>
<p>I want to be able to unit test this.</p>
<p>My end to end test works fine</p>
<pre><code>    it('/api (GET) test expected routes', async done =&gt; {
        const ResponseData = await request(app.getHttpServer())
            .get('/api')
            .set('Accept', 'application/json');

        expect(ResponseData.status).toBe(200);
        expect(ResponseData.headers['content-type']).toContain('json');
        expect(ResponseData.body.routes.length).toBeGreaterThan(2);
        done();         // Call this to finish the test
    });
</code></pre>
<p>The problem I am having, is how to create and pass the Request part that is needed for the root() call for a unit test.  The ExpressRequest is not a class or anything to simply create, and then assign values.  It is currently a large definition.  I assume there must be an easy way to create one, but I have not found it yet.</p>
",https://stackoverflow.com/questions/64776196/unit-testing-the-nestjs-routes-are-defined,"['testing', 'routes', 'jestjs', 'nestjs']",698,True,1,1
Unit Testing involving DB (Insert/Update/Select),"<p>Looking forward to know the best practice in this area and context.</p>

<p>Two scenarios</p>

<ol>
<li>I have a component written in Java &amp; Spring where I am getting some data , converting it into another format that involves core business logic and insert/update a Cassandra DB.</li>
<li>Another java component reads data from that DB, runs business logic on that and take care of some other functionalities.</li>
</ol>

<p>Now while writing the unit test cases I can think of the below two high level approaches</p>

<ol>
<li>I can use Mockito or similar and mock the DAO object so that I don't actually call DB while doing get and save operations on DAO Object.</li>
<li>I can actually not mock and let is connect to DB.</li>
<li>We connect to DB only during build snapshot (for few test cases) </li>
</ol>

<p>However - </p>

<p>For (1) - We are not actually testing if the data are stored/updated properly.
For (2) - This should not be a good idea to do it in unit / regression as we don't want to connect to DB every time we do mvn install or build
For (3) - This sounds like a better option provided this is feasible.</p>

<p>Question is - 
What is the best practice around testing the DB operations as part of the unit tests or regression test or during build. Should we always mock these calls ?</p>
",https://stackoverflow.com/questions/59635613/unit-testing-involving-db-insert-update-select,"['database', 'unit-testing', 'mockito']",863,True,1,1
Asp.net Core MVC - Unit testing Razor Views,"<p>I am trying to write UI unit tests for my MVC core project and my problem is I am not able to find a MVC view generator or  renderer that I can use in my unit test project.</p>

<p>I did implement a ViewRenderService for a specific requirement in another project but I cannot use it because of the dependencies cannot be injected into the unit test project.</p>

<p>What is a better way to approach this for dotnet core mvc? Any guidance will help.</p>
",https://stackoverflow.com/questions/60663968/asp-net-core-mvc-unit-testing-razor-views,"['c#', 'asp.net-mvc', 'asp.net-core']",222,False,1,0
How to test method in unit testing,"<p>I have such <code>service</code> as below. Let's say i want to test <code>Create()</code> method. I read that in <code>unit testing</code> i should test by <code>comparing, counting</code> and so on. How could i then test my <code>Create()</code> method. Is it ugly to change return type from <code>void Create</code> to <code>bool Create</code> just to be able to check method output for testing purpose or that's not ideal idea? Can you propose something?</p>

<pre><code>public class CreateCarService : ICreateCarService
{
    private readonly ICarQuery _carQuery;
    private readonly ICarRepository _carRepository;

    public CreateCarService(ICarQuery carQuery, ICarRepository carRepository)
    {
        _carQuery = carQuery;
        _carRepository = carRepository;
    }

    public void Create(Car car)
    {
        if (car == null) throw new CusException(Error, ""Car object cannot be null"");

        if (_carQuery.IsLoginExist(car.Login))
            throw new CusException(Error, ""Message1"");

        if (_carQuery.IsEmailExist(car.Email))
            throw new CusException(Error, ""Message1"");

        _carRepository.Add(car);
    }
}
</code></pre>
",https://stackoverflow.com/questions/60929477/how-to-test-method-in-unit-testing,"['c#', 'unit-testing', 'nunit']",1532,True,1,3
Unit testing on a python class property,"<p>Suppose I have a class:</p>

<pre><code>class Player(object):
    def __init__(self):
        self.goal = ''

    @property
    def goal(self):
        return self.goal
</code></pre>

<p>Is it possible to write a unit test on the property <code>goal</code>, given that it is not callable?</p>
",https://stackoverflow.com/questions/59732625/unit-testing-on-a-python-class-property,"['python', 'unit-testing', 'python-unittest']",480,True,1,1
SyntaxError Importing Mocha for Typescript Unit Testing,"<p>Below I have a sample test for a Typescript project. I'm using mocha chai to do the testing. The test case is blank for now.</p>
<pre><code>import {KafkaConsumer} from '../infrastructure/delivery/kafka/kafka-consumer';
import {expect} from 'chai';
import {describe, it} from 'mocha';

describe('KafkaConsumer Initialization', () =&gt; {
    it('should initialize KafkaConsumer', () =&gt; {
    })
})
</code></pre>
<p>When I run the test I get the following error:</p>
<pre><code> import {describe} from 'mocha';
       ^

SyntaxError: Unexpected token {
</code></pre>
<p>Any idea why this might be? If I change line 3 to import 'mocha'; I a similar SyntaxError. Without that line, <code>describe()</code> and <code>it()</code> are not defined</p>
<p>Below is my <code>package.json</code> file.</p>
<pre><code>    {
  &quot;name&quot;: &quot;wss&quot;,
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;private&quot;: true,
  &quot;main&quot;: &quot;dist/index.js&quot;,
  &quot;scripts&quot;: {
    &quot;tsc&quot;: &quot;tsc&quot;,
    &quot;start&quot;: &quot;node --inspect=5858 -r ts-node/register ./src/index.ts&quot;,
    &quot;start:watch&quot;: &quot;nodemon&quot;,
    &quot;build&quot;: &quot;tsc&quot;,
    &quot;prod&quot;: &quot;tsc &amp;&amp; npm run postbuild &amp;&amp; node ./dist/index.js&quot;,
    &quot;postbuild&quot;: &quot;npm run copy-files&quot;,
    &quot;copy-files&quot;: &quot;copyfiles -u 1 ./src/**/*.js dist&quot;,
    &quot;test&quot;: &quot;env TS_NODE_COMPILER_OPTIONS='{\&quot;module\&quot;: \&quot;commonjs\&quot; }' mocha -r ts-node/register 'tests/**/*.ts'&quot;,
    &quot;test:watch&quot;: &quot;nodemon --exec npm test&quot;
  },
  &quot;nyc&quot;: {
    &quot;require&quot;: [
      &quot;ts-node/register&quot;
    ],
    &quot;include&quot;: [
      &quot;src/**/*.ts&quot;
    ],
    &quot;extension&quot;: [
      &quot;.ts&quot;
    ],
    &quot;reporter&quot;: [
      &quot;lcov&quot;,
      &quot;text&quot;
    ],
    &quot;sourceMap&quot;: true,
    &quot;instrument&quot;: true
  },
  &quot;dependencies&quot;: {
    &quot;@types/dotenv&quot;: &quot;^6.1.1&quot;,
    &quot;@types/newrelic&quot;: &quot;^5.11.0&quot;,
    &quot;@types/redis&quot;: &quot;^2.8.21&quot;,
    &quot;aws-iot-device-sdk&quot;: &quot;^2.2.4&quot;,
    &quot;axios&quot;: &quot;^0.19.0&quot;,
    &quot;bluebird&quot;: &quot;^3.5.5&quot;,
    &quot;chai-http&quot;: &quot;^4.3.0&quot;,
    &quot;cookie-parser&quot;: &quot;~1.4.3&quot;,
    &quot;copyfiles&quot;: &quot;^2.2.0&quot;,
    &quot;dotenv&quot;: &quot;^7.0.0&quot;,
    &quot;express&quot;: &quot;~4.16.0&quot;,
    &quot;kafka-node&quot;: &quot;^4.1.3&quot;,
    &quot;lodash&quot;: &quot;^4.17.15&quot;,
    &quot;morgan&quot;: &quot;~1.9.0&quot;,
    &quot;newrelic&quot;: &quot;^5.11.0&quot;,
    &quot;redis&quot;: &quot;^3.0.2&quot;,
    &quot;reflect-metadata&quot;: &quot;^0.1.13&quot;,
    &quot;uuid&quot;: &quot;^8.0.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/bluebird&quot;: &quot;^3.5.27&quot;,
    &quot;@types/express&quot;: &quot;^4.16.1&quot;,
    &quot;@types/jsonwebtoken&quot;: &quot;^8.3.2&quot;,
    &quot;@types/lodash&quot;: &quot;^4.14.150&quot;,
    &quot;@types/mocha&quot;: &quot;^8.0.0&quot;,
    &quot;@types/node&quot;: &quot;^11.13.14&quot;,
    &quot;@types/winston&quot;: &quot;^2.4.4&quot;,
    &quot;chai&quot;: &quot;^4.2.0&quot;,
    &quot;eslint&quot;: &quot;^4.19.1&quot;,
    &quot;mocha&quot;: &quot;^8.0.1&quot;,
    &quot;nodemon&quot;: &quot;^1.18.11&quot;,
    &quot;nyc&quot;: &quot;^14.1.1&quot;,
    &quot;ts-node&quot;: &quot;^8.10.2&quot;,
    &quot;ts-node-dev&quot;: &quot;^1.0.0-pre.41&quot;,
    &quot;tslint&quot;: &quot;^5.16.0&quot;,
    &quot;typescript&quot;: &quot;^3.9.2&quot;,
    &quot;typescript-eslint-parser&quot;: &quot;^22.0.0&quot;
  }
}
</code></pre>
",https://stackoverflow.com/questions/62900961/syntaxerror-importing-mocha-for-typescript-unit-testing,"['node.js', 'typescript', 'mocha.js', 'chai']",515,False,0,1
Testing a private method in unit testing,"<p>I know the answer to this question is: you do not test private method but only the public method that will eventually lead to that private method invocation.</p>
<p>BUT
In my case, the public method actually starting up a consumer/connection to kafka, so i only want to test the logic done when a kafka message is received.
I do not want to make the logic method public as no one will use it out side of the kafka infrastructure, but still i want to unit test the logic done there.</p>
<p>What is the best practice solution? I can change the code if need be</p>
<p>Heres some examples:</p>
<p>the private method in question</p>
<pre><code> private void handleConsumerRecord(ConsumerRecord&lt;PK, byte[]&gt; cr, Acknowledgment acknowledgment) throws IOException {
//logic to be tested
}
</code></pre>
<p>the private method that calls the private logic method</p>
<pre><code>/**
     * Initialize the kafka message listener
     */
    private void initConsumerMessageListenerContainer(ProducerFactory&lt;PK, V&gt; producerFactory) {
        if (!processAsBatch) {
            // start a acknowledge message listener to allow the manual commit
            acknowledgingMessageListener =  (cr, acknowledgment) -&gt; {
                try {
                    handleConsumerRecord(cr, acknowledgment);
                } catch (IOException e) {
                    log.error(&quot;Failed to handle consumed message, commiting message and performing irrecoverableException actions&quot;);
                    exceptionHandlerManager.getIrrecoverableExceptionHandler().performAction(null, cr.value(), cr.topic(), cr.key());
                }
            };

            // start and initialize the consumer container
            container = initContainer(acknowledgingMessageListener, producerFactory);
}
</code></pre>
<p>and this is the public method that starts everything</p>
<pre><code>/**
     * Start the message consumer
     * The record event will be delegate on the onMessage()
     */
    public void start(ProducerFactory&lt;PK, V&gt; producerFactory) {
        initConsumerMessageListenerContainer(producerFactory);
        container.start();
    }
</code></pre>
<p>The unit test i tried to write</p>
<pre><code>    kafkaByteArrConsumer.getAcknowledgingMessageListener().onMessage(record, acknowledgment);
        doThrow(TemporaryException.class).when(kafkaByteArrConsumer).getConsumerMessageLogic().onMessage(record.value(), acknowledgment);
        Mockito.verify(exceptionHandlerManager.getTemporaryExceptionHandler(), Mockito.times(1))
                .performAction();
</code></pre>
<p>As you can see, the <code>getAcknowledgingMessageListener</code> will not be initialized by the <code>initConsumerMessageListenerContainer()</code> and therefore i wont be able to access the handleConsumer method when mocking <code>.getConsumerMessageLogic().onMessage</code></p>
<p>(which is called by the //some logic to be tested part)</p>
",https://stackoverflow.com/questions/64135554/testing-a-private-method-in-unit-testing,"['java', 'junit']",232,True,0,2
ReactJS Jest enzyme unit testing axios.get() axios.post(),"<p>My code is like</p>
<pre class=""lang-js prettyprint-override""><code>constructor(props) {
  super();
  this.state = {
    isLoading: true,
    questionsData: [],
    studyCategoryList: [],
    studyList: [],
    filteredStudyList: [],
    selectedStudyCategory: &quot;0&quot;,
    selectedStudy: &quot;0&quot;,
    filterData: [],
    deleteQuestionIndex: 0   
  };
}
</code></pre>
<p>In constructor, I am initializing the state, and I have written below method for dropdowns data</p>
<pre class=""lang-js prettyprint-override""><code>componentDidMount() {
  this._isMounted = true;
  axios
    .get(url + &quot;getAllQuestionsDropdownValues&quot;)
    .then((response) =&gt; {
      this.setState({ studyCategoryList: response.data[0],studyList: response.data[1] });
      // this.setState({ studyList: response.data[1] });
      // this.setState({ isLoading: false });
    })
    .catch((error) =&gt; {
      console.log(error);
      // this.setState({ isLoading: false });
    });

  this.getQuestionsData(this.state.selectedStudyCategory, this.state.selectedStudy);

  const selectAll = &quot;0&quot;;
  this.state.selectedStudyCategory = selectAll;
  this.state.selectedStudy = selectAll;
}
</code></pre>
<p>Based on dropdown selection, posting the dropdown selected data and getting the filtered data from database. find the below post method for it.</p>
<pre class=""lang-js prettyprint-override""><code>getQuestionsData = (scid, sid) =&gt; {
  this.setState({ isLoading: true });
  axios.post(`${url}getQuestionList`, { studycategoryid: scid, studyid: sid })
    .then((response) =&gt; {
      this.setState({ questionsData: response.data, filterData: response.data });
    })
    .catch((error) =&gt; {
      this.setState({ isLoading: false });
    });
}
</code></pre>
<p>When writing the uint test cases with axios, I couldn't able to write test cases with jest enzyme on axios get and post methods.</p>
<p>Please provide complete example to achieve it.</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/65102865/reactjs-jest-enzyme-unit-testing-axios-get-axios-post,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",689,False,0,1
Unit testing euler-to-quaternion implementation fails,"<p>I'm currently trying to implement a quaternion, in which I need euler-to-quaternion conversion. My current implementation looks like this, which I've nicked from <a href=""https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles"" rel=""nofollow noreferrer"">here</a></p>

<pre><code>void Quaternion::FromEuler(double x, double y, double z)
{
    z *= Math::DegToRad;
    y *= Math::DegToRad;
    x *= Math::DegToRad;

    double xCos = Math::Cos(x / 2);
    double xSin = Math::Sin(x / 2);
    double yCos = Math::Cos(y / 2);
    double ySin = Math::Sin(y / 2);
    double zCos = Math::Cos(z / 2);
    double zSin = Math::Sin(z / 2);

    W = zCos * yCos * xCos + zSin * ySin * xSin;
    X = zCos * yCos * xSin - zSin * ySin * xCos;
    Y = zSin * yCos * xSin + zCos * ySin * xCos;
    Z = zSin * yCos * xCos - zCos * ySin * xSin;
}
</code></pre>

<p>I'm testing the implementation using the following unit test</p>

<pre><code>TEST(Quaternions, FromEuler)
{
    Quaternion quaternion(45, 90, 180);


    ExpectNear(quaternion, 0.6532815, -0.2705981, 0.6532815, 0.270598);
}
</code></pre>

<p>Which fails in the following way.</p>

<pre><code>  Expected | Actual     
X  0.6533   -0.6533
Y -0.2706    0.2706
Z  0.6533    0.6533
W  0.2706    0.2706
</code></pre>

<p>The expected value have been acquired from a variety of websites, which yields the same values, but with different signs, similar to how my current output differs from the expected output.</p>

<p>I've also tried several different implementation, yielding the same type of failure.</p>

<p>Is this due to rotations having <a href=""https://drive.google.com/file/d/0B9rLLz1XQKmaUHhmMExJbVZtb0U/view"" rel=""nofollow noreferrer"">several representations</a>, in which case the failure of my unit test is actually a false negative? If so, how do I implement a proper unit test?</p>
",https://stackoverflow.com/questions/60059409/unit-testing-euler-to-quaternion-implementation-fails,"['c++', 'unit-testing', 'quaternions', 'euler-angles']",378,True,0,1
Unit testing WebAPI Controller that takes parameters,"<p>I have a WebAPI controller that takes a parameters object like this:</p>

<pre><code>public class InvoicesParameters : QueryStringParameters
{
    public string InvoiceType { get; set; } = ""P"";
    public bool Approved { get; set; } = false;
    public string Region { get; set; } = null;
    public string VendorCode { get; set; } = null;
}
</code></pre>

<p>The controller works just fine. I can pass any or all of the params and get the expected results. Now I am trying to add a unit test for this controller using xUnit. I've tried several different methods all with various failing results.</p>

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

<pre><code>[Theory(DisplayName = ""Get Invoices"")]
[ClassData(typeof(InvoicesParametersTestData))]
public void GetInvoices_ShouldReturnInvoices(InvoicesParameters iparams)
{
    var mockService = new Mock&lt;IShopAPService&gt;();
    mockService.Setup(x =&gt; x.GetInvoices(iparams))
        .Returns(GetSampleInvoices());

    var controller = new InvoicesController(mockService.Object);

    IHttpActionResult actionResult = controller.GetInvoices(iparams);
    var contentResult = actionResult as OkNegotiatedContentResult&lt;List&lt;Invoice&gt;&gt;;

    Assert.NotNull(contentResult);
    Assert.NotNull(contentResult.Content);
    Assert.Equal(3, contentResult.Content.Count);
}

private List&lt;InvoiceDto&gt; GetSampleInvoices()
{
    List&lt;InvoiceDto&gt; output = new List&lt;InvoiceDto&gt;
    {
        new InvoiceDto
        {
            Id = 1,
            VendorCode = ""PFSATL"",
            VendorName = ""PlantStone LLC"",
            Type = ""I"",
            PONumber = ""54P-00007365"",
            OrderId  = ""940817"",
            InvoiceType = ""P"",
            InvoiceNumber = ""DT1010816950"",
            InvoiceDate = Convert.ToDateTime(""01/01/2020""),
            InvoiceAmount = 2496.48M,
            Region = ""WEST"",
            ShopNumber = ""16"",
            ApprovalDate = null,
            Approver = null
        },
        new InvoiceDto
        {
            Id = 2,
            VendorCode = ""NATSLC"",
            VendorName = ""National American Doodads"",
            Type = ""I"",
            PONumber = ""72P-00004838"",
            OrderId  = ""874566"",
            InvoiceType = ""P"",
            InvoiceNumber = ""123454321789"",
            InvoiceDate = Convert.ToDateTime(""01/01/2020""),
            InvoiceAmount = 457.88M,
            Region = ""WEST"",
            ShopNumber = ""16"",
            ApprovalDate = null,
            Approver = null
        },
        new InvoiceDto
        {
            Id = 3,
            VendorCode = ""BRIDG"",
            VendorName = ""Bridgeport Soda"",
            Type = ""I"",
            PONumber = ""54P-0074865"",
            OrderId  = ""741258"",
            InvoiceType = ""P"",
            InvoiceNumber = ""987456"",
            InvoiceDate = Convert.ToDateTime(""01/01/2020""),
            InvoiceAmount = 74.99M,
            Region = ""WEST"",
            ShopNumber = ""16"",
            ApprovalDate = null,
            Approver = null
        }
    };

    return output;
}


public class InvoicesParametersTestData
{
    public static IEnumerable&lt;InvoicesParameters&gt; TestData
    {
        get
        {
            yield return new InvoicesParameters { InvoiceType = ""P"", Approved = false };
            yield return new InvoicesParameters { InvoiceType = ""P"", Approved = true };
        }
    }
}
</code></pre>

<p>Something is not right with this pattern. I am getting a compile time error of ClassData must point to a valid class.  Is there a better way to do this? or a way to fix what I have?</p>
",https://stackoverflow.com/questions/59566218/unit-testing-webapi-controller-that-takes-parameters,"['c#', '.net', 'xunit', 'xunit.net']",331,True,0,1
Getting NullPointerException performing unit-testing with Mockito,"<p><br/>
Please don't mark it as duplicate, I am unable to fix this issue.
<br/><br/>
I am writing unit testing using <em>Mockito</em>. While executing the test case, I am getting <code>NullPointerException</code> on the <code>@Autowired bean</code> of <code>MainTemplate class</code>.</p>

<p>Code:</p>

<pre><code>public abstract class Template{

  abstract public boolean isEven(String input);

  private String getName(String initial){
    return ""INIT""+initial;
  }

  final public void run(String input){
   isEven(input);
   getName(input);

  }
}
</code></pre>

<p><br/>
Implementation of Template:
<br/></p>

<pre><code>public class MainTemplate extends Template{

 @Autowired
 private UserUtil userUtil;

    @Override
    public boolean isEven(String input){
      return userUtil.getResult(input);  //GETTING NullPointerException here..
    }
}
</code></pre>

<p><br/>
Bean configuration:</p>

<pre><code>@Configuration
public class BeanConfiguration{
  @Bean
  public Template getBean(){
     return new MainTemplate();
  }
}

@Service
public class Executor{
 @Autowired
 private BeanConfiguration beanConfig;

 public void execute(){
   beanConfig.getBean().run(""sample input"");
 }

}
</code></pre>

<p>Unit testing class:
<br/></p>

<pre><code>@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MainTemplateTest{

  @InjectMocks
  private MainTemplate mainTemplate;

  @Mock
  private UserUtil userUtil;

  @Test
  public void isEvenTest(){

    Mockito.when(userUtil.getResult(anyString())).thenReturn(true);

    mainTemplate.isEven(""input string"");
  }
}
</code></pre>

<p><br/>
I am getting NullPointerException while running the above test.<br/>
Getting NullPointerException on:
<br/></p>

<pre><code>    @Override
    public boolean isEven(String input){
      return userUtil.getResult(input);  //GETTING NullPointerException, while calling from mock method
    }
</code></pre>
",https://stackoverflow.com/questions/61323907/getting-nullpointerexception-performing-unit-testing-with-mockito,"['java', 'unit-testing', 'mockito']",330,True,0,1
unit testing the commandhandler depended on Interface,"<p>I am not much comfortable to write unit test. So sorry for asking basic questions.</p>

<p>Here is commandhandler </p>

<pre><code>ICalculateAge CalculateAge { get; set; }

public UpdateAgeCommandHandler(ICalculateAge calculateAge)
{
    this.CalculateAge = calculateAge;
}
</code></pre>

<p>I want to unit test this, so I tried below in of cs file in my test project:</p>

<pre><code>UpdateAgeCommandHandler cmd1 =  new UpdateAgeCommandHandler());
</code></pre>

<p>But its not working because I am not passing Interface. How do I pass this interface?</p>
",https://stackoverflow.com/questions/59897424/unit-testing-the-commandhandler-depended-on-interface,"['c#', 'asp.net', 'nservicebus']",132,True,0,1
Angular 7 Unit testing - PhantomJS has crashed,"<p>I am using Angular 7 for unit testing using karma and phantom JS. While I have run from my local machine, from my MAC --</p>

<pre><code>ng test --watch=false
</code></pre>

<p>Local Machine Output -</p>

<pre><code>ng test
10% building modules 2/2 modules 0 active18 01 2020 14:54:57.990:WARN [karma]: No captured browser, open http://localhost:9876/
18 01 2020 14:54:57.995:INFO [karma-server]: Karma v3.1.4 server started at http://0.0.0.0:9876/
18 01 2020 14:54:57.997:INFO [launcher]: Launching browsers PhantomJS with concurrency unlimited
18 01 2020 14:54:58.011:INFO [launcher]: Starting browser PhantomJS
 10% building modules 5/7 modules 2 active ..._weather_forcast_testing/src/styles.cssBrowserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`
18 01 2020 14:55:05.820:WARN [karma]: No captured browser, open http://localhost:9876/    
18 01 2020 14:55:06.004:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket i77IuK4nefa0HrxhAAAA with id 31463905
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 6 of 6 SUCCESS (1.598 secs / 1.535 secs)
TOTAL: 6 SUCCESS
TOTAL: 6 SUCCESS
</code></pre>

<p>It's working fine. MAC Configuration - </p>

<pre><code>Angular CLI: 7.3.7
Node: 8.9.4
OS: darwin x64
Angular: 7.2.11
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.11.4
@angular-devkit/build-angular     0.11.4
@angular-devkit/build-optimizer   0.11.4
@angular-devkit/build-webpack     0.11.4
@angular-devkit/core              7.1.4
@angular-devkit/schematics        7.3.7
@angular/cdk                      7.3.6
@angular/cli                      7.3.7
@angular/flex-layout              7.0.0-beta.22
@angular/material                 7.3.6
@ngtools/webpack                  7.1.4
@schematics/angular               7.3.7
@schematics/update                0.13.7
rxjs                              6.4.0
typescript                        3.2.2
webpack                           4.23.1
</code></pre>

<p>I deployed the same code in AWS EC2 - Ubuntu 18.04, Try to run the same command - </p>

<pre><code>ng test --watch=false
</code></pre>

<p>Ubuntu machine Output -</p>

<pre><code>ng test
10% building modules 2/2 modules 0 active18 01 2020 09:22:29.639:WARN [karma]: No captured browser, open http://localhost:9876/
    18 01 2020 09:22:29.710:INFO [karma-server]: Karma v3.1.4 server started at http://0.0.0.0:9876/
    18 01 2020 09:22:29.710:INFO [launcher]: Launching browsers PhantomJS with concurrency unlimited
    18 01 2020 09:22:29.831:INFO [launcher]: Starting browser PhantomJS
     10% building modules 7/10 modules 3 active ..._weather_forcast_testing/src/styles.cssBrowserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`
     52% building modules 354/354 modules 0 active18 01 2020 09:23:29.869:WARN [launcher]: PhantomJS have not captured in 60000 ms, killing.
     56% building modules 390/390 modules 0 active18 01 2020 09:23:34.149:INFO [launcher]: Trying to start PhantomJS again (1/2).
     95% emitting CopyPlugin                                                                  

    18 01 2020 09:24:54.635:WARN [launcher]: PhantomJS have not captured in 60000 ms, killing.
    18 01 2020 09:25:24.043:WARN [karma]: No captured browser, open http://localhost:9876/
    18 01 2020 09:25:24.793:INFO [launcher]: Trying to start PhantomJS again (2/2).
    18 01 2020 09:25:25.515:ERROR [karma-server]: { Error: spawn ENOMEM

    Cannot read property 'success' of undefined
    TypeError: Cannot read property 'success' of undefined
        at TestCommand.runSingleTarget (/home/ubuntu/youtube_angular7__weather_forcast_testing/node_modules/@angular/cli/models/packages/angular/cli/models/architect-command.ts:242:21)
        at &lt;anonymous&gt;
        at Immediate._tickCallback (internal/process/next_tick.js:189:7)
        at runCallback (timers.js:810:20)
        at tryOnImmediate (timers.js:768:5)
        at processImmediate [as _immediateCallback] (timers.js:745:5)
</code></pre>

<p>Ubuntu Machine Configuration -</p>

<pre><code>Angular CLI: 7.3.7
Node: 8.17.0
OS: linux x64
Angular: 7.2.11
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.11.4
@angular-devkit/build-angular     0.11.4
@angular-devkit/build-optimizer   0.11.4
@angular-devkit/build-webpack     0.11.4
@angular-devkit/core              7.1.4
@angular-devkit/schematics        7.3.7
@angular/cdk                      7.3.6
@angular/cli                      7.3.7
@angular/flex-layout              7.0.0-beta.22
@angular/material                 7.3.6
@ngtools/webpack                  7.1.4
@schematics/angular               7.3.7
@schematics/update                0.13.7
rxjs                              6.4.0
typescript                        3.2.2
webpack                           4.23.1
</code></pre>

<p>Why the same code and same configuration is working fine in MAC and not working in Ubuntu ?</p>
",https://stackoverflow.com/questions/59799226/angular-7-unit-testing-phantomjs-has-crashed,"['phantomjs', 'angular7', 'karma-jasmine', 'angular-test']",470,False,-1,1
Angular Unit Testing Code Coverage for Void: ()=&gt;,"<p>I have a simple ngOnInit() function in my component.ts file with a const variable of type void. By any chance anyone know how to cover that line of code and go inside that void method?</p>
<p>app.component.ts</p>
<pre><code>import { Component, Inject, OnInit } from '@angular/core';
import {DOCUMENT} from '@angular/common'

export type SessionHandler = ()=&gt; void;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {

  title = 'test';

  constructor(@Inject(DOCUMENT) private _document: any){}

  ngOnInit() {
   const sess: SessionHandler = (): void =&gt;{
     console.log('Meoww');
   }
   this.testService.func(sess);
  }
  }
</code></pre>
<p>app.component.spec.ts</p>
<pre><code>import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

fdescribe('AppComponent', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
  }));

  it('should render title', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    component.ngOnInit();
  });
});
</code></pre>
",https://stackoverflow.com/questions/65441099/angular-unit-testing-code-coverage-for-void,"['angular', 'unit-testing']",200,False,-1,1
Unit Testing Angular service file using Jasmine,"<p>I am new to angular and jasmine environment. Facing some issue in jasmine testing when testing my service.ts file</p>
<p><strong>Angular Function in .ts file</strong></p>
<pre><code>getBenchmarkingOptInData(assessmentId: string): Observable&lt;boolean&gt; {
    if (this._benchmarkingOptedIn.value === null) {
      return this.httpClient
        .get&lt;IPbAssessmentMetadata&gt;(
          `/api/metadata`
        )
        .pipe(
          catchError(() =&gt; {
            return of(null);
          }),
          map((response: IPbAssessmentMetadata): boolean =&gt; {
            console.log('response :', response) // `response` is displayed ex: {a:1}
            if (response) {
              this._benchmarkingOptedIn.next(response.consentToContribute);
              return response.consentToContribute;
            }
          })
        );
    } else {
      return of(this._benchmarkingOptedIn.value);
    }
  }
</code></pre>
<p><strong>Unit Test :</strong></p>
<pre><code>
const httpClientSpy = jasmine.createSpyObj&lt;HttpClient&gt;('HttpClient', [
    'get',
    'post',
    'put',
    'delete',
  ]);
....
....
beforeEach(() =&gt; {
let service = new ServiceName()
})
it('should call the getBenchmarkingOptInData create api', () =&gt; {

    const id = '55c0e8ef-dfa4-4c30-bf3a-5f5b1b69a275';

    const assessmentcreationResponse = require('../../../mock/assessments/assessments-api-response.json');

   // `assessmentcreationResponse` contains {a:1}

    httpClientSpy.get.and.returnValue(of(assessmentcreationResponse));
    service.getBenchmarkingOptInData(id).subscribe(res =&gt; {
      expect(httpClientSpy.get).toHaveBeenCalledWith(
        `/api/metadata`
      );
      console.log('RESPONSE : ', res); //HERE I AM GETTING empty response, But I was expecting the data {a:1}  
     
      //expect(res).toBe(assessmentcreationResponse);
    });
});

Is it because of the RxJS operators in between (pipe, map), how to mock ?
</code></pre>
<p>I am Not sure, what I am missing, Please help, and also let me know if you need some more info.</p>
",https://stackoverflow.com/questions/62575096/unit-testing-angular-service-file-using-jasmine,"['angular', 'unit-testing', 'jasmine', 'angular-services']",34,False,0,0
angular element unit testing .valid returns false,"<p>I have the following input element in an angular form</p>
<pre><code>&lt;input type=&quot;text&quot; 
                                    id=&quot;description&quot; name=&quot;description&quot; [value]=&quot;description&quot;
                                    [(ngModel)]=&quot;description&quot; (change)=&quot;update(description)&quot;
                                    #description=&quot;ngModel&quot; maxlength=&quot;100&quot; required/&gt;
</code></pre>
<p>Now my problem is that when in actual development in the <code>update</code> method <code>update(elementRef: any)</code> when I check <code>elementRef.valid</code> it returns true, however in unit testing when I check the same it returns <code>false</code>, I`m not sure what is going wrong here.</p>
<p>On further investigation I found out that if I removed <code>required</code> then it passes the validation on the unit test.</p>
",https://stackoverflow.com/questions/63126976/angular-element-unit-testing-valid-returns-false,"['angular', 'unit-testing']",26,False,0,0
Spock unit testing to test the RestTemplate.postForEntity,"<p>I am new to Spock unit testing framework. I am able to write unit test cases using Spock for simple logics. Now, I am writing the same for a Rest API.</p>

<p>I am using Spring's RestTemplate to hit the GET and POST requests. I have seen number of example in google for GET request(like WireMock). But, there is no enough information to give clarification on how to write test cases for POST requests. </p>

<p>Here is my sample code which is written in Junit. I have to convert the same to Spock (I can do).</p>

<pre><code>import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;

import com.github.tomakehurst.wiremock.junit.WireMockRule;

@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
@ActiveProfiles(value = ""integration"")
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class LocalControllerTest {

  @Rule
  public WireMockRule wireMockRule = new WireMockRule(9999);

  @Before
  public void setUp() {
    mockRemoteService();
  }

  @Test
  public void testLocalServiceWithMockedRemoteService() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity&lt;String&gt; response = restTemplate.getForEntity(""http://localhost:8080/localService"", String.class);
    org.junit.Assert.assertEquals(""Input : request from client endpoint, Message : mocked remote service response"", response.getBody());
  }

  private void mockRemoteService() {
    stubFor(get(urlEqualTo(""/remote""))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader(""Content-Type"", ""application/json"")
            .withBodyFile(""remoteServiceResponse.json"")));
  }

}
</code></pre>

<p>Main issue is, even though I wrote the test cases, the call is actually happening to the service (Which is at my localhost) which I am not expecting to happen it. Is there any way to Mock up the data locally and make the call to dummy endpoint for POST request using Spock framework? I don't know much about to mock a dummy endpoint.</p>

<p>Your help is highly appreciated.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/60819973/spock-unit-testing-to-test-the-resttemplate-postforentity,"['groovy', 'spock']",739,False,0,0
"Unit testing, connection to api in UWP","<p>Hi I have to write unit test to this method: </p>

<pre><code>public static async Task&lt;TradeModel[]&gt; LoadTrades(int limit = 300)
{
    string url = """";

    if (limit &lt;= 300)
    {
        url = $""https://api.bitbay.net/rest/trading/transactions/BTC-PLN?limit={ limit }"";
    }
    else
    {

    }

    using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))//exeption
    {
        if (response.IsSuccessStatusCode)
        {
            TradeItemModel trade = await response.Content.ReadAsAsync&lt;TradeItemModel&gt;();

            return trade.Items;
        }
        else
        {
            throw new Exception(response.ReasonPhrase);
        }
    }
}
</code></pre>

<p>And my unit test:</p>

<pre><code>[TestMethod]
public async Task TestMethod1()
{
    List&lt;int&gt; numbers = new List&lt;int&gt; { 1, 26, 70, 5 };
    List&lt;Type&gt; expected = new List&lt;Type&gt; { typeof(TradeModel[]), typeof(TradeModel[]), typeof(TradeModel[]), typeof(TradeModel[]) };
    List&lt;Type&gt; actual = new List&lt;Type&gt;();

    for(int i= 0; i &lt; 4; i++)
    {
        var trades = await TradeProcessor.LoadTrades(numbers[i]);
        actual.Add(trades.GetType());
    }

    CollectionAssert.AreEqual(expected, actual);
}
</code></pre>

<p>I don't understand why I get an exeption Object reference not set to an instance of an object. What am I doing wrong? How this test should look like?</p>
",https://stackoverflow.com/questions/61755008/unit-testing-connection-to-api-in-uwp,"['c#', 'unit-testing', 'testing', 'uwp']",27,True,0,1
Unit testing a BehaviorSubject in a service,"<p>I'm working on a toy project to learn unit testing in Angular (replaced Karma with Jest). I've seen similar questions but all of them handle subscriptions differently, so I wasn't able to get the exact answer to work for me. </p>

<p>TL;DR: I'm trying to test a BehaviorSubject, but rather than the value I'm expecting, it's sending it's initial value to me. I understand the ordering of the subscription in the test matters, but I couldn't figure the proper ordering yet.</p>

<p>I have a BehaviorSubject in a service: </p>

<pre><code>export class SomeService {
  // ...
  remainingSeconds: number;

  private _seconds: Subject&lt;number&gt; = new BehaviorSubject(RegularTimerSeconds.WORK_TIME);
  public readonly seconds$: Observable&lt;number&gt; = this._seconds.asObservable();

  setTimer(seconds: number) {
    this.remainingSeconds = seconds;
    this._seconds.next(this.remainingSeconds);
  }

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

<p>and a listener on a component, which subscribes to the Observable using the async pipe in the template </p>

<pre><code>export class SomeComponent implements OnInit, OnDestroy {
  // ...
  remainingSeconds$ = this.timer.seconds$.pipe(tap(seconds =&gt; console.log(`remainingSeconds$: ${seconds}`)));

  constructor(public timer: TimerService) {}
}
</code></pre>

<p>Subscription happens in the template as follows</p>

<pre><code>&lt;ng-container *ngIf=""{
  remainingSeconds: remainingSeconds$ | async,
  currentState: currentState$ | async,
  informationText: informationText$ | async,
  doneCounter: doneCounter$ | async
} as data""&gt;
  &lt;!-- ... --&gt;
  &lt;div class=""regular-timer-container"" *ngIf=""data.remainingSeconds !== undefined""&gt;
    &lt;p&gt;Remaining seconds: {{ data.remainingSeconds }}&lt;/p&gt;  
  &lt;/div&gt;
&lt;/ng-container&gt;
</code></pre>

<p>I would like to test that when the <code>setTimer</code> function in the service is called, the remainingSeconds$ observable in the component also gets the correct value. Especially, if the ""remainingSeconds"" value in the service is undefined, I'd like to make sure that the remainingSeconds$ observable gets the updated undefined value, and thus the appropriate UI element is hidden. </p>

<p>The problem I'm having with the test (for which the code is below) is that when I call <code>service.setTimer(undefined)</code> from the component, I'm getting the initial value of the BehaviorSubject rather than the <code>undefined</code> value I wanted (which makes the test useless).</p>

<pre><code>it(`shouldn't render the timer component if the seconds value is unset`, async(() =&gt; {
  component.remainingSeconds$
    .subscribe(
      seconds =&gt; {
        expect(seconds).toEqual(undefined);

        fixture.detectChanges();

        const timerContainerDom: DebugElement = fixture.debugElement;
        const regularTimerComponent = timerContainerDom.query(By.directive(AppComponent));

        expect(regularTimerComponent).toBeFalsy();
      }
    );

  timerService.setTimer(undefined);
}));
</code></pre>

<p>I'm adding <a href=""https://stackblitz.com/edit/angular-ivy-5wvhcv"" rel=""nofollow noreferrer"">a stackblitz link</a>, but sadly I couldn't run npm test on there. Hopefully it'll give some basic idea as to what I'm trying to accomplish.</p>
",https://stackoverflow.com/questions/61954961/unit-testing-a-behaviorsubject-in-a-service,"['angular', 'unit-testing', 'rxjs']",6618,True,0,2
undefined reference to `vtable [CMakeLists.txt] (Unit Testing),"<p>I'm getting several errors when conducting my unit test. My goal is to see if my make->shipCost() will be equal to the expected.</p>

<pre><code>TEST(FactoryTestSet, USNShipCost) {
    USN_Fleet_Factory* makeAShip; 
    USN_Ship *make; 
    makeAShip = new USN_Ship_Factory;
    make = makeAShip-&gt;CreateAircraftCarrier(""Aircraft Carrier"");
    EXPECT_EQ(make-&gt;shipCost(), 8); 
    make = makeAShip-&gt;CreateCruiser(""Cruiser"");
    EXPECT_EQ(make-&gt;shipCost(), 5); 
    make = makeAShip-&gt;CreateDestroyer(""Destroyer"");
    EXPECT_EQ(make-&gt;shipCost(), 3); 
    make = makeAShip-&gt;CreateFrigate(""Frigate"");
    EXPECT_EQ(make-&gt;shipCost(), 2); 
}

TEST(FactoryTestSet, PLANShipCost) {
    PLAN_Fleet_Factory* makeAVessel; 
    PLAN_Ship *assemble; 
    makeAVessel = new PLAN_Ship_Factory;
    assemble = makeAVessel-&gt;CreateAircraftCarrier(""Aircraft Carrier"");
    EXPECT_EQ(assemble-&gt;shipCost(), 8); 
    assemble = makeAVessel-&gt;CreateCruiser(""Cruiser"");
    EXPECT_EQ(assemble-&gt;shipCost(), 4); 
    assemble = makeAVessel-&gt;CreateDestroyer(""Destroyer"");
    EXPECT_EQ(assemble-&gt;shipCost(), 3);
    assemble = makeAVessel-&gt;CreateFrigate(""Frigate"");
    EXPECT_EQ(assemble-&gt;shipCost(), 1);
}
</code></pre>

<p>Example of what one of my base subclasses looks like:</p>

<pre><code>class GF_Class_Aircraft_Carrier : public USN_Ship{
private:
    int shipPrice = 8;
    int PI = 10;
public:
    void accept(Visitor &amp;v); 
    virtual void ShipName() {std::cout &lt;&lt; ""- USS Gerald R. Ford\n"";}
    virtual void shipHullNumber() {std::cout &lt;&lt; ""- CVN-75\n"";}
    void shipClassName() {std::cout &lt;&lt; ""- Gerald Ford Class Aircraft Carrier\n"";}
    void shipType() {std::cout &lt;&lt; ""- Aircraft Carrier\n"";}
    void arament() {std::cout &lt;&lt; ""- 40 F-35 Lightning's, 10 E-8 Growler Hornet's, 8 SH-60 Seahawk's\n"";}
    int shipCost() {std::cout &lt;&lt; ""- Ship Cost:$"" &lt;&lt; shipPrice &lt;&lt; "" billion\n""; return shipPrice;}
    int powerIndex() {return PI;}
    virtual void assignHomePort() {std::cout &lt;&lt; ""- Home Port:  \n"";}
    virtual void assignAdmiral() {std::cout &lt;&lt; ""- Commanding Officer:  \n"";}

};
</code></pre>
",https://stackoverflow.com/questions/62289707/undefined-reference-to-vtable-cmakelists-txt-unit-testing,"['c++', 'unit-testing']",75,False,0,0
Skipping or Mocking SecurityUtils during Unit testing,"<p>I have a REST endpoint that uses the <code>SecurityUtil.getCurrentUserLogin().get();</code> method.</p>

<p>I'm building unit tests for this endpoint, and would like to skip over the <code>SecurityUtil.getCurrentUserLogin()</code> method, but when I Mock or Spy the class, it throws an error because it's final.</p>

<p>My only other thought is to figure out how to force it to return a value. But I'm having trouble structuring that properly. Something along the lines of <code>when(SecurityUtils.getCurrentUserLogin().get()).thenReturn(PresetUserLogin);</code></p>

<p>I'd appreciate any suggestions. Thanks!</p>
",https://stackoverflow.com/questions/60818501/skipping-or-mocking-securityutils-during-unit-testing,"['spring-mvc', 'junit', 'spring-security', 'mockito', 'spy']",478,False,0,1
Unit testing in BASH (checking script output),"<p>How to automate checking of the script output in BASH? 
For example if I wanted student to write a command and then check if the ouput of the command is what my predefined command is set to produce.
Br, mika</p>
",https://stackoverflow.com/questions/61955681/unit-testing-in-bash-checking-script-output,"['bash', 'unit-testing']",380,False,0,1
Mocking Android Snackbar for Mockk Unit Testing,"<p>I want to to mock the Snackbar class, but the initialization code below keeps throwing errors.</p>
<pre class=""lang-kotlin prettyprint-override""><code>    @MockK
    lateinit var snackbar: Snackbar
</code></pre>
<p>It looks like the mock initalizer has to access BaseTransientBottomBar's static method, which calls Android.os.Looper.getMainLooper(). Here is the error log:</p>
<pre><code>java.lang.ExceptionInInitializerError
    at sun.reflect.GeneratedSerializationConstructorAccessor4.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
    at io.mockk.proxy.jvm.ObjenesisInstantiator.instanceViaObjenesis(ObjenesisInstantiator.kt:75)
    at io.mockk.proxy.jvm.ObjenesisInstantiator.instance(ObjenesisInstantiator.kt:42)
    at io.mockk.proxy.jvm.ProxyMaker.instantiate(ProxyMaker.kt:75)
    at io.mockk.proxy.jvm.ProxyMaker.proxy(ProxyMaker.kt:42)
    at io.mockk.impl.instantiation.JvmMockFactory.newProxy(JvmMockFactory.kt:34)
    at io.mockk.impl.instantiation.AbstractMockFactory.newProxy$default(AbstractMockFactory.kt:29)
    at io.mockk.impl.instantiation.AbstractMockFactory.mockk(AbstractMockFactory.kt:59)
    at io.mockk.impl.annotations.JvmMockInitializer.assignMockK(JvmMockInitializer.kt:145)
    at io.mockk.impl.annotations.JvmMockInitializer.initMock(JvmMockInitializer.kt:39)
    at io.mockk.impl.annotations.JvmMockInitializer.initAnnotatedMocks(JvmMockInitializer.kt:22)
    at com.example.MyTest.&lt;init&gt;(MyTest.kt:155)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
    at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.os.Looper.getMainLooper(Looper.java)
    at com.google.android.material.snackbar.BaseTransientBottomBar.&lt;clinit&gt;(BaseTransientBottomBar.java:185)
    ... 35 more
</code></pre>
<p>Does anyone know how to solve this problem? Thank you in advance.</p>
",https://stackoverflow.com/questions/63315993/mocking-android-snackbar-for-mockk-unit-testing,"['android', 'unit-testing', 'kotlin', 'mockk']",523,False,0,1
object is possibly undefined angular unit testing,"<p>I was working on unit testing I am getting below error</p>
<blockquote>
<p>Object is possibly 'undefined'</p>
</blockquote>
<pre><code> it('should set the dataSource filter to the provided argument', () =&gt; {
  component.applyFilter('filterValue');
   expect(this.dataSource.filter).toEqual('filterValue');
  })

it('should set the dataSource filter to the provided argument', () =&gt; {
   component.applyFilter('filterValue');
   expect(this.DMDataSource.filter).toEqual('filterValue');
 })
</code></pre>
<p>I am getting error inside expect(this) what is the mistake here.</p>
<p>Please let me know.</p>
",https://stackoverflow.com/questions/63970068/object-is-possibly-undefined-angular-unit-testing,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",900,True,-1,1
How to begin unit testing using phpstorm,"<p>so firstly, I am very new to coding. This question pertains to unit testing using php. Should be obvious, I know, but my question is, in order to actually use the unit tests i will eventually create, will I have to also make up some code apply the tests? All of the tutorials explain how to configure the IDE i am using (phpstorm) but do not give any sample code to actually perform the tests. Is there a feature built into phpstorm which allows you to try the unit tests you create? If i do in fact require sample code, what kind of code should i use and where could i get it from? Any help is appreciated, thank you.</p>
",https://stackoverflow.com/questions/60767529/how-to-begin-unit-testing-using-phpstorm,"['php', 'unit-testing']",66,True,0,1
Unit testing CanDeactiveGuard and ModalDialogService behind it,"<p>I've got a <code>CanDeactiveGuard</code> that's working just fine. I'm writing unit tests and they're working except for one where I want to <code>callThrough</code> and launch the Modal Dialog component that prompts the user to save. The <code>openConfirmDialog()</code> method is in the Guard but it calls a service to launch the modal. The service is the code I want executed.</p>
<p>So, there's the Guard class and the <code>ModalDialogService</code> that is responsible for launching the modal. Is it realistic to execute the code in <code>ModalDialogService</code> from a method in the Guard? Or should I be testing the service separately?</p>
<p>Here's the guard spec file:</p>
<pre><code>class MockGuardComponent implements ComponentCanDeactivate {
  // Set this value to the value you want to mock being returned from 
GuardedComponent
  returnValue: boolean | Observable&lt;boolean&gt;;

  canDeactivate(): boolean | Observable&lt;boolean&gt; {
    return this.returnValue;
  }
}

describe('PendingChangesGuard', () =&gt; {
  let mockGuardComponent: MockGuardComponent;
  let service: PendingChangesGuard;
  let dialogService: ModalDialogService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ModalDialogComponent],
      providers: [
        PendingChangesGuard,
        MockGuardComponent,
        Overlay,
        ModalDialogService,
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [ModalDialogComponent],
      },
    });
    service = TestBed.get(PendingChangesGuard);
    dialogService = TestBed.get(ModalDialogService);
    mockGuardComponent = TestBed.get(MockGuardComponent);
  });

  it('should expect service to instantiate', () =&gt; {
    expect(service).toBeTruthy();
  });

  it('can route if unguarded -- form is not dirty', () =&gt; {
    mockGuardComponent.returnValue = true;
    expect(service.canDeactivate(mockGuardComponent)).toBeTruthy();
  });

  it('cannot route if guarded -- form is dirty', () =&gt; {
// *** Here is where I'm trying to execute the openConfirmDialog() 
method that creates a modal
    spyOn(service, 'openConfirmDialog').and.callThrough();
    mockGuardComponent.returnValue = false;
    expect(service.canDeactivate(mockGuardComponent)).toBeFalsy();
    expect(service.openConfirmDialog).toHaveBeenCalled();
  });

  it('will route if guarded and user accepted the dialog and 
confirmed', () =&gt; {
    // Mock the behavior of the Component
    const subject$ = new Subject&lt;boolean&gt;();
    mockGuardComponent.returnValue = subject$.asObservable();
    const canDeactivate$ = &lt;Observable&lt;boolean&gt;&gt;(
      service.canDeactivate(mockGuardComponent)
    );
    canDeactivate$.subscribe((deactivate) =&gt; {
      // This is the real test
      expect(deactivate).toBeTruthy();
    });
    // Emulate the accept action
    subject$.next(true);
  });

  it('will not route if guarded and user rejected the dialog', () =&gt; {
    // Mock the behavior of the MockGuardedComponent
    const subject$ = new Subject&lt;boolean&gt;();
    mockGuardComponent.returnValue = subject$.asObservable();
    const canDeactivate$ = &lt;Observable&lt;boolean&gt;&gt;(
      service.canDeactivate(mockGuardComponent)
    );
    canDeactivate$.subscribe((deactivate) =&gt; {
      // this is the real test
      expect(deactivate).toBeFalsy();
    });
    // Emulate the reject
    subject$.next(false);
  });
});
</code></pre>
<p>So, you can see it's the 2nd test where I'm trying to call right through the <em>openConfirmDialog()</em> method and have it launch the modal.</p>
<p>And here's the <em>ModalDialogService</em> class:</p>
<pre><code>export class ModalDialogService {
  constructor(
    @Inject(DOCUMENT) private readonly document: Document,
    private readonly viewportRuler: ViewportRuler,
    private readonly injector: Injector,
    private readonly overlay: Overlay
  ) {}

  public open&lt;T, D&gt;(
    component: ComponentType&lt;T&gt;,
    config: ModalDialogConfig&lt;D&gt; = {}
  ): ModalDialogRef&lt;T&gt; {
    // Override default configuration
    const dialogConfig = { ...DEFAULT_CONFIG, ...config };

    // Returns an OverlayRef which is a PortalHost
    const overlayRef = this.createOverlay(dialogConfig);

    // Instantiate remote control
    const dialogRef = new ModalDialogRef&lt;T&gt;(overlayRef);
    dialogRef.instance = this.attachDialogContainer(
      component,
      overlayRef,
      dialogConfig,
      dialogRef
    );

    if (dialogConfig.hasBackdrop &amp;&amp; dialogConfig.closeOnBackdropClick) 
    {
      overlayRef.backdropClick().subscribe(() =&gt; dialogRef.close());
    }

    return dialogRef;
  }

  private createOverlay(config: ModalDialogConfig): OverlayRef {
     const overlayConfig = this.getOverlayConfig(config);
    return this.overlay.create(overlayConfig);
  }

  private attachDialogContainer&lt;T&gt;(
    component: ComponentType&lt;T&gt;,
    overlayRef: OverlayRef,
    config: ModalDialogConfig,
    dialogRef: ModalDialogRef&lt;T&gt;
  ): T {
    const injector = this.createInjector(config, dialogRef);
    const containerPortal = new ComponentPortal(component, undefined, 
injector);
    const containerRef: ComponentRef&lt;T&gt; = 
overlayRef.attach(containerPortal);

    return containerRef.instance;
  }

  private createInjector&lt;T, D&gt;(
    config: ModalDialogConfig&lt;D&gt;,
    dialogRef: ModalDialogRef&lt;T&gt;
  ): PortalInjector {
    const injectionTokens = new WeakMap();
    injectionTokens.set(ModalDialogRef, dialogRef);
    injectionTokens.set(MODAL_DIALOG_DATA, config.data || null);

    return new PortalInjector(this.injector, injectionTokens);
  }

  private getOverlayConfig(config: ModalDialogConfig): OverlayConfig {
    const positionStrategy = this.overlay
      .position()
      .global()
      .centerHorizontally()
      .centerVertically();

    const overlayConfig = new OverlayConfig({
      hasBackdrop: config.hasBackdrop,
      backdropClass: config.backdropClass,
      panelClass: config.panelClass,
      disposeOnNavigation: config.closeOnNavigation,
      scrollStrategy: this.overlay.scrollStrategies.block(),
      positionStrategy,
    });

    return overlayConfig;
  }
}
</code></pre>
<p>Since the <code>openConfirmDialog()</code> method isn't actually executing the code in the <code>ModalDialogService</code> then I must have to test that separately, correct? And, if that's the case, do I need to mock all the objects I need to create a dialog, i.e. <code>OverlayRef, ModalDialogConfig, ModalDialogRef</code>?</p>
",https://stackoverflow.com/questions/62204032/unit-testing-candeactiveguard-and-modaldialogservice-behind-it,"['angular', 'typescript']",495,True,0,2
Unit testing a viewController with constructor dependency,"<p>I want to write a simple unit test for the viewController described below that has constructor dependency. Unfortunately one of the parameters is of type NSCoder. How do I create the NSCoder argument while testing? As I get this error message.</p>

<p>caught ""NSInvalidArgumentException"", ""*** -decodeObjectForKey: only defined for abstract class.  Define -[NSKeyedArchiver decodeObjectForKey:]!""</p>

<p>online research: <a href=""https://stackoverflow.com/questions/32500193/how-to-test-required-initcoder"">deprecated solution stackoverflow</a></p>

<p>ViewModel</p>

<pre><code>class ViewModel  {
  private let response: DataResponse
  private var name = ""Character name""

  init(reponse: Result) {
      self.reponse = response
  }

  var fullName: String {
    return name
  }

  fund getData() {
     if self.result.name.count &gt; 0 {
         self.name = self.result.name
     }
  }

}
</code></pre>

<p>ViewController</p>

<pre><code>class ViewController: UIViewController {
  @IBOutlet weak var name: UILabel!

  private var viewModel: ViewModel

  init?(viewModel: ViewModel, coder: NSCoder) {
      self.viewModel = viewModel
      super.init(coder: coder)
  }

  required init(coder: NSCoder) {
      fatalError(""init(coder:) has not been implemented"")
  }

  override func viewDidLoad() {
      super.viewDidLoad()
      viewModel.getData()
      characterNameLabel.text = viewModel.fullName
  }
}
</code></pre>

<p>The method that shows viewController</p>

<pre><code>@IBSegueAction func showViewController(coder: NSCoder) -&gt; 
ViewController? {

    guard let selectedRow = tableView.indexPathForSelectedRow?.row else {
      return nil
    }
    let singleResult = specialViewModel.results(at: selectedRow)
    let viewModel = ViewModel(result: singleResult)
    return ViewController(viewModel: viewModel, coder: coder)

}
</code></pre>

<p>Testcase snippet</p>

<pre><code>class ViewControllerTest: XCTestCase {
  var viewControllerUnderTest: ViewController!
  var viewModel: ViewModel!

  override func setUp() {
      super.setUp()
      let data = PagedResponse.stub().data.results[0]
      self.viewModel = ViewModel(result: data)
      self.viewModel.getData()
      let coder = ""??"" // how do I create coder
      self.viewControllerUnderTest = ViewControllerUnderTest(viewModel: viewModel, coder: coder)
      self.viewControllerUnderTest.loadView()
      self.viewControllerUnderTest.viewDidLoad()
  }

  override func tearDown() {
      super.tearDown()
  }
}
</code></pre>
",https://stackoverflow.com/questions/61952405/unit-testing-a-viewcontroller-with-constructor-dependency,"['swift', 'swift5', 'ios13.2']",298,False,0,0
Firebase sinon / chai unit testing in nodeJS,"<p>Trying to get offline unit testing working for my Firebase project.  I can't seem to figure out why the following test isn't running and logging console.log('b') &amp; ('c').  I assume I've stubbed it incorrectly but can't figure it out.  By the test output and console.log it only returns 'a' and then also returns true.</p>

<p>Help appreciated.</p>

<pre><code>index.js

function createFreeAgents(admin) {
    admin.database().ref('/CONFIG').update({ 
        ""agencyActive"" : false,
        ""listCount"" : true
    });
    **console.log('a')**
    admin.database().ref('/FREEAGENTPICK').once('value', snap =&gt; {
        **console.log('b')**
        snap.forEach(team =&gt; {
            **console.log('c')**
            let newAgentObject = {
                ""rookie"": 2,
                ""senior"": 4,
            }

            admin.database().ref('/FREEAGENTPICK/' + team.key).update(newAgentObject);
        })
    })

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

<pre><code>const chai = require('chai');
const expect = chai.expect;
const assert = chai.assert;

const sinon = require('sinon');
const admin = require('firebase-admin');
const test = require('firebase-functions-test')();
const functions = require('../index');

describe('it should update a players score', () =&gt; {
    let adminInitStub, adminDatabaseStub;

    beforeEach(() =&gt; {            
        adminInitStub = sinon.stub(admin, 'initializeApp');
        adminDatabaseStub = sinon.stub(admin, 'database');
    });

    afterEach(() =&gt; {
        adminInitStub.restore();
        test.cleanup();
    });

    describe('run createFreeAgent()', () =&gt; {  
        it('should run createFreeAgents() and return true', () =&gt; {  
            // Stubs
            databaseStub = sinon.stub();
            refStub = sinon.stub();
            updateStub = sinon.stub();

            // Values
            configUpdate = { 
                ""agencyActive"" : false,
                ""listCount"" : true
            };

            // DBMocks
            adminDatabaseStub = Object.defineProperty(admin, 'database', { get: () =&gt; databaseStub });
            databaseStub.returns({ ref: refStub }); 

            refStub
                .withArgs('/CONFIG')
                .onFirstCall()
                .returns({ update: updateStub })
                .withArgs('/FREEAGENTPICK')
                .onFirstCall()
                .returns({ once: updateStub })

            updateStub
                .onFirstCall()
                .returns(configUpdate)
                .onSecondCall()
                .returns(snapFreeAgent)

            assert.deepEqual(updateStub('/CONFIG'), configUpdate);

            result = functions.createFreeAgents(adminDatabaseStub);
            expect(result).to.equal(true);

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

<pre><code>test output

  it should update a players score
    run createFreeAgent()
a
      √ should run createFreeAgents() and return true


  1 passing (13ms)

</code></pre>
",https://stackoverflow.com/questions/62481203/firebase-sinon-chai-unit-testing-in-nodejs,"['firebase', 'unit-testing', 'firebase-realtime-database', 'chai', 'sinon']",96,False,0,1
NativeScript - unit testing an HttpInterceptor NSLocationStrategy error,"<p>I'm writing an app with NativeScript 6.4.1 and Angular 8.</p>

<p>I want to write unit tests for my HttpInterceptor. My interceptor adds on a token to select http calls and routes users to an authentication page if they get certain errors from the backend.</p>

<p>The code runs fine and it works but my unit test does not.</p>

<p>When I run my unit test, I get this error:</p>

<pre><code>NullInjectorError: StaticInjectorError(DynamicTestModule)[RouterExtensions -&gt; NSLocationStrategy]:
  StaticInjectorError(Platform: core)[RouterExtensions -&gt; NSLocationStrategy]:
    NullInjectorError: No provider for NSLocationStrategy!
error properties: Object({ originalStack: 'Error: NullInjectorError: No provider for NSLocationStrategy!
    at new ZoneAwareError (file:///data/data/org.nativescript.SelfServiceApp/files/app/vendor.js:157861:33)
</code></pre>

<p>I don't know why I am getting the error.</p>

<p>Here is my unit test:</p>

<pre><code>import { nsTestBedBeforeEach } from 'nativescript-angular/testing';
import { TestBed } from '@angular/core/testing';
import { HttpInterceptorService } from '~/app/core/interceptors/http-interceptor-service';
import { HttpLoaderService } from '~/app/core/shared/http-loader.service';
import { AuthenticationService } from '~/app/authentication/shared/services/authentication.service';
import { SsoAuthenticationService } from '~/app/authentication/pages/single-sign-on/sso-authentication.service';
import { EndpointHelperService } from '~/app/core/shared/endpoint-helper.service';
import { RouterExtensions } from 'nativescript-angular/router';

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NativeScriptRouterModule } from 'nativescript-angular/router';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule, Location } from '@angular/common';

describe('HttpInterceptorService Test', () =&gt; {

    let service: HttpInterceptorService;

    beforeEach(nsTestBedBeforeEach([], [
        HttpInterceptorService,
        HttpLoaderService,
        AuthenticationService,
        SsoAuthenticationService,
        EndpointHelperService,
        RouterExtensions
    ], [
        HttpClientTestingModule, 
        RouterTestingModule, 
        NativeScriptRouterModule, 
        CommonModule
    ]));

    it('should be defined', () =&gt; {
        service = TestBed.get(HttpInterceptorService);
        expect(service).toBeTruthy();
    });
});
</code></pre>

<p>Here is my interceptor:</p>

<pre><code>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError, from } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { HttpLoaderService } from '../shared/http-loader.service';
import { boundMethod } from 'autobind-decorator';
import { AuthenticationService } from '../../authentication/shared/services/authentication.service';
import { SsoAuthenticationService } from '../../authentication/pages/single-sign-on/sso-authentication.service';
import { EndpointHelperService } from '../shared/endpoint-helper.service';
import { switchMap } from 'rxjs/operators';
import { RouterExtensions } from 'nativescript-angular/router';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

    constructor(
        private httpLoaderService: HttpLoaderService,
        private authentication: AuthenticationService,
        private ssoAuthentication: SsoAuthenticationService,
        private endpointHelper: EndpointHelperService,
        private router: RouterExtensions
    ) {}

    public intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {

        this.httpLoaderService.onRequestStart();

        // do not add to token endpoints
        if (this.endpointHelper.isTokenEndpoint(request.url)) {
            return this.returnRequest(request, next);
        }

        //do not add to registration server
        if (this.endpointHelper.isRegisterEndpoint(request.url)) {
            return this.returnRequest(request, next);
        }

        return this.appendSSOTokenToHeader(request, next);
    }

    @boundMethod
    private appendSSOTokenToHeader(request: HttpRequest&lt;any&gt;, next: HttpHandler) {

        return from(this.ssoAuthentication.getHttpHeader())
            .pipe(
                switchMap((newHeader) =&gt; {

                    request = request.clone({ 
                        body: { ...request.body, clientcode: this.authentication.clientcode },
                        setHeaders: { Authorization: newHeader },
                        url: this.authentication.mobileApiUrl + request.url
                    });

                    return this.returnRequest(request, next);
                })
            );
    }

    @boundMethod
    private returnRequest(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
        return next
            .handle(request)
            .pipe(tap(this.handleSuccess), catchError(this.handleError));
    }

    @boundMethod
    private handleSuccess(event: HttpEvent&lt;any&gt;): void {
        if (event instanceof HttpResponse) {
            this.httpLoaderService.onRequestEnd();
        }
    }

    @boundMethod
    private handleError(error: HttpErrorResponse) {

        this.httpLoaderService.onRequestEnd();

        if (this.endpointHelper.shouldRedirectToSSOPage(error)) {
            this.router.navigate(['register-via-sso']);
        }

        return throwError(error);
    }

}
</code></pre>
",https://stackoverflow.com/questions/60832757/nativescript-unit-testing-an-httpinterceptor-nslocationstrategy-error,"['angular', 'unit-testing', 'http', 'nativescript', 'angular-http-interceptors']",111,True,0,1
Check mobile connection with Runtime Unit testing,"<p>I am trying to build an unit test for this method </p>

<pre><code>public static boolean isOnline(){
    final String command = ""ping -c 1 google.com"";
    boolean isConnected = false;
    try {
        isConnected = Runtime.getRuntime().exec(command).waitFor() == 0;
    } catch (InterruptedException | IOException e) {
        e.printStackTrace();
    }
    return isConnected;
}
</code></pre>

<p>but I'm totally stuck with this problem. I tried to this with PowerMockito like that</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class TestConnection {

   @Mock
   private Runtime mockRuntime;

   @Mock
   private  Process process;

   @Test
   public void test() throws InterruptedException {

       String command = ""ping -c 1 google.com"";

       boolean isConnected = false;

       PowerMockito.mockStatic(Runtime.class);

       try {
           process = mockRuntime.exec(""ping -c 1 google.com"");
       } catch (IOException e) {
           e.printStackTrace();
       }
       when(process.waitFor()).thenReturn(0);

       if (process.waitFor() == 0){
           isConnected = true;
       }
       Assert.assertThat(isConnected, CoreMatchers.is(Utils.isOnline()));
       // do the rest of your test
   }
}
</code></pre>

<p>it's my first time with mockito and powerMokito and I don't know where I did Wrong</p>
",https://stackoverflow.com/questions/59740800/check-mobile-connection-with-runtime-unit-testing,"['java', 'android', 'unit-testing', 'testing', 'runtime']",76,False,0,0
Xcode - Unit Testing UIColor from asset catalog,"<p>I wrote an extension for my Theme class that returns my mainColor based on my current theme. My unit tests cover theme changes but I still have problem with UIColor optional value. I can't cover the situation that UIColor could not able returns my specific color from my color catalog.  </p>

<pre><code>extension Theme {
var mainColor: UIColor {
    switch self {
        case .system:
          if let color = UIColor(named: ""MainColor"") {
             return color
          } else {
             return .clear
          }
        case .custom:
             return .yellow
      }
   }
}
</code></pre>

<p>I also used this line instead of unwrapping the optional but it didn't work too.</p>

<pre><code>return UIColor(named: ""MainColor"") ?? .clear
</code></pre>

<p>How I unit test that the correct color is retrieved from the asset catalog?</p>
",https://stackoverflow.com/questions/59918752/xcode-unit-testing-uicolor-from-asset-catalog,"['swift', 'xcode', 'unit-testing']",810,True,0,2
Unit Testing Service Layer in Spring Boot,"<p>I have a service layer (Code Below:)</p>

<pre><code>@Service
public class EquityFeedsService {

    @Autowired
    private EquityFeedsRedisRepositoryImpl equityFeedsRedisRepositoryImpl;

    public void save(EquityFeeds equityFeeds) {

        logger.info(""Inside the save method of EquityFeedsService."");

        equityFeedsRedisRepositoryImpl.save(equityFeeds);
    }

   // other methods 
}
</code></pre>

<p>Now I am trying to write a Unit Test case for the above method below: </p>

<pre><code>@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public class EquityFeedsServiceTest {

    private MockMvc mockMvc;

    @InjectMocks
    private EquityFeedsService equityFeedsService;

    @Mock
    private EquityFeedsRedisRepositoryImpl equityFeedsRedisRepositoryImpl;

    @BeforeEach
    public void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(equityFeedsService).build();
    }

    @Test
    public void testSaveMethod() {
        EquityFeeds equityFeeds = new EquityFeeds(423,""SAPEXTXN1"", ""GS"");

        when(equityFeedsRedisRepositoryImpl.save(any(EquityFeeds.class))).thenReturn(new EquityFeeds());


    }
}
</code></pre>

<p>This code gives me the below Exception: 
in line (any(EquityFeeds.class))</p>

<pre><code>Required type:
EquityFeeds (This is my model class) 

Provided:
Matcher &lt;com.investmentbank.equityfeedsprocessingupdated.model.EquityFeeds&gt; (This is the fully qualified path name of the mode class) 
no instance(s) of type variable(s) T exist so that Matcher&lt;T&gt; conforms to EquityFeeds
</code></pre>

<p>and Exception : </p>

<pre><code>Cannot resolve method 'thenReturn(com.investmentbank.equityfeedsprocessingupdated.model.EquityFeeds)'     
</code></pre>

<p>What is wrong with my Unit Test Case? How do i solve this?</p>
",https://stackoverflow.com/questions/61257146/unit-testing-service-layer-in-spring-boot,"['unit-testing', 'mockito', 'junit5', 'spring-boot-test', 'domain-service-class']",61,False,0,0
Unit Testing Node JS API using Jest,"<p>I'm trying to write unit test cases for NodeJS API by mocking the DB call using <code>jest.fn(() =&gt; Promise.resolve([""FAQ 1""]));</code> </p>

<p><strong>My API factory file is something like this:</strong></p>

<pre><code>const getFAQ=(request,reply)=&gt;{

faqs.findByCondition(request.params.filter,success=&gt;{
    reply(Response.sendResponse(true, success, ResponseMessages.SUCCESS, StatusCodes.OK));
 }, error =&gt; {
    log.error('ERROR : ', error);
         reply(Response.sendResponse(false, error, ResponseMessages.ERROR, 400));
    });

};
</code></pre>

<p><strong>My Model JS containing <code>findByCondition()</code> is something like this:</strong></p>

<pre><code>findByCondition = (condition, success_callback, error_callback) =&gt; {
        ""use strict"";
        faq.find(condition, (err, docs) =&gt; {
            if (err) {
                error_callback(err);
            } else {
                success_callback(docs);
            }
        });
    }
</code></pre>

<p><strong>I've tried writing my unit test case as follows:</strong></p>

<pre><code>describe(""test cases for FAQ Factory"", () =&gt; {
    utils.callAPI = jest.fn(() =&gt; 'test')

    test('getFAQ Success Case', (done) =&gt; {
        const request = {
            params: {
                filter: 'all'
            },
            headers: {
                authorization: 'asfasfasdfas'
            }
        }
        faqModel.findByCondition = jest.fn(() =&gt; Promise.resolve([""FAQ 1""]));
        faqFactory.getFAQ(request, (result) =&gt; {
            expect(result).toBeDefined();
            expect(result.status_code).toBe(200);
        })
    })
});
</code></pre>

<p>I'm able to run the test case successfully but the code coverage is not covering the success or error callbacks</p>

<p><strong>but the same test case works if I change my API Factory to something like this:</strong></p>

<pre><code>const getFAQ = (request, reply) =&gt; {
  faqs.findByCondition(request.params.filter).then(success =&gt; {
    reply(Response.sendResponse(true, success, ResponseMessages.SUCCESS, StatusCodes.OK));
  }).catch(error =&gt; {

    log.error('ERROR : ', error);
    reply(Response.sendResponse(false, error, ResponseMessages.ERROR, 400));
  });
};

</code></pre>

<p>Is there any way that I could write my test case so that it will cover the success/error callbacks?</p>
",https://stackoverflow.com/questions/60448802/unit-testing-node-js-api-using-jest,"['javascript', 'node.js', 'unit-testing', 'jestjs']",599,True,0,2
Unit testing vue components with Jest issue,"<p>I'm struggling trying to unit test some components in an app and I would really apreciate if someone could help me.
I've already set up the Jest enviroment for testing in Vue and things work just fine until I try to test a component that rely on other modules with functions in it. These functions are helpers useful for importing vuex actions and getters quicker in the components. Here there are some lines of code that I hope could help with the problem:</p>
<ul>
<li>this is the error that Jest throws in the console:</li>
</ul>
<pre><code>/app # yarn test:unit /common / page - header / ProjectWizard.spec.js
yarn run v1 .22 .5
$ jest / common / page - header / ProjectWizard.spec.js
FAIL src / specs / common / page - header / projectWizard.spec.js
● Test suite failed to run

Configuration error:

  Could not locate module @ / state / helpers mapped as:
  /app/$1.

Please check your configuration
for these entries: {
  &quot;moduleNameMapper&quot;: {
    &quot;/^@\/(.*)$/&quot;: &quot;/app/$1&quot;
  },
  &quot;resolver&quot;: undefined
}

57 |
  import VueGoogleAutocomplete from '../../../node_modules/vue-google-autocomplete'
58 |
  &gt; 59 |
  import {
    |
    ^
    60 | contractTypesMethods,
    61 | contractTypesGetters,
    62 | installationTypesMethods,

    at createNoMappedModuleFoundError(node_modules / jest - resolve / build / index.js: 551: 17)
    at src / components / builder / ProjectWizard.vue: 59: 1
    at Object. &lt; anonymous &gt; (src / components / builder / ProjectWizard.vue: 491: 3)
</code></pre>
<ul>
<li>this is the ProjectWizard file:</li>
</ul>
<pre><code>&lt;template&gt;
  &lt;form-wizard
    @on-complete=&quot;onComplete(model)&quot;
    error-color=&quot;#f1b44c&quot;
    color=&quot;#EC641C&quot;
    nextButtonText=&quot;Avanti&quot;
    backButtonText=&quot;Indietro&quot;
    :finishButtonText=&quot;(isModifying) ? 'Conferma modifiche' : 'Crea Progetto'&quot;
    id=&quot;project-form-wizard&quot;
    style=&quot;overflow: hidden;&quot;
  &gt;

    &lt;tab-content title=&quot;Informazioni preliminari&quot; icon=&quot;mdi mdi-folder-information&quot; :before-change=&quot;validateFirstTab&quot;&gt;

      &lt;vue-form-generator-component :model=&quot;model&quot; :schema=&quot;zeroTabSchema&quot; :options=&quot;formOptions&quot; ref=&quot;zeroTabSchema&quot;&gt;
      &lt;/vue-form-generator-component&gt;

      &lt;b-form-group featured class=&quot;col-12&quot; label=&quot;Indirizzo (Via etc.)&quot; label-for=&quot;indirizzo-progetto&quot;&gt;
        &lt;vue-google-autocomplete required keypress types=&quot;&quot; ref=&quot;address&quot; id=&quot;indirizzo-progetto&quot;
          classname=&quot;form-control&quot; placeholder=&quot;Inserisci qui l'indirizzo del progetto&quot;
          v-on:placechanged=&quot;getAddressData&quot; country=&quot;it&quot;&gt;
        &lt;/vue-google-autocomplete&gt;
      &lt;/b-form-group&gt;

      &lt;vue-form-generator-component :model=&quot;model&quot; :schema=&quot;firstTabSchema&quot; :options=&quot;formOptions&quot; ref=&quot;firstTabForm&quot;&gt;
      &lt;/vue-form-generator-component&gt;

    &lt;/tab-content&gt;
    &lt;tab-content 
      title=&quot;Dettagli progetto&quot;
      icon=&quot;mdi mdi-home-search-outline&quot; 
      :before-change=&quot;validateSecondTab&quot;
    &gt;

      &lt;vue-form-generator-component
        :model=&quot;model&quot; 
        :schema=&quot;secondTabSchema&quot;
        :options=&quot;formOptions&quot; 
        ref=&quot;secondTabForm&quot;
      &gt;&lt;/vue-form-generator-component&gt;

    &lt;/tab-content&gt;
  &lt;/form-wizard&gt;
&lt;/template&gt;

&lt;script&gt;
import {
  FormWizard,
  TabContent
} from &quot;vue-form-wizard&quot;;

import VueFormGenerator from 'vue-form-generator'
import {
  resources
} from &quot;../../../src/utils/validation&quot;
Object.assign(VueFormGenerator.validators.resources, resources)
import VueGoogleAutocomplete from '../../../node_modules/vue-google-autocomplete'

import {
  contractTypesMethods,
  contractTypesGetters,
  installationTypesMethods,
  installationTypesGetters,
  interventionTypesMethods,
  interventionTypesGetters,
  contactsMethods,
  projectManagementMethods,
  projectManagementGetters,
  projectsMethods
} from &quot;@/state/helpers&quot;;

// STATELESS
import {
  fetchContacts
} from '@/stateless/modules/common'

export default {
  data() {
    var vm = this;
    return {
      ...contractTypesGetters,
      ...installationTypesGetters,
      ...interventionTypesGetters,
      ...projectManagementGetters,
      
      contractTypes: [],
      selectedContract: &quot;&quot;,
      installationTypesFiltered: [],
      interventionTypesFiltered: [],
      installationTypes: [],
      interventionTypes: [],
      contactPersons: [],
      address: '',
      model: {
        projectName: '',
        address: {
          partialStreet: '',
          streetNumber: '',
          city: '',
          province: '',
          country: '',
          CAP: '',
          state: ''
        },
        contractType: '',
        installationType: '',
        interventionType: '',
        contactPerson: '',
        description: ''
      },
      formOptions: {
        validationErrorClass: &quot;has-error&quot;,
        validationSuccessClass: &quot;has-success&quot;,
        validateAfterChanged: true,
      },
      zeroTabSchema: {
        fields: [{
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            label: &quot;Nome del progetto&quot;,
            model: &quot;projectName&quot;,
            required: true,
            featured: true,
            maxlength: 64,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-12'
          },]
      },
      firstTabSchema: {
        fields: [
          {
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            label: &quot;Via&quot;,
            model: &quot;address.partialStreet&quot;,
            required: true,
            featured: true,
            maxlength: 128,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-6'
          },
          {
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            label: &quot;Numero civico&quot;,
            model: &quot;address.streetNumber&quot;,
            required: true,
            featured: true,
            maxlength: 16,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-6'
          },
          {
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            label: &quot;Città&quot;,
            model: &quot;address.city&quot;,
            required: true,
            featured: true,
            maxlength: 64,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-6'
          },
          {
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            label: &quot;Provincia&quot;,
            model: &quot;address.province&quot;,
            required: true,
            featured: true,
            maxlength: 2,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-6'
          },
          {
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            label: &quot;Paese&quot;,
            model: &quot;address.country&quot;,
            required: true,
            featured: true,
            maxlength: 32,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-6'
          },
          {
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            label: &quot;CAP&quot;,
            model: &quot;address.CAP&quot;,
            required: true,
            featured: true,
            min: 5,
            maxlength: 8,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-6'
          },
          {
            type: &quot;input&quot;,
            inputType: &quot;text&quot;,
            visible: false,
            label: &quot;Regione&quot;,
            model: &quot;address.state&quot;,
            required: true,
            featured: true,
            maxlength: 32,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-6'
          },
        ]
      },
      secondTabSchema: {
        fields: [{
            type: &quot;select&quot;,
            label: &quot;Tipo di appalto&quot;,
            model: &quot;contractType&quot;,
            required: true,
            featured: true,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-12',
            selectOptions: {
              hideNoneSelectedText: true
            },
            onChanged(event) {
              const filterdTypes = vm.installationTypes.filter((element) =&gt; {
                return element.contractType === event.contractType
              })
              let installation = document.getElementById('insediamento')
              installation.innerHTML = ''
              installation.disabled = false
              for (let i = 0; i &lt; filterdTypes.length; i++) {
                installation.options[i] = new Option(
                  filterdTypes[i].name, 
                  filterdTypes[i].id
                )
              }
              installation.value = &quot;&quot;
              let intervention = document.getElementById('tipologia-di-intervento')
              intervention.value = &quot;&quot;
            },
            values: () =&gt; {
              return this.contractTypes
            },
          },
          {
            type: &quot;select&quot;,
            disabled: &quot;true&quot;,
            label: &quot;Insediamento&quot;,
            model: &quot;installationType&quot;,
            required: true,
            featured: true,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-12',
            selectOptions: {
              hideNoneSelectedText: true
            },
            onChanged(event) {
              const filterdTypes = vm.interventionTypes.filter((element) =&gt; {
                return element.installationType === event.installationType
              })
              let intervention = document.getElementById('tipologia-di-intervento')
              intervention.innerHTML = ''
              intervention.disabled = false
              for (let i = 0; i &lt; filterdTypes.length; i++) {
                intervention.options[i] = new Option(
                  filterdTypes[i].name, 
                  filterdTypes[i].id
                )
              }
              intervention.value = &quot;&quot;
            },
            values: () =&gt; {
              return this.isModifying ? this.installationTypes : []
            },
          },
          {
            type: &quot;select&quot;,
            disabled: &quot;true&quot;,
            noneSelectedText: &quot;&quot;,
            label: &quot;Tipologia di intervento&quot;,
            model: &quot;interventionType&quot;,
            required: true,
            featured: true,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-12',
            selectOptions: {
              hideNoneSelectedText: true
            },
            values: () =&gt; {
              return this.isModifying ? this.interventionTypes : []
            },
          },
          {
            type: &quot;select&quot;,
            label: &quot;Referente di progetto&quot;,
            model: &quot;contactPerson&quot;,
            required: true,
            featured: true,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-12',
            selectOptions: {
              hideNoneSelectedText: true
            },
            hint: '&lt;div id=&quot;new-contact-creation-project&quot;&gt;&lt;i class=&quot;mdi mdi-account-multiple-plus&quot;&gt;&lt;/i&gt; &lt;span&gt;Crea nuovo referente&lt;/span&gt;&lt;/div&gt;',
            values: () =&gt; {
              return this.contactPersons
            },
          },
          {
            type: &quot;textArea&quot;,
            label: &quot;Descrizione&quot;,
            model: &quot;description&quot;,
            featured: true,
            maxlength: 512,
            validator: VueFormGenerator.validators.string,
            styleClasses: 'col-12'
          }
        ]
      }
    }
  },

  components: {
    FormWizard,
    TabContent,
    'vue-form-generator-component': VueFormGenerator.component,
    VueGoogleAutocomplete
  },

  computed: {
    isModifying() {
       return (this.$router.currentRoute.name == 'builderHome') ? false : true
    },
  },

  methods: {
    ...contractTypesMethods,
    ...installationTypesMethods,
    ...interventionTypesMethods,
    ...contactsMethods,
    ...projectsMethods,
    ...projectManagementMethods,

    onComplete: function (json) {
      if (this.isModifying) {
        this.updateProject({
          projectId: this.currentProject().id,
          name: this.model.projectName,
          description: this.model.description,
          address: this.model.address.partialStreet,
          streetNumber: this.model.address.streetNumber,
          city: this.model.address.city,
          province: this.model.address.province,
          country: this.model.address.country,
          zipCode: this.model.address.CAP,
          contactPerson: this.model.contactPerson,
          contractType: this.model.contractType,
          installationType: this.model.installationType,
          interventionType: this.model.interventionType
        }).then(() =&gt; location.reload())
      } else {
        this.addProject(json)
        .then(response =&gt; {
          if (response) {
            this.$router.push({
                  name: 'BOMUpload',
                  params: { projectId: response.data.data.createProject.project.id }
              })
          }
        })
      }
    },
    validateFirstTab: function () {
      if (!this.model.projectName) {
        return alert('Il nome del progetto è obbligatorio')
      }
      return this.$refs.firstTabForm.validate();
    },
    validateSecondTab: function () {
      return this.$refs.secondTabForm.validate();
    },

    newContactPersonCreation() {
      this.$emit('new-contact-person-creation')
    },
    
    getAddressData: function (addressData, placeResultData) {
      this.address = addressData;
      this.model.address.country = addressData.country;
      this.model.address.city = addressData.locality;
      if (placeResultData.address_components[4].short_name == 'IT') {
        this.model.address.province = placeResultData.address_components[2].short_name
      } else if (placeResultData.address_components[4].short_name.length &gt; 2) {
        this.model.address.province = placeResultData.address_components[3].short_name
      } else {
        this.model.address.province = placeResultData.address_components[4].short_name
      }
      this.model.address.partialStreet = addressData.route;
      this.model.address.streetNumber = addressData.street_number;
      this.model.address.CAP = addressData.postal_code;
      this.model.address.state = addressData.administrative_area_level_1;
    },

    getContacts() {
      fetchContacts()
      .then(response =&gt; {
        this.contactPersons = response.map(contact =&gt; {
          return { id: contact.node.id, name: contact.node.name }
        })
        this.model.contactPerson = this.contactPersons.slice(-2).pop().id
        if (this.isModifying) {
          this.model.contactPerson = this.currentProject().contactPerson.id
        }
      })
      .catch(err =&gt; console.error('Riga 417 ProjectWizard.vue', err))
    }
  },

  mounted() {

    if (this.isModifying) {
      this.model.projectName = this.currentProject().name
      this.model.address.partialStreet = this.currentProject().address.address
      this.model.address.streetNumber = this.currentProject().address.streetNumber
      this.model.address.city = this.currentProject().address.city
      this.model.address.province = this.currentProject().address.province
      this.model.address.country = this.currentProject().address.country
      this.model.address.CAP = this.currentProject().address.zipCode      
      this.model.description = this.currentProject().description
    }

    var newContact = document.querySelector(&quot;#new-contact-creation-project&quot;)
    newContact.onclick = () =&gt; {
      this.newContactPersonCreation()
    };

    // CONTRACT TYPES
    this.fetchContractTypes()
      .then(response =&gt; {
        if (response) {
          let processedContractTypes = []
          this.contractTypes = this.allContractTypes()
      
          this.contractTypes.forEach(contractType =&gt; {
            let contractTypeObj = { id: contractType.node.id, name: contractType.node.name }
            processedContractTypes.push(contractTypeObj)
          })

          this.contractTypes = processedContractTypes

          if (this.isModifying){
            this.model.contractType = this.currentProject().contractType.id
          }

        } else {
          alert('Not working fetchContractTypes')
        }
      })

    // INSTALLATION TYPES
    this.fetchInstallationTypes()
      .then(response =&gt; {
        if (response) {
          let processedInstallationTypes = []
          this.installationTypes = this.allInstallationTypes()

          this.installationTypes.forEach(installationType =&gt; {
            let installationTypeObj = { 
              id: installationType.node.id, 
              name: installationType.node.name,
              contractType: installationType.node.contractType.id
            }
            processedInstallationTypes.push(installationTypeObj)
          })

          this.installationTypes = processedInstallationTypes

          if (this.isModifying){
            this.model.installationType = this.currentProject().installationType.id
          }

        } else {
          alert('Not working fetchInstallationTypes')
        }
      })

    // INTERVENTION TYPES
    this.fetchInterventionTypes()
      .then(response =&gt; {
        if (response) {
          let processedInterventionTypes = []
          this.interventionTypes = this.allInterventionTypes()

          this.interventionTypes.forEach(interventionType =&gt; {
            let interventionTypeObj = {
              id: interventionType.node.id,
              name: interventionType.node.name,
              installationType: interventionType.node.installationType.id,
            }
            processedInterventionTypes.push(interventionTypeObj)
          })

          this.interventionTypes = processedInterventionTypes

          if (this.isModifying){
            this.model.interventionType = this.currentProject().interventionType.id
          }

        } else {
          alert('Not working fetchInterventionTypes')
        }
      })

    // CONTACT PERSONS
    this.getContacts()
  },
}
&lt;/script&gt;
</code></pre>
<ul>
<li>this is my jest configuration file:</li>
</ul>
<pre><code>module.exports = {
  verbose: true,
  roots: [&quot;&lt;rootDir&gt;/src/&quot;, &quot;&lt;rootDir&gt;/src/specs/&quot;],
  moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
  moduleNameMapper: {
    '^@/(.*)$': '&lt;rootDir&gt;/$1',
    &quot;~(.*)$&quot;: &quot;&lt;rootDir&gt;/$1&quot;
  },
  transform: {
    &quot;^.+\\.js$&quot;: &quot;babel-jest&quot;,
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'jest-transform-stub',
    &quot;^.+\\.vue$&quot;: &quot;vue-jest&quot;
  },
  snapshotSerializers: [
    &quot;&lt;rootDir&gt;/node_modules/jest-serializer-vue&quot;
  ],
  transformIgnorePatterns: [
    '&lt;rootDir&gt;/node_modules/(?!vue-google-autocomplete)',
    '&lt;rootDir&gt;/(?!)'
  ]
}
</code></pre>
<ul>
<li>and finally this is the code in the spec file:</li>
</ul>
<pre><code>import { mount } from '@vue/test-utils'
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import Component from '@/src/components/builder/ProjectWizard'

Vue.use(BootstrapVue)

describe('ProjectWizard', () =&gt; {
  it('should render a card for each project received from its parent', () =&gt; {
    const wrapper = mount(Component)
    console.log(wrapper)
  })
})
</code></pre>
<p>I dont't understand why Jest isn't able to find those functions since the module's location is right.</p>
",https://stackoverflow.com/questions/65354071/unit-testing-vue-components-with-jest-issue,"['javascript', 'unit-testing', 'vue.js', 'jestjs', 'vue-component']",338,False,0,0
Unit Testing for the Controllor SpringBoot Java,"<p>Need to do Unit Testing for the Controller part of the project but have got the error. Believe ModelAndVIew part cause the issue, even though I have mocked it and returned ModelAndView as it is return type of method. However, it does not work. Do not have any issue with Pom.xml, therefore, did not add it. 
    ProjectController:</p>

<pre><code>package com.bsptech.itcommunity.controller;

import com.bsptech.itcommunity.entity.Itproject;
import com.bsptech.itcommunity.service.inter.EmployeeProfileServiceInter;
import com.bsptech.itcommunity.service.inter.ItProjectServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(value = ""/projects"")
public class ProjectController {

    @Autowired
    private ItProjectServiceInter itProjectServiceInter;

    @Autowired
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @RequestMapping(method = RequestMethod.GET, path = ""/{projectId}"")
    public ModelAndView detail(@PathVariable(""projectId"") Integer projectId, ModelAndView modelAndView) {
        Itproject itproject = itProjectServiceInter.findById(projectId);
       modelAndView.addObject(""itproject"", itproject);
        modelAndView.setViewName(""project/details"");
        return modelAndView;
    }

    @GetMapping
    public ModelAndView index(ModelAndView modelAndView) {
        List&lt;Itproject&gt; projectList = itProjectServiceInter.findAll();
        modelAndView.addObject(""projectList"", projectList);
        modelAndView.setViewName(""project/index"");
        return modelAndView;
    }

    @RequestMapping(value = ""/join"", method = RequestMethod.POST)
    public String joinTeam(@RequestParam(""projectId"") Integer projectId){

        int result= employeeProfileServiceInter.joinProject(projectId);
        if(result==2)
            return ""redirect:/projects/""+projectId+""?alreadyjoined"";
        else if(result==1)
            return ""redirect:/projects/""+projectId+""?joinsuccess"";
        else if(result==3)
            return ""redirect:/projects/""+projectId+""?alreadysent"";
        else
            return ""redirect:/projects?error"";
    }
}
</code></pre>

<p>ProjectControllerTest</p>

<pre><code>@WebMvcTest(ProjectController.class)
@SpringBootTest
public class ProjectControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private ItProjectServiceInter itProjectServiceInter;

    @MockBean
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @Mock
    ModelAndView modelAndView;

    @Test
    public void detail() throws Exception {
      OngoingStubbing resultItProject =  when(itProjectServiceInter.findById(1)).thenReturn(new Itproject(1));
        when(modelAndView.addObject(resultItProject)).thenReturn(new ModelAndView(""project/details""));
        RequestBuilder request = MockMvcRequestBuilders.get(""/{projectId}"").accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc
                .perform(request)
                .andExpect(status().isOk())
                .andExpect(content().json(""project/details""))
                .andReturn();
    }


}
</code></pre>

<blockquote>
<pre><code>Error Which I have found it: 
java.lang.NullPointerException
  at com.bsp.tech.it.community.controller.ProjectControllerTest.detail(ProjectControllerTest.java:44)
  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.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
  at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
  at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
</blockquote>

<p>When I am using </p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {
</code></pre>

<p><strong>Getting an initialization error:</strong></p>

<blockquote>
  <p>java.lang.IllegalStateException: Unable to find a
  @SpringBootConfiguration, you need to use @ContextConfiguration or
  @SpringBootTest(classes=...) with your test</p>
  
  <p>at org.springframework.util.Assert.state(Assert.java:73)    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:149)
    at
  org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration(WebMvcTestContextBootstrapper.java:36)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:395)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:98)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:139)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:124)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:142)
    at
  org.springframework.test.context.junit4.SpringRunner.(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at
  org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at
  org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at
  org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
    at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at
  com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at
  com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)</p>
</blockquote>

<p><strong>And In the pom.xml Using this dependency:</strong></p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>
",https://stackoverflow.com/questions/60259848/unit-testing-for-the-controllor-springboot-java,"['java', 'spring-boot', 'unit-testing', 'junit']",193,False,0,1
Flutter command to export Unit testing Result,"<p>I am able to export unit testing report from Android Studio IDE. We have button to export in Android studio as below image</p>

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

<p>After clicking export button I will get a new dialog to select location of export and file type like below image</p>

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

<p>I need terminal command to do the export . </p>

<p>Terminal Command ""flutter test"" is just executing my test cases. I want to know the command for exporting unit test cases.</p>
",https://stackoverflow.com/questions/61955000/flutter-command-to-export-unit-testing-result,"['unit-testing', 'flutter', 'terminal']",594,True,0,1
Unit testing a Python Azure timer function,"<p>Azure <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#unit-testing"" rel=""nofollow noreferrer"">provide documentation for unit testing HTTP and Queue Python functions</a>. This is done by creating a mock <a href=""https://learn.microsoft.com/de-de/python/api/azure-functions/azure.functions.queuemessage?view=azure-python"" rel=""nofollow noreferrer"">QueueMessage</a> or <a href=""https://learn.microsoft.com/de-de/python/api/azure-functions/azure.functions.httprequest?view=azure-python"" rel=""nofollow noreferrer"">HTTPRequest</a>. However, there is no documentation for creating a unit test for <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=python"" rel=""nofollow noreferrer"">Timer functions</a>.</p>
<p>There is a <a href=""https://learn.microsoft.com/en-us/python/api/azure-functions/azure.functions.timerrequest?view=azure-python"" rel=""nofollow noreferrer"">TimerRequest class</a>, but creating a new instance of it fails with the following error:</p>
<pre><code>req = func.TimerRequest()
</code></pre>
<blockquote>
<p>TypeError: Can't instantiate abstract class TimerRequest with abstract
methods past_due</p>
</blockquote>
<p>What is the correct approach for creating a unit test for a Python Azure timer function?</p>
",https://stackoverflow.com/questions/63355115/unit-testing-a-python-azure-timer-function,"['python', 'azure', 'unit-testing', 'azure-functions']",831,True,0,1
Unit testing a Router provider in Go,"<p>I have a file in my project as :</p>
<pre><code>package handlers

import (
    &quot;github.com/gorilla/mux&quot;
)

type IHandlerProvider interface {
    GetRouter() *mux.Router
}

type HandlerProvider struct{}

func (h HandlerProvider) GetRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc(&quot;/health&quot;, Health).Methods(&quot;GET&quot;)
    return r
}
</code></pre>
<p>What is the right way to unit test this? For instance:</p>
<pre><code>package handlers

import (
    &quot;testing&quot;

    &quot;github.com/stretchr/testify/assert&quot;
)

func TestGetRouterOk(t *testing.T) {
    var subject IHandlerProvider = HandlerProvider{}
    router := subject.GetRouter()
    assert.NotNil(t, router)
}
</code></pre>
<p>I can assert the object not being null, but how can I test the routes are correct?</p>
",https://stackoverflow.com/questions/64584472/unit-testing-a-router-provider-in-go,"['unit-testing', 'go']",1150,True,-1,2
Angular Unit Testing Directive for Input Restriction,"<p>I have a directive with restricts user from Inputting special characters. Trying to write a unit test that validates to make sure user is not able to input special characters.</p>
<p>Below I am trying to simulate keydown event when user enters A@ - and need to test only A was allowed to be entered. Looks like the input is not getting updated with these values via events. console.log(input.value) prints empty string. The only way I can set the value is input.value but in that case I am able to set special characters as well which is not what I want.</p>
<p>Anyway to reflect user input and validate to make sure special character was not allowed?</p>
<pre><code>    it('should not allow special chars', () =&gt; {
        component.regexInput = '[a-zA-Z0-9\-\_ ]{1,25}';
        fixture.detectChanges();
        const input = fixture.nativeElement.querySelector('input');
        const event = new KeyboardEvent(&quot;keydown&quot;, {
            &quot;key&quot;: &quot;A&quot;
        });
        input.dispatchEvent(event);
        fixture.detectChanges();
        const event2 = new KeyboardEvent(&quot;keydown&quot;, {
            &quot;key&quot;: &quot;@&quot;
        });
        input.dispatchEvent(event2);
        fixture.detectChanges();
        console.log(input.value);
        expect(input.value).toEqual('A');
    });
</code></pre>
",https://stackoverflow.com/questions/63490767/angular-unit-testing-directive-for-input-restriction,"['unit-testing', 'angularjs-directive', 'karma-jasmine']",607,False,0,1
Unit testing in Python: Nesting mocked objects,"<p>I am new to unit testing in Python. I am trying to unit test a method that does something like this:</p>
<pre><code>MyClass:

    client : Client

    def __init__(client):
        self.client=client

    def method_to_test(self):
        images = self.client.get_stuff()
        image = images[0]
        result = []
        for region in image.regions:    
            result.append(region.region_id)
        return result
</code></pre>
<p>I have tried mocking and nesting of all the classes involved: Client, Image and ImageRegion. But at some point the mocking breaks down and my test fails. Is there a way to mock things so that one can do something like:</p>
<pre><code>def test_method_to_test():
   result = MyClass(mock_client).method_to_test()
   assert dummy_region_id in result
</code></pre>
<p>... or perhaps better ways to test in such situations with nested custom objects?</p>
<p>My latest attempt looks like this:</p>
<pre><code>with patch('package.module.ImageRegion') as MockRegion:
    region = MockRegion()
    region.region_id.return_value = dummy_region_id 
        with patch('package.module.Image') as MockImage:
            image = MockImage()
            image.regions.return_value = [region]
                with patch('package.module.Client') as MockClient:
                    mock_client = MockClient()
                    mock_client.get_regions.return_value = [image]
                    result = MyClass(mock_client).method_to_test()
                    assert dummy_region_id in result
</code></pre>
",https://stackoverflow.com/questions/63948475/unit-testing-in-python-nesting-mocked-objects,"['python-3.x', 'unit-testing', 'pytest', 'python-unittest', 'python-unittest.mock']",342,True,0,1
CakePHP unit testing components containing db calls,"<p>I'm trying to test a component in unit tests. problem I have is with database calls. I get error saying that association is not declared in my table class. But association is there, I checked by pasting code to AppController which returns data correctly.</p>

<p>How can I test my component code when I use associations in my query builder.</p>

<p>Looks like generic tableClass is used instead of my declared table class?</p>
",https://stackoverflow.com/questions/60016055/cakephp-unit-testing-components-containing-db-calls,"['unit-testing', 'cakephp-3.0']",33,False,0,0
Unit testing : 2 scenarios in one test?,"<p>I want to know if I have a method to test :</p>

<pre><code>public boolean validString(String str) {
   ...
}
</code></pre>

<p>Is is good to do a unit test like this :</p>

<pre><code>public void should_valid_string() {
  assertTrue(validString(""okString""));
  assertFalse(validString(""wrongString""));
}
</code></pre>

<p>or it's better to do two tests ?</p>
",https://stackoverflow.com/questions/60998409/unit-testing-2-scenarios-in-one-test,"['java', 'unit-testing', 'testing']",66,True,-1,1
Unit Testing of Angular Directive returning failure,"<p>I have a directive numbersOnly which applied to input type textbox.
Here is my Component HTML</p>

<pre><code> &lt;input type=""text"" class=""form-control"" id=""productIndex""
               required
               numbersOnly
               name=""productId""
               placeholder=""Enter Product Index""
               #postProduct
               (keyup)=""onProductAdd(postProduct)""
                /&gt;
</code></pre>

<p>A very simple directive which restricts from entering any alphabet</p>

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

@Directive({
  selector: '[numbersOnly]'
})
export class NumbersOnlyDirective {

  constructor(private _el: ElementRef) { }

  @HostListener('input', ['$event']) onInputChange(event) {
    const initalValue = this._el.nativeElement.value;
    this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
    if (initalValue !== this._el.nativeElement.value) {
      event.preventDefault();
    }
  }
}

</code></pre>

<p>Now, when writing the Unit test case using jasmine, it is always showing me an error. Below is my UT file. (Note: Keydown event is getting fired)</p>

<pre><code>import {ComponentFixture, TestBed} from '@angular/core/testing';
import { NumbersOnlyDirective } from './numbers-only.directive';
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';

@Component({
  template: `&lt;input numbersOnly type=""text"" name=""productId""  /&gt;`
})
// tslint:disable-next-line:no-unnecessary-class
class TestAllowOnlyNumbersComponent {
 //  allowNumbers = true;
}
fdescribe('Directive: numbersOnly', () =&gt; {
  let component: TestAllowOnlyNumbersComponent;
  let fixture: ComponentFixture&lt;TestAllowOnlyNumbersComponent&gt;;
  let inputEl: DebugElement;


  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [TestAllowOnlyNumbersComponent, NumbersOnlyDirective],
      schemas:      [ NO_ERRORS_SCHEMA ],
    });
    fixture = TestBed.createComponent(TestAllowOnlyNumbersComponent);
    component = fixture.componentInstance;
    inputEl = fixture.debugElement.query(By.css('input[name=""productId""]'));
    fixture.detectChanges();   
  });

  it('keydown input', () =&gt; {
    const event = new KeyboardEvent('keydown', { key: 'F' });
    inputEl.nativeElement.dispatchEvent(event);
    expect(event.defaultPrevented).toBe(true);
  });

});
</code></pre>
",https://stackoverflow.com/questions/61614064/unit-testing-of-angular-directive-returning-failure,"['javascript', 'angular', 'directive']",365,False,0,0
Unit testing Spatie laravel-medialibrary file upload,"<p>I'm having trouble getting a unit test working for file upload, and storing the file using Spatie's <a href=""https://docs.spatie.be/laravel-medialibrary/v7/introduction/"" rel=""nofollow noreferrer"">medialibrary</a>.</p>

<p>The code works fine in the browser: the file saves correctly.</p>

<p>However, this unit test fails:</p>

<pre><code>        Storage::fake('resource-files');
        $file = UploadedFile::fake()-&gt;create('courtform.pdf', 1024);

        $response = $this-&gt;ActingAs($this-&gt;adminUser())
                        -&gt;json('PATCH', '/forms/' . $dbentry-&gt;id, [
            'name' =&gt; 'Form 800',
            'state' =&gt; 'VT',
            'description' =&gt; 'General info form',
            'file' =&gt; $file,
        ]);

        // Assert the file was stored...
        Storage::disk('resource-files')-&gt;assertExists('1/courtform.pdf');
</code></pre>

<p>It fails because the mime type is empty:</p>

<pre><code>Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileUnacceptableForCollection^ {#1485
  #message: ""The file with properties `name: courtform.pdf, size: 0, mime: inode/x-empty` was not accepted into the collection named `source-pdfs` of model `App\Form` with id `1`""
</code></pre>

<p>... and I have required that the files in this collection be PDFs:</p>

<pre><code>    public function registerMediaCollections()
    {
      // Keep only one file per model
      $this
            -&gt;addMediaCollection('source-pdfs')
            -&gt;useDisk('resource-files')
            -&gt;singleFile()
            -&gt;acceptsFile(function (File $file) {
            return $file-&gt;mimeType === 'application/pdf';
          });

      $this
            -&gt;addMediaCollection('source-fdfs')
            -&gt;singleFile();

    }
</code></pre>

<p>But this empty mimeType is only an issue with the unit test — it's not a problem in the browser.</p>

<p>Does anyone know why the file properties might be <code>size: 0, mime: inode/x-empty</code> when evaluated by registerMediaCollections()?</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/62001494/unit-testing-spatie-laravel-medialibrary-file-upload,"['laravel', 'laravel-medialibrary']",2126,True,0,1
Django Unit Testing A Button (Not Form),"<p>Im writing unit tests for a Django package (<a href=""https://github.com/django-notifications/django-notifications"" rel=""nofollow noreferrer"">Django-Notifications</a>) and want to unit test that a notification is deleted when the 'delete' button is pressed.</p>
<p>I know how to test forms:</p>
<pre><code>response = self.client.post(
            reverse('webpage'), data={
            'question': 'some question'},
            HTTP_REFERER=referer,
            follow=True
        )
</code></pre>
<p>And I know how to mock users and sign them in, but have no idea how to unit test non-form buttons =.</p>
<p>More specifically, I dont know how to:</p>
<ol>
<li><p>Create the mock notification</p>
</li>
<li><p>Test that the button successfully removes the notification</p>
</li>
</ol>
<p>(Perhaps this is something that should only be functional tested?)</p>
<p>This is all I have so far:</p>
<pre><code>def test_delete_button_removes_notification(self):
        user = User.objects.create_superuser('username')
        self.client.force_login(user)
        # create notification

        # simulate button press

        # assert notification count == 0
</code></pre>
<p>Thank you.</p>
",https://stackoverflow.com/questions/62370882/django-unit-testing-a-button-not-form,"['django', 'tdd', 'django-testing', 'django-tests']",727,False,0,0
Unable to resolve NoSuchElementException while unit testing,"<p>I am trying to test supplierService class and getting <strong>NoSuchElementException</strong> while testing getSKUNameTest()</p>
<pre><code>java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
    at com.inventory.SpringInventory1ApplicationTests.getSKUNameTest(SpringInventory1ApplicationTests.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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)



</code></pre>
<p>Catalog.java and Supplier.java are the entity class</p>
<p>Catalog.java</p>
<pre><code>package com.inventory.entities;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;

@Entity
@Table(name = &quot;catalog&quot;)
public class Catalog {

    @Id
    @Column(length = 50)
    // @GeneratedValue
    private int skuCode;
    @Column(length = 50)
    private String skuName;
    @Column(length = 50)
    private String skuDesc;
    @Column(length = 50)
    private String bName;
    @Column(length = 50)
    private String bDesc;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = &quot;supplier_id&quot;, nullable = false, unique = true)
    @JsonManagedReference
    @JsonIgnore
    private Supplier supplier;// FK

    public Catalog() {
    }

    public Catalog(int skuCode, String skuName, String skuDesc, String bName, String bDesc, Supplier supplier) {
        this.skuCode = skuCode;
        this.skuName = skuName;
        this.skuDesc = skuDesc;
        this.bName = bName;
        this.bDesc = bDesc;
        this.supplier = supplier;
    }

    public int getSkuCode() {
        return skuCode;
    }

    public void setSkuCode(int skuCode) {
        this.skuCode = skuCode;
    }

    public String getSkuName() {
        return skuName;
    }

    public void setSkuName(String skuName) {
        this.skuName = skuName;
    }

    public String getSkuDesc() {
        return skuDesc;
    }

    public void setSkuDesc(String skuDesc) {
        this.skuDesc = skuDesc;
    }

    public String getbName() {
        return bName;
    }

    public void setbName(String bName) {
        this.bName = bName;
    }

    public String getbDesc() {
        return bDesc;
    }

    public void setbDesc(String bDesc) {
        this.bDesc = bDesc;
    }

    public Supplier getSupplier() {
        return supplier;
    }

    public void setSupplier(Supplier supplier) {
        this.supplier = supplier;
    }

    @Override
    public String toString() {
        return &quot;Catalog [skuCode=&quot; + skuCode + &quot;, skuName=&quot; + skuName + &quot;, skuDesc=&quot; + skuDesc + &quot;, bName=&quot; + bName
                + &quot;, bDesc=&quot; + bDesc + &quot;, supplier=&quot; + supplier + &quot;]&quot;;
    }

}


</code></pre>
<p>Supplier.java</p>
<pre><code>
package com.inventory.entities;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity
@Table(name = &quot;supplier&quot;)
public class Supplier {

    @Id
    @Column(length = 50)
    private int supplierId;
    @Column(length = 50)
    private String supplierName;
    @OneToOne(mappedBy = &quot;supplier&quot;,fetch = FetchType.LAZY)
    @JsonBackReference
    private Catalog catalog;

    public Supplier() {
    }

    public Supplier(int supplierId, String supplierName) {
        super();
        this.supplierId = supplierId;
        this.supplierName = supplierName;
    }

    public int getSupplierId() {
        return supplierId;
    }

    public void setSupplierId(int supplierId) {
        this.supplierId = supplierId;
    }

    public String getSupplierName() {
        return supplierName;
    }

    public void setSupplierName(String supplierName) {
        this.supplierName = supplierName;
    }

    public Catalog getCatalog() {
        return catalog;
    }

    public void setCatalog(Catalog catalog) {
        this.catalog = catalog;
    }

    @Override
    public String toString() {
        return &quot;Supplier [supplierId=&quot; + supplierId + &quot;, supplierName=&quot; + supplierName + &quot;, catalog=&quot; + catalog + &quot;]&quot;;
    }

}


</code></pre>
<p>Service Classes</p>
<p>CatalogService.java</p>
<pre><code>package com.inventory.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.inventory.entities.Catalog;
import com.inventory.repository.CatalogRepository;

@Service
public class CatalogService {
    
    @Autowired
    private CatalogRepository catalogRepository;
    
    public Catalog getCatalogById(int id) {
        return catalogRepository.findById(id).get();
    }
    
    public Catalog saveCatalog(Catalog catalog) {
        return catalogRepository.save(catalog);
    }
    
}


</code></pre>
<p>SupplierService.java</p>
<pre><code>
package com.inventory.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.inventory.entities.Supplier;
import com.inventory.repository.SupplierRepository;

@Service
public class SupplierService {
    
    @Autowired
    private SupplierRepository supplierRepository;

    public Supplier getSupplierById(int id) {
        return supplierRepository.findById(id).get();
    }
    
    public Supplier insertSupplier(Supplier supplier) {
        return supplierRepository.save(supplier);
    }
    

}


</code></pre>
<p>Repository Classes</p>
<p>SupplierRepository.java</p>
<pre><code>package com.inventory.repository;

import org.springframework.data.repository.CrudRepository;

import com.inventory.entities.Supplier;

public interface SupplierRepository extends CrudRepository&lt;Supplier, Integer&gt;{

}


</code></pre>
<p>CatalogRepository.java</p>
<pre><code>package com.inventory.repository;

import org.springframework.data.repository.CrudRepository;

import com.inventory.entities.Catalog;

public interface CatalogRepository extends CrudRepository&lt;Catalog, Integer&gt;{

}


</code></pre>
<p>Here is Testing Class</p>
<p>SpringInventory1ApplicationTests.java</p>
<pre><code>package com.inventory;

import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

import java.util.Optional;

import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import com.inventory.entities.Catalog;
import com.inventory.entities.Supplier;
import com.inventory.repository.CatalogRepository;
import com.inventory.repository.SupplierRepository;
import com.inventory.service.CatalogService;
import com.inventory.service.SupplierService;

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringInventory1ApplicationTests {

    @Autowired
    private CatalogService catalogSevice;
    @InjectMocks
    private SupplierService supplierService;
    
    @MockBean
    private CatalogRepository catalogRepository;
    
    @Mock
    private SupplierRepository supplierRepository;
    
    @Before
    void setUp() {
        MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void getCatalogByIdTest() {
        Catalog catalog = new Catalog(201,&quot;Kitchen Products&quot;, &quot;Daily Products&quot;, &quot;bajaj&quot;, &quot;bajaj Eletronics&quot;, new Supplier(1,&quot;Shubham&quot;));
        when(catalogRepository.findById(201)).thenReturn(Optional.of(catalog));
        assertEquals(catalog,catalogSevice.getCatalogById(201));
    }
    
    @Test
    public void getSKUNameTest() {
        Supplier supplier = new Supplier(1,&quot;John&quot;);
        Catalog catalog = new Catalog();
        catalog.setbName(&quot;Bajaj&quot;);
        catalog.setbDesc(&quot;Eletrical gadgets&quot;);
        catalog.setSkuCode(101);
        catalog.setSkuName(&quot;Mixer&quot;);
        catalog.setSupplier(supplier);
        
        //supplier.setCatalog(catalog);     
        when(supplierRepository.findById(1).get()).thenReturn(supplier);
        Supplier s = supplierService.getSupplierById(1);
        assertEquals(&quot;Mixer&quot;,supplierService.getSupplierById(1).getCatalog().getSkuName());
    }

    
    @Test
    public void insetCatalogTest() {
        Catalog catalog = new Catalog(201,&quot;Kitchen Products&quot;, &quot;Daily Products&quot;, &quot;bajaj&quot;, &quot;bajaj Eletronics&quot;, new Supplier(6,&quot;Shubham&quot;));
        when(catalogRepository.save(catalog)).thenReturn(catalog);
        assertEquals(catalog, catalogSevice.saveCatalog(catalog));
    }
    
    
    @Test
    public void insertSupplierTest() {
        Supplier supplier = new Supplier(20, &quot;Shubhanjali&quot;);
        when(supplierRepository.save(supplier)).thenReturn(supplier);
        assertEquals(supplier, supplierService.insertSupplier(supplier));
    }

}

</code></pre>
<p>I am getting NoSuchElementException in testing getSKUNameTest().
while debugging I noticed that  <code>when(supplierRepository.findById(1).get()).thenReturn(supplier);</code>
this line is returning nothing, but I don't know how to resolve this issue, Please Help.</p>
<p>Please help me as I am new to Spring and Hibernate as well in stackoverflow if anything needs to be edited or question is not clear please guide me so I can improve it further.</p>
",https://stackoverflow.com/questions/65075693/unable-to-resolve-nosuchelementexception-while-unit-testing,"['java', 'spring-boot', 'hibernate', 'rest', 'mockito']",754,True,0,1
Data Testing / REST Assured / Java Unit Testing,"<p>So in the past I have worked with rest assured and other java frameworks.</p>
<p>This is more an open ended question in what is the best / modern way to test data either sql / oracle ...etc</p>
<p>So the basics would be is you need to confirm data in a table is equal to a specific string / int / boolean ...etc. The test needs to be able to run via maven or something that can be integrated into a Jenkins type of environment so that it will be run on every build.</p>
<p>What would you suggest is the best way to achieve this any idea or tools that you have used would be welcome.</p>
<p>I have searched around and most people are just doing normal unit tests. But if i wanted to test production data that should remain static what would you suggest or are the best practices.</p>
<p>Thanks
Flenters</p>
",https://stackoverflow.com/questions/63190700/data-testing-rest-assured-java-unit-testing,"['java', 'testing', 'junit', 'rest-assured']",281,True,-1,1
Unit Testing in React JS using Jest,"<p>I trying to do unit testing in a react application in which I want to test only one component.</p>
<p>What is the command for running the test of particular component?</p>
<p>I am doing this way for testing.</p>
<pre><code>npm test -- --testPathPattern components
</code></pre>
<p>I have all the <code>*.test.js</code> inside the components folder.</p>
<p>Above command will run the test cases for all the test files under the components folder but I want to run the tests only for the specific component.</p>
",https://stackoverflow.com/questions/64183721/unit-testing-in-react-js-using-jest,"['reactjs', 'jestjs']",220,True,0,2
Angular/Jest unit testing with Mapquest API,"<p>I am using mapquest api through CDN and have it declared as ""declare let L: any;"" in my typescript code. When I try to write unit tests and run the test suite I get an error ""ReferenceError: L is not defined"".</p>

<p>I am using Angular 8 and Jest as test runner. Please let me know, how to include the declaration in the unit tests. Thanks in advance</p>
",https://stackoverflow.com/questions/61196726/angular-jest-unit-testing-with-mapquest-api,"['angular', 'unit-testing', 'jasmine', 'jestjs', 'mapquest']",142,False,0,1
Unit testing of Realm in Xamarin iOS,"<p>Xamarin iOS native app. I have to write unit test for Realm api. It is the layer with ability to filter data. It can contain complicated Linq queries, so testing is necessary.
For instance, method:</p>
<p><code> Task&lt;List&lt;T&gt;&gt; Get(int count, int type, int? id);</code></p>
<p>Creating NUnit test I need to get Realm object:</p>
<p><code>var realm = Realm.GetInstance(new InMemoryConfiguration(&quot;test&quot;));</code></p>
<p>but getting an exception:</p>
<pre><code>System.TypeInitializationException : The type initializer for 'Realms.SharedRealmHandle' threw an exception.
  ----&gt; System.DllNotFoundException : realm-wrappers assembly:&lt;unknown assembly&gt; type:&lt;unknown type&gt; member:(null)
  at Realms.InMemoryConfiguration.CreateRealm (Realms.Schema.RealmSchema schema) [0x0003e] in C:\jenkins\workspace\realm_realm-dotnet_PR\Realm\Realm\Configurations\InMemoryConfiguration.cs:62 
  at Realms.Realm.GetInstance (Realms.RealmConfigurationBase config, Realms.Schema.RealmSchema schema) [0x0003c] in C:\jenkins\workspace\realm_realm-dotnet_PR\Realm\Realm\Realm.cs:136 
  at Realms.Realm.GetInstance (Realms.RealmConfigurationBase config) [0x00000] in C:\jenkins\workspace\realm_realm-dotnet_PR\Realm\Realm\Realm.cs:81 
  at UnitTestREALM.TransactionsRealmApiTest.RealmApi () [0x00001] in /Users/user/Projects/myApp/UnitTestREALM/TransactionsRealmApiTest.cs:26 
  at (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo.InternalInvoke(System.Reflection.RuntimeMethodInfo,object,object[],System.Exception&amp;)
  at System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x0006a] in /Users/builder/jenkins/workspace/build-package-osx-mono/2020-02/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.Reflection/RuntimeMethodInfo.cs:395 
--DllNotFoundException
  at (wrapper managed-to-native) Realms.SynchronizationContextEventLoopSignal.install_eventloop_callbacks(Realms.SynchronizationContextEventLoopSignal/get_eventloop,Realms.SynchronizationContextEventLoopSignal/post_on_event_loop,Realms.SynchronizationContextEventLoopSignal/release_eventloop)
  at Realms.SynchronizationContextEventLoopSignal.Install () [0x0003b] in C:\jenkins\workspace\realm_realm-dotnet_PR\Realm\Realm\Native\SynchronizationContextEventLoopSignal.cs:122 
  at Realms.NativeCommon.Initialize () [0x00112] in C:\jenkins\workspace\realm_realm-dotnet_PR\Realm\Realm\Native\NativeCommon.cs:91 
  at Realms.SharedRealmHandle..cctor () [0x00000] in C:\jenkins\workspace\realm_realm-dotnet_PR\Realm\Realm\Handles\SharedRealmHandle.cs:128
</code></pre>
<p>So, main point that I can't create Realm instance.<br />
Is launched iphone simulator necessary to work with Realm?
Are there some possibility to create unit tests for Realm?
Or should it be some kind of Auto tests?</p>
",https://stackoverflow.com/questions/64678657/unit-testing-of-realm-in-xamarin-ios,"['c#', 'ios', 'xamarin', 'realm', 'nunit']",116,True,0,1
Unit testing Elastic Search Nest client - BulkAll,"<p>I am writing a unit test for the ElasticSearch Nest .net client.</p>
<p>I have the following call inside a repository class</p>
<pre><code>var observable = _client.BulkAll(documents,
    selector =&gt; selector
        .BackOffTime(&quot;30s&quot;)
        .BackOffRetries(2)
        .RefreshOnCompleted()
        .Size(1000)
    ).Wait(
        TimeSpan.FromMinutes(15),
        next =&gt; {
            _logger.LogInformation($&quot;Adding {next.Items.Count} number of items&quot;);
    });
</code></pre>
<p>In my unit test I have :</p>
<pre><code>client = Substitute.For&lt;IElasticClient&gt;();
await _repository.AddDocuments(documents);
_client.Received().BulkAll(Arg.Any&lt;IBulkAllRequest&lt;Purchase&gt;);
</code></pre>
<p>But I get the following exception when running my unit test</p>
<pre><code>Value cannot be null. (Parameter 'observable')
   at Nest.Extensions.ThrowIfNull[T](T value, String name, String message)
</code></pre>
<p>I'm not sure how to correctly structure my unit test.</p>
<p>Any help much appreciated</p>
",https://stackoverflow.com/questions/64101323/unit-testing-elastic-search-nest-client-bulkall,"['c#', 'unit-testing', 'elasticsearch', 'observable', 'nest']",794,True,0,1
Spring Data JPA - Unit Testing with H2,"<p>My app is calling Oracle DB using Spring data JPA, and one of the operations is calling a Stored Procedure.</p>
<p>When it come to integration testing, I'm using H2 DB, but I found difficulties to call the SP.</p>
<p>Below is the way I'm calling the SP</p>
<pre><code>final StoredProcedureQuery query = entityManager
            .createStoredProcedureQuery(&quot;MY_SP_HERE&quot;)
            .registerStoredProcedureParameter(&quot;PARAM_1&quot;, String.class, ParameterMode.IN)
            .setParameter(&quot;PARAM_1&quot;, &quot;VALUE_PARAM_1&quot;)
            .registerStoredProcedureParameter(&quot;V_CURSOR_OUT&quot;, CustomClass.class,
                    ParameterMode.REF_CURSOR);

query.execute();

final List&lt;Object[]&gt; obj = query.getResultList();
</code></pre>
<p>Is it possible to call the SP from H2 ?</p>
",https://stackoverflow.com/questions/62594362/spring-data-jpa-unit-testing-with-h2,"['spring', 'unit-testing', 'spring-data-jpa', 'h2']",202,False,0,0
Unit testing interfaces using lambdafunction AWS annotation,"<p>I'm looking a way to unit testing a call to an external lambda. I have an interface using @LambdaFunction (<code>functionName = &quot;external-lambda&quot;</code>) on a method that call the external handler. I don't figure out how to (mock maybe?) Stub this component inside my unit test. There is a correct way to attain this?</p>
",https://stackoverflow.com/questions/63043674/unit-testing-interfaces-using-lambdafunction-aws-annotation,"['amazon-web-services', 'junit', 'aws-lambda', 'mockito']",40,False,0,0
"AngularFireDatabase, Jest and unit testing firebase realtime database","<p>I have a service that has 2 methods that return data from firebase realtime db</p>
<pre><code>getAllProducts -&gt; returns an observable array of products
getSingleProduct -&gt; returns an observable single product
</code></pre>
<p>I am trying to create unit tests using Jest to mock firebase so I can test these 2 methods:</p>
<p><strong>Test file</strong></p>
<pre class=""lang-js prettyprint-override""><code>    import {TestBed, async} from '@angular/core/testing';
    import {ProductService} from './product.service';
    import {AngularFireModule} from '@angular/fire';
    import {environment} from 'src/environments/environment';
    import {AngularFireDatabase} from '@angular/fire/database';
    import {getSnapShotChanges} from 'src/app/test/helpers/AngularFireDatabase/getSnapshotChanges';
    import {Product} from './product';
    
    class angularFireDatabaseStub {
      getAllProducts = () =&gt; {
        return {
          db: jest.fn().mockReturnThis(),
          list: jest.fn().mockReturnThis(),
          snapshotChanges: jest
            .fn()
            .mockReturnValue(getSnapShotChanges(allProductsMock, true))
        };
      };
      getSingleProduct = () =&gt; {
        return {
          db: jest.fn().mockReturnThis(),
          object: jest.fn().mockReturnThis(),
          valueChanges: jest.fn().mockReturnValue(of(productsMock[0]))
        };
      };
    }
    
    describe('ProductService', () =&gt; {
      let service: ProductService;
    
      beforeEach(() =&gt; {
        TestBed.configureTestingModule({
          imports: [AngularFireModule.initializeApp(environment.firebase)],
          providers: [
            {provide: AngularFireDatabase, useClass: angularFireDatabaseStub}
          ]
        });
        service = TestBed.inject(ProductService);
      });
    
      it('should be created', () =&gt; {
        expect(service).toBeTruthy();
      });
    
      it('should be able to return all products', async(() =&gt; {
        const response$ = service.getAllProducts();
        response$.subscribe((products: Product[]) =&gt; {
          expect(products).toBeDefined();
          expect(products.length).toEqual(10);
        });
      }));
    });
</code></pre>
<p><code>allProductsMock</code> and <code>singleProductMock</code> are just dummy data in the local file.</p>
<p><em>The error thrown is <code>this.db.list</code> is not a function.</em></p>
<p>If I change the stub to a basic constant and not a class, then the allProducts test passes, but obviously I am then stuck testing the <code>getSingleProduct</code> method:</p>
<pre class=""lang-js prettyprint-override""><code>    const angularFireDatabaseStub = {
      db: jest.fn().mockReturnThis(),
      list: jest.fn().mockReturnThis(),
      snapshotChanges: jest
        .fn()
        .mockReturnValue(getSnapShotChanges(allProductsMock, true))
      };
    }
</code></pre>
<p>So how can I make the stub more versatile and be able to also test the <code>getSingleProduct</code> method?</p>
<p><strong>Helper</strong></p>
<p><code>getSnapshotChanges</code> is a helper:</p>
<pre class=""lang-js prettyprint-override""><code>    import {of} from 'rxjs';
    
    export function getSnapShotChanges(data: object, asObservable: boolean) {
      const actions = [];
      const dataKeys = Object.keys(data);
      for (const key of dataKeys) {
        actions.push({
          payload: {
            val() {
              return data[key];
            },
            key
          },
          prevKey: null,
          type: 'value'
        });
      }
      if (asObservable) {
        return of(actions);
      } else {
        return actions;
      }
    }
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I did find one way to do both tests, but it's not very DRY having to setup the TestBed twice. Surely there must be a way to combine both stubs and inject them into the TestBed only once?</p>
<pre class=""lang-js prettyprint-override""><code>import {TestBed, async} from '@angular/core/testing';
import {ProductService} from './.service';
import {AngularFireModule} from '@angular/fire';
import {environment} from 'src/environments/environment';
import {AngularFireDatabase} from '@angular/fire/database';
import {productsMock} from '../../../../mocks/products.mock';
import {getSnapShotChanges} from 'src/app/test/helpers/AngularFireDatabase/getSnapshotChanges';
import {Product} from './product';
import {of} from 'rxjs';

const getAllProductsStub = {
  db: jest.fn().mockReturnThis(),
  list: jest.fn().mockReturnThis(),
  snapshotChanges: jest
    .fn()
    .mockReturnValue(getSnapShotChanges(productsMock, true))
};
const getSingleProductStub = {
  db: jest.fn().mockReturnThis(),
  object: jest.fn().mockReturnThis(),
  valueChanges: jest.fn().mockReturnValue(of(productsMock[0]))
};

describe('getAllProducts', () =&gt; {
  let service: ProductService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [AngularFireModule.initializeApp(environment.firebase)],
      providers: [{provide: AngularFireDatabase, useValue: getAllProductsStub}]
    }).compileComponents();
    service = TestBed.inject(ProductService);
  });

  it('should be able to return all products', async(() =&gt; {
    const response$ = service.getAllProducts();
    response$.subscribe((products: Product[]) =&gt; {
      expect(products).toBeDefined();
      expect(products.length).toEqual(10);
    });
  }));
});

describe('getSingleProduct', () =&gt; {
  let service: ProductService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [AngularFireModule.initializeApp(environment.firebase)],
      providers: [{provide: AngularFireDatabase, useValue: getSingleProductStub}]
    }).compileComponents();
    service = TestBed.inject(ProductService);
  });

  it('should be able to return a single  product using the firebase id', async(() =&gt; {
    const response$ = service.getSingleProduct('-MA_EHxxDCT4DIE4y3tW');
    response$.subscribe((product: Product) =&gt; {
      expect(product).toBeDefined();
      expect(product.id).toEqual('-MA_EHxxDCT4DIE4y3tW');
    });
  }));
});

</code></pre>
",https://stackoverflow.com/questions/62597952/angularfiredatabase-jest-and-unit-testing-firebase-realtime-database,"['angular', 'firebase', 'unit-testing', 'jestjs', 'angularfire']",955,True,6,1
"django test client CRUD API, unit testing","<p>I want to write pure unit tests for my CRUD APP in django.
Everyone use django tests or pytests, but I am really confused. Should I use test client to testing eg. POST method?
Unit tests should be isolate and class should be test independently. We should use mocks DB etc.</p>
<p>So why this code from <a href=""https://medium.com/@ksarthak4ever/test-driven-development-tdd-in-django-and-django-rest-framework-drf-a889a8068cb7"" rel=""nofollow noreferrer"">https://medium.com/@ksarthak4ever/test-driven-development-tdd-in-django-and-django-rest-framework-drf-a889a8068cb7</a> is unit tests?</p>
<pre><code>class PrivateIngredientsApiTest(TestCase): #Test the private ingredients api
 
 def setUp(self):
  self.client = APIClient()
  self.user = get_user_model().objects.create_user(
   'ksarthak4ever@gmail',
   'hakunamatata'
  )
  self.client.force_authenticate(self.user)

 def test_retrieve_ingredients_list(self): #Test retrieving a list of ingredients
  Ingredient.objects.create(user=self.user, name='Potato')
  Ingredient.objects.create(user=self.user, name='Peas')
  res = self.client.get(INGREDIENTS_URL)ingredients = Ingredient.objects.all().order_by('-name')
  serializer = IngredientSerializer(ingredients, many=True)
  self.assertEqual(res.status_code, status.HTTP_200_OK)
  self.assertEqual(res.data, serializer.data)
</code></pre>
<p>For me this is functional test, not unit test. I search all over the internet how to write unit tests for django, but I didn't find anything.</p>
",https://stackoverflow.com/questions/62676838/django-test-client-crud-api-unit-testing,"['python', 'django', 'unit-testing', 'testing', 'tdd']",592,False,0,0
C++ unit testing for multiple cpu architectures,"<p>we develop an app in C++ for ARM and x86 architectures. Of course we integration test our app for both architectures but for now we unit test our app only on x86. Is this a possible error source and is it normal to run unit tests for all supported architectures? </p>
",https://stackoverflow.com/questions/61645642/c-unit-testing-for-multiple-cpu-architectures,"['c++', 'unit-testing', 'x86', 'arm']",124,True,0,1
Unit Testing Public Signed .NET Core/Framework Libraries,"<p>I have a NuGet package library project that is compiling for .NET Core and .NET Framework. It is also using the new <a href=""https://github.com/dotnet/corefx/blob/master/Documentation/project-docs/public-signing.md"" rel=""noreferrer"">public signing</a>.</p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup Label=""Build""&gt;
    &lt;TargetFrameworks&gt;netstandard2.0;net472&lt;/TargetFrameworks&gt;
  &lt;/PropertyGroup&gt;

  &lt;PropertyGroup Label=""Signing""&gt;
    &lt;SignAssembly&gt;true&lt;/SignAssembly&gt;
    &lt;AssemblyOriginatorKeyFile&gt;../../Key.snk&lt;/AssemblyOriginatorKeyFile&gt;
    &lt;PublicSign&gt;true&lt;/PublicSign&gt;
  &lt;/PropertyGroup&gt;

&lt;/Project&gt;
</code></pre>

<p>I have an xUnit test project using which is also cross compiling to .NET Core and .NET Framework.</p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup Label=""Build""&gt;
    &lt;TargetFrameworks&gt;netcoreapp3.1;net472&lt;/TargetFrameworks&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup Label=""Package References""&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""16.4.0"" /&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.4.1"" /&gt;
    &lt;PackageReference Include=""xunit.runner.visualstudio"" Version=""2.4.1"" /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup Label=""Project References""&gt;
    &lt;ProjectReference Include=""..\..\Source\Foo\Foo.csproj"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>

<p>When I run the tests in this project, the .NET Core test run succeeds but the .NET Framework test run fails with:</p>

<blockquote>
  <p>System.IO.FileLoadException : Could not load file or assembly 'Foo, Version=0.0.1.0, Culture=neutral, PublicKeyToken=fc5550082a9c642c' or one of its dependencies. Strong name signature could not be verified.  The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)</p>
</blockquote>

<p>How can I get them both to work?</p>
",https://stackoverflow.com/questions/60058571/unit-testing-public-signed-net-core-framework-libraries,"['c#', '.net', '.net-core', 'xunit', 'strongname']",203,True,5,1
Unit Testing a Class With A Private Constructor,"<p>I am trying to test a class that only has a private constructor.  This is for a course registration system.  The courses do not get create via our application, therefore we intentionally have no public constructor.  Instead we use EF to get the courses that are already in the database, and register students to them.</p>
<p>I am trying to test the register method of the Course class, however I have no way of creating an instance. I could use
<code>course = (Course)Activator.CreateInstance(typeof(Course), true);</code>, but then I don't have a way to setup the necessary properties since those are private.</p>
<p>What is the recommended approach for unit testing without a constructor?</p>
<p>This is a slimmed down version of the code.</p>
<pre><code>public class Course
{
    private Course()
    {
    }

    public int Id { get; private set; }
    public string Name { get; private set; }
    public bool Open { get; private set; }
    public virtual ICollection&lt;Student&gt; Students { get; private set; }

    public void Register(string studentName)
    {
        if (Open)
        {
            var student = new Student(studentName);
            Students.Add(student);
        }
    }
}
</code></pre>
<p>// Usage //</p>
<pre><code>using (var db = new SchoolContext())
        {
            var course = db.Courses.Include(x =&gt; x.Students).Where(x =&gt; x.Name == courseName).First();

            course.Register(studentName);
            db.SaveChanges();
        }
</code></pre>
<p>// Unit Test //</p>
<pre><code>[Fact]
public void CanRegisterStudentForOpenClass(){
    // HERE I HAVE NO WAY TO CHANGE THE OPEN VARIABLE
    var course = (Course)Activator.CreateInstance(typeof(Course), true);
    course.Register(&quot;Bob&quot;);
}



    
</code></pre>
",https://stackoverflow.com/questions/63400165/unit-testing-a-class-with-a-private-constructor,"['c#', '.net', 'unit-testing', 'xunit']",2002,True,5,5
Unit testing: Entry name &#39;res/layout/test_toolbar.xml&#39; collided,"<p>I've tried to do some unit test example that included in an Android Studio project like <code>ExampleInstrumentedTest</code> and <code>ExampleUnitTest</code>, so the result is :</p>

<blockquote>
  <p>Entry name 'res/layout/test_toolbar.xml' collided</p>
</blockquote>

<p>I've searched everywhere on google but there's not answers to this specific problem, so any help will be grateful </p>

<p>here's the source of the basic unit test example :  </p>

<p><strong>ExampleUnitTest</strong></p>

<pre><code> * Example local unit test, which will execute on the development machine (host).
 *
 * @see &lt;a href=""http://d.android.com/tools/testing""&gt;Testing documentation&lt;/a&gt;
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() {
        assertEquals(4, 2 + 2);
    }}
</code></pre>

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

<p><strong>ExampleInstrumentedTest</strong></p>

<pre><code> * Instrumented test, which will execute on an Android device.
 *
 * @see &lt;a href=""http://d.android.com/tools/testing""&gt;Testing documentation&lt;/a&gt;
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getInstrumentation().getContext();

        assertEquals(""com.example.abder.emarque"", appContext.getPackageName());
    }}
</code></pre>

<p><a href=""https://i.stack.imgur.com/yZRqZ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yZRqZ.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/60428832/unit-testing-entry-name-res-layout-test-toolbar-xml-collided,"['java', 'android', 'unit-testing', 'android-debug', 'test-coverage']",1715,False,4,2
Firebase Authentication Unit Testing via emulators with Angular,"<p>I've been trying to unit test every testable piece of code in my projects and I recently found that Firebase has added Authentication as part of their emulation suite. I'm working on an Angular/Nativescript project right now and I'm running my database tests with the Firestore emulator as a part of my testing environment and I love it. Thing is, a bit of finagling is required to get this to work in the first place.</p>
<p>Basically I just configure <code>TestBed</code> with both the required Firebase modules and provide a <code>SETTINGS</code> object which tells <code>AngularFirestoreModule</code> to target the emulator instead of my production database. It looks something like this:</p>
<pre class=""lang-js prettyprint-override""><code>TestBed.configureTestingModule({
    imports:[
        AngularFireModule.initializeApp(environment.firebaseConfig),
        AngularFirestoreModule
    ],
    providers: [
        //this is what I'm unit testing
        { provide: Database, useClass: FirebaseDatabase },
        //this is the object I provide to my testing environment
        { provide: SETTINGS, useValue: { host: 'localhost:8080', ssl: false } }  
    ]
});
</code></pre>
<p>So far so good. Problem is when I try to apply that same concept to Authentication. Going through the <a href=""https://github.com/angular/angularfire/blob/master/src/auth/auth.ts"" rel=""nofollow noreferrer"">AngularFireAuth</a> source code it seems like it requires injection for the mostly the same stuff as the <a href=""https://github.com/angular/angularfire/blob/master/src/firestore/firestore.ts"" rel=""nofollow noreferrer"">AngularFirestore</a> module except <code>SETTINGS</code>. What do I need to provide in <code>TestBed</code> to target the Authentication emulator?</p>
",https://stackoverflow.com/questions/64652742/firebase-authentication-unit-testing-via-emulators-with-angular,"['angular', 'firebase', 'unit-testing', 'firebase-authentication', 'firebase-cli']",391,False,4,0
"Android, Room fail on unit testing with Robolectric","<p>I am trying to create some tests for a view model. </p>

<p>The view model includes a Database instantiation which calls a Database</p>

<p><code>CallRoomDatabase db = CallRoomDatabase.getDatabase(application);</code></p>

<p>where getDatabase takes an instance of the Dao()</p>

<pre><code>  @Database(entities = {CallEntity.class}, version = 1)
 public abstract class CallRoomDatabase extends RoomDatabase {

public abstract CDao cDao();

// marking the instance as volatile to ensure atomic access to the variable
private static volatile CRoomDatabase INSTANCE;

public static CRoomDatabase getDatabase(final Context context) {
    if (INSTANCE == null) {
        synchronized (CallRoomDatabase.class) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        CRoomDatabase.class, ""database"")
                        // Wipes and rebuilds instead of migrating if no Migration object.
                        // Migration is not part of this codelab.
                        .fallbackToDestructiveMigration()
                        .addCallback(sRoomDatabaseCallback)
                        .build();
            }
        }
    }
    return INSTANCE;
}
</code></pre>

<p>However, when trying to instantiate the model within a test, I get an error on <code>.build()</code> above</p>

<pre><code>  java.lang.NullPointerException
at androidx.room.Room.getGeneratedImplementation(Room.java:79)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:952)
at com.s.o.dbutils.CRoomDatabase.getDatabase(CRoomDatabase.java:32)
at com.s.o.viewmodels.CViewModelTest.checkForNuTest(CViewModelTest.kt: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.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:83)
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)
</code></pre>

<p>At <code>RoomDatabase.java</code> </p>

<pre><code>            T db = Room.getGeneratedImplementation(mDatabaseClass, DB_IMPL_SUFFIX);
</code></pre>

<p>At <code>Room.java</code>  <code>klass</code> is <code>null</code></p>

<pre><code>        static &lt;T, C&gt; T getGeneratedImplementation(Class&lt;C&gt; klass, String suffix) {
</code></pre>

<p>I have tried not using the model at all at the test, just instantiate the db with</p>

<pre><code>          val db = CRoomDatabase.getDatabase(ApplicationProvider.getApplicationContext())
</code></pre>

<p>Still breaks at the same <code>.build()</code></p>

<p>Any ideas how to get past that exception ?</p>

<p>We dont actually need to test the db someway, just some functions included in that model, so some way to just avoid the error would suffice.</p>
",https://stackoverflow.com/questions/60720976/android-room-fail-on-unit-testing-with-robolectric,"['android', 'unit-testing', 'kotlin', 'android-room', 'robolectric']",1572,True,4,2
Unit testing c++ code into Zephyr with googletest,"<p>We are starting to work with Zephyr and have decided to use C++. I am now trying  to figure out how to unittest the code. As I understand ztest and unity which is already integrated into zephyr/nrfconnect doesn't support c++. I have decided to use googletest. I have created a custom module to download, compile and integrate into zephyr. I have now some troubles.</p>
<p>The structure of my project look like this:</p>
<pre><code>|-modules
|   |-googletest
|         |-zephyr
|            |-module.yml
|         |-CMakeLists.txt
|         |-CMakeLists.txt.in
|         |-Kconfig
|-src
|-tests
   |-button
   |    |-main.cpp
   |-CMakeLists.txt
   |-prj.conf
   |-testcase.yaml   
</code></pre>
<p>CMakeList of tests/button look like this:</p>
<pre><code>cmake_minimum_required(VERSION 3.13.1)

set(BOARD native_posix)
set(ZEPHYR_TOOLCHAIN_VARIANT zephyr)
set(TOOLCHAIN_ROOT ${ZEPHYR_BASE})
set(ZEPHYR_EXTRA_MODULES $ENV{ZEPHYR_BASE}/../iot_aleph/modules/googletest)

find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(&quot;Button unit tests&quot;)

# Include event headers
zephyr_library_include_directories(../../src/board)

# Add test sources
target_sources(app PRIVATE src/main.cpp)
target_sources(app PRIVATE ../../src/board/button.cpp)

target_link_libraries(app PUBLIC gtest_main) 
</code></pre>
<p>CMakeLists.txt of module/googletest look like:</p>
<pre><code>cmake_minimum_required(VERSION 3.1)

if(CONFIG_GOOGLETEST)

# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G &quot;${CMAKE_GENERATOR}&quot; .
  RESULT_VARIABLE result
  WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
  message(FATAL_ERROR &quot;CMake step for googletest failed: ${result}&quot;)
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
  RESULT_VARIABLE result
  WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
  message(FATAL_ERROR &quot;Build step for googletest failed: ${result}&quot;)
endif()

set(gtest_force_shared_crt ON CACHE BOOL &quot;&quot; FORCE)

add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
                 ${CMAKE_CURRENT_BINARY_DIR}/googletest-build
                 EXCLUDE_FROM_ALL)

endif()
</code></pre>
<p>CMakeLists.txt.in</p>
<pre><code>cmake_minimum_required(VERSION 3.1)

project(googletest-download NONE)

include(ExternalProject)
ExternalProject_Add(googletest
  GIT_REPOSITORY    https://github.com/google/googletest.git
  GIT_TAG           release-1.10.0
  SOURCE_DIR        &quot;${CMAKE_CURRENT_BINARY_DIR}/googletest-src&quot;
  BINARY_DIR        &quot;${CMAKE_CURRENT_BINARY_DIR}/googletest-build&quot;
  CONFIGURE_COMMAND &quot;&quot;
  BUILD_COMMAND     &quot;&quot;
  INSTALL_COMMAND   &quot;&quot;
  TEST_COMMAND      &quot;&quot;
)
</code></pre>
<p>The GoogleTest framework seems to compile correctly but when it come to linking, I hae a lot of errors:</p>
<pre><code>[92/93] Linking CXX executable zephyr/zephyr.elf
FAILED: zephyr/zephyr.elf zephyr/zephyr.lst zephyr/zephyr.stat zephyr/zephyr.exe 
: &amp;&amp; ccache /usr/bin/g++     zephyr/CMakeFiles/zephyr_prebuilt.dir/misc/empty_file.c.obj  -o zephyr/zephyr.elf  -Wl,-T  zephyr/linker.cmd  -Wl,-Map=/home/cyril/Documents/zephyr_workpsace/iot_aleph/tests/button/build/zephyr/zephyr_prebuilt.map  -Wl,--whole-archive  app/libapp.a  zephyr/libzephyr.a  zephyr/arch/arch/posix/core/libarch__posix__core.a  zephyr/soc/posix/inf_clock/libsoc__posix__inf_clock.a  zephyr/boards/posix/native_posix/libboards__posix__native_posix.a  -Wl,--no-whole-archive  zephyr/kernel/libkernel.a  zephyr/CMakeFiles/offsets.dir/arch/posix/core/offsets/offsets.c.obj  -L/home/cyril/Documents/zephyr_workpsace/iot_aleph/tests/button/build/zephyr  lib/libgtest_main.a  lib/libgtest.a  -lpthread  -Wl,--gc-sections  -Wl,--build-id=none  -Wl,--sort-common=descending  -Wl,--sort-section=alignment  -Wl,-u,_OffsetAbsSyms  -Wl,-u,_ConfigAbsSyms  -lstdc++  -m32  -ldl  -pthread  -lm &amp;&amp; cd /home/cyril/Documents/zephyr_workpsace/iot_aleph/tests/button/build/zephyr &amp;&amp; cmake -E rename zephyr_prebuilt.map zephyr.map &amp;&amp; /usr/bin/objdump -S zephyr.elf &gt; zephyr.lst &amp;&amp; /usr/bin/readelf -e zephyr.elf &gt; zephyr.stat &amp;&amp; /usr/bin/cmake -E copy zephyr.elf zephyr.exe
/usr/bin/ld: i386:x86-64 architecture of input file `lib/libgtest.a(gtest-all.cc.obj)' is incompatible with i386 output
/usr/bin/ld: lib/libgtest.a(gtest-all.cc.obj): in function `testing::internal::AssertHelper::AssertHelper(testing::TestPartResult::Type, char const*, int, char const*)':
...
gtest-all.cc:(.text+0x25bb): undefined reference to `operator new(unsigned long)'
/usr/bin/ld: lib/libgtest.a(gtest-all.cc.obj): in function `testing::AssertionResult::AssertionResult(testing::AssertionResult const&amp;)':
gtest-all.cc:(.text+0x2876): undefined reference to `operator new(unsigned long)'
/usr/bin/ld: lib/libgtest.a(gtest-all.cc.obj): in function `testing::internal::(anonymous namespace)::SplitEscapedString(std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;)':
gtest-all.cc:(.text+0x41d6): undefined reference to `std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::operator[](unsigned long) const'
/usr/bin/ld: gtest-all.cc:(.text+0x41f4): undefined reference to `std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::operator[](unsigned long) const'
/usr/bin/ld: gtest-all.cc:(.text+0x4250): undefined reference to `std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::operator[](unsigned long) const'
/usr/bin/ld: gtest-all.cc:(.text+0x427c): undefined reference to `std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::substr(unsigned long, unsigned long) const'
/usr/bin/ld: gtest-all.cc:(.text+0x42bc): undefined reference to `std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::operator[](unsigned long) const'
/usr/bin/ld: gtest-all.cc:(.text+0x42f0): undefined reference to `std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::substr(unsigned long, unsigned long) const'
/usr/bin/ld: lib/libgtest.a(gtest-all.cc.obj): in function `testing::internal::StringStreamToString(std::__cxx11::basic_stringstream&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;*)':
gtest-all.cc:(.text+0x6c0a): undefined reference to `std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::reserve(unsigned long)'
/usr/bin/ld: lib/libgtest.a(gtest-all.cc.obj): in function `testing::Test::Test()':
gtest-all.cc:(.text+0x7b75): undefined reference to `operator new(unsigned long)'
/usr/bin/ld: lib/libgtest.a(gtest-all.cc.obj): in function `testing::TestInfo::TestInfo(std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;, char const*, char const*, testing::internal::CodeLocation, void const*, testing::internal::TestFactoryBase*)':
gtest-all.cc:(.text+0x86b7): undefined reference to `operator new(unsigned long)'
/usr/bin/ld: gtest-all.cc:(.text+0x8726): undefined reference to `operator new(unsigned long)'
...
</code></pre>
<p>Can someone help me?</p>
<p>Cyril</p>
",https://stackoverflow.com/questions/63039301/unit-testing-c-code-into-zephyr-with-googletest,"['c++', 'unit-testing', 'c++11', 'cmake', 'zephyr-rtos']",1547,False,4,1
Firebase auth unit testing error No Firebase App,"<p>I'm trying to test my <code>firebase auth</code> methods. Auth methods are signin, signout , register, etc.
this are methods i want to perform unit test.</p>
<p>I'm getting error <code>No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()</code></p>
<p>I tried to initialize <code>Firebase.initializeApp</code> in test <code>main</code> method its also doesn't work.</p>
<pre><code> class MockUserRepository extends Mock implements AuthService {
  final MockFirebaseAuth auth;
  MockUserRepository({this.auth});
 }
 class MockFirebaseAuth extends Mock implements FirebaseAuth{}
 class MockFirebaseUser extends Mock implements FirebaseUser{}
 class MockFirebase extends Mock implements Firebase{}
 void main() {
   MockFirebase firebase=MockFirebase();
   MockFirebaseAuth _auth = MockFirebaseAuth();
   BehaviorSubject&lt;MockFirebaseUser&gt; _user = BehaviorSubject&lt;MockFirebaseUser&gt;();
   when(_auth.onAuthStateChanged).thenAnswer((_){
      return _user;
     });
   AuthService _repo = AuthService.instance(auth: _auth);
   group('user repository test', (){
       when(_auth.signInWithEmailAndPassword(email: &quot;email&quot;,password: &quot;password&quot;)).thenAnswer((_)async{
  _user.add(MockFirebaseUser());
});
when(_auth.signInWithEmailAndPassword(email: &quot;mail&quot;,password: &quot;pass&quot;)).thenThrow((){
  return null;
});
test(&quot;sign in with email and password&quot;, () async {
  var signedIn = await _repo.onLogin(email:&quot;testuser@test.com&quot;,password: &quot;123456&quot;);
  expect(signedIn, isNotNull);
  expect(_repo.status, Status.Authenticated);
});

test(&quot;sing in fails with incorrect email and password&quot;,() async {
  var signedIn = await _repo.onLogin(email:&quot;testuser@test.com&quot;,password: &quot;666666&quot;);
  expect(signedIn, false);
  expect(_repo.status, Status.Unauthenticated);
});

test('sign out', ()async{
  await _repo.signout();
  expect(_repo.status, Status.Unauthenticated);
 });
});
} 
</code></pre>
<p>AuthService class</p>
<pre><code>    enum Status { Uninitialized, Authenticated, Authenticating, 
    Unauthenticated }

   class AuthService with ChangeNotifier {
     FirebaseAuth auth = FirebaseAuth.instance;
     FirebaseUser _user;

    FirebaseUser get user =&gt; _user;

    set user(FirebaseUser value) {
      _user = value;
    }

    Status _status = Status.Uninitialized;

    Future&lt;User&gt; getCurrentUser() async {
      User currentUser;
      await FirebaseAuth.instance.authStateChanges().listen((User user) {
      currentUser = user;
      });
      return currentUser;
     }
    AuthService();
    AuthService.instance({this.auth}) {
       //    auth.onAuthStateChanged.listen((user) {
      //      onAuthStateChanged(user);
      //    });
      }

     Future&lt;void&gt; signout() async {
     await auth.signOut();
       }

     Future&lt;User&gt; createAccount({String email, String password}) async {
        try {
           UserCredential userCredential = await 
                  auth.createUserWithEmailAndPassword(
             email: email, password: password);
            return userCredential != null ? userCredential.user : null;
          } on FirebaseAuthException catch (e) {
           showToast(e.message);
          } catch (e) {
          log(e.toString());
           return null;
          }
       }

     Future&lt;User&gt; onLogin({String email, String password}) async {
      try {
        User user;
           await auth
        .signInWithEmailAndPassword(email: email, password: password)
      .then((value) {
        showToast(&quot;Login sucessful&quot;);
       user = value != null ? value.user : null;
      });
      return user;
     } on FirebaseAuthException catch (e) {
      showToast(e.message);
     }
    }

    sendResetPassword({String email}) async {
      bool isSent = false;
      try {
         await auth.sendPasswordResetEmail(email: email).then((value) {
           showToast(&quot;Reset password email sent&quot;);
            isSent = true;
        });
        return isSent;
       } on FirebaseAuthException catch (e) {
           showToast(e.message);
    }
  }

    Future&lt;void&gt; onAuthStateChanged(FirebaseUser user) async {
     if (user == null) {
       _status = Status.Unauthenticated;
        } else {
        _user = user;
        _status = Status.Authenticated;
       }
       notifyListeners();
     }

     Status get status =&gt; _status;

     set status(Status value) {
        _status = value;
        }
   }
</code></pre>
",https://stackoverflow.com/questions/63634609/firebase-auth-unit-testing-error-no-firebase-app,"['android', 'firebase', 'unit-testing', 'flutter', 'firebase-authentication']",4247,True,4,2
AWS SAM CLI Unit testing Lambda Functions NodeJS,"<p>I am using the <a href=""https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html"" rel=""nofollow noreferrer"">SAM CLI</a> to test and deploy AWS Lambda functions. I am trying to run unit tests using Mocha and Chai in NodeJS. The tests are located in the <code>test</code> directory and I can run the tests using the command <code>mocha --recursive</code>.</p>
<p>The problem is I am using environment variables in the tests. My environemnt variables are defined in the   <code>template.yaml</code> file for the SAM CLI. It looks something like this:</p>
<pre><code>  RefreshFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/index.handler
      Runtime: nodejs12.x
      MemorySize: 128
      Timeout: 100
      Environment:
        Variables:
          APP_ID: A
          CLIENT_ID: B 
          CLIENT_SECRET: C 
          AWS_REGION_DB: D
</code></pre>
<p>They are defined here as when I deploy my function they automatically go with it onto AWS too. It also allows me to use the <code>sam local invoke</code> command which runs my lambda function locally using Docker.</p>
<p>Is there anyway that anyone knows that the <code>sam local invoke</code> command can be used to run test cases locally instaed of running the lambda function? Or how to access my environment variables in the <code>template.yaml</code> file from test cases using mocha and chai?</p>
",https://stackoverflow.com/questions/64387505/aws-sam-cli-unit-testing-lambda-functions-nodejs,"['node.js', 'amazon-web-services', 'aws-lambda', 'mocha.js', 'aws-sam']",2173,True,4,3
Angular Unit testing - Reactive Form value not updating,"<p>I am new to angular unit testing. 
Test Scenario: The form view value in the html is equal to the component form value.
The email value is retrieved by a shared value and being used in the component registration form. I could retrieve the email value from the component using the reactive forms, but when trying to access via the native element, it gives empty. 
Below is the component.ts</p>

<pre><code>ngOnit(public serviceEmail) {
    this.assignEmailAvailable();
    this.createRegistration();

    }
assignEmailAvailable() {
 if(service.email){
    this.email = serviceEmail.email;
  }
 }   
createRegistration() {
   this.registerForm = new FormGroup({
       email:new FormControl({value:this.email})
    })
}
</code></pre>

<p>In the component.spec.ts, I am gonna call this function and check whether both values are same.
component.spec.ts</p>

<pre><code> beforeEach(() =&gt; {
    fixture = TestBed.createComponent(RegisterComponent);
    component = fixture.componentInstance;
    service = TestBed.get(serviceEmail);
  });
it('Registration Form Creation', fakeAsync(() =&gt; {
    service.email = ""dsf@gmail.com"";

    fixture.detectChanges();

    component.assignEmailAvailable();
    component.createRegisterForm();

    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
    const email = fixture.debugElement.query(By.css('input[id=""email""]')).nativeElement;
//The value is empty even after creating the form using the component function
    expect(email.value).toBe(component.emailValue);
    });
//THis returns me the value set
    expect(component.registerForm.get('email').value).toBe(component.emailValue);
  }));
</code></pre>
",https://stackoverflow.com/questions/59638229/angular-unit-testing-reactive-form-value-not-updating,"['angular', 'unit-testing', 'karma-jasmine', 'angular-reactive-forms']",8462,True,4,2
Vue unit testing vuex store action with jest,"<p>I'm using Vue version 2.6.11, Vuex version 3.4.0. I have a function in the vuex store (timeTravel) which moves array element from given index to another given index. I have a component with a button that trigger this function. I'm new to unit testing and it's confusing for me.</p>
<p><strong>ActionList.vue component</strong></p>
<pre><code>// other codes

&lt;v-btn color=&quot;primary&quot; dark @click=&quot;timeTravel({from:action.from_index,to:action.to_index,action_list_index:index})&quot;&gt;
  &lt;v-icon left dark&gt;
   mdi-clock-outline
  &lt;/v-icon&gt;
   Submit
&lt;/v-btn&gt;

&lt;script&gt;
import { mapGetters, mapActions } from &quot;vuex&quot;;
export default {
  name: &quot;ActionsList&quot;,
  computed: mapGetters([&quot;commitedActionsList&quot;]),
  methods: {
    ...mapActions([&quot;timeTravel&quot;]),
  },
};
&lt;/script&gt;
</code></pre>
<p><strong>Vuex store</strong></p>
<pre><code>import Vue from &quot;vue&quot;;
import Vuex from &quot;vuex&quot;;
import axios from &quot;axios&quot;;

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    posts: [],
    commitedActions: [],
  },
  getters: {
    postsList: (state) =&gt; state.posts,
    commitedActionsList: (state) =&gt; state.commitedActions,
  },
  mutations: {
    setPosts: (state, posts) =&gt; (state.posts = posts),
    setCommitedActions: (state, commitedActions) =&gt;
      state.commitedActions.push(commitedActions),
  },
  actions: {
    async fetchPosts({ commit }) {
      const response = await axios.get(
        &quot;https://jsonplaceholder.typicode.com/posts/?_limit=5&quot;
      );
      commit(&quot;setPosts&quot;, response.data);
    },
    timeTravel({ commit, getters }, data) {
      var from = data[&quot;from&quot;];
      var to = data[&quot;to&quot;];
      var action_list_index = data[&quot;action_list_index&quot;];
      console.log(from,to,action_list_index);
      var posts_copy = getters.postsList;

      var f = posts_copy.splice(from, 1)[0]; // remove `from` item and store it
      posts_copy.splice(to, 0, f); // insert stored item into position `to`
      commit(&quot;setPosts&quot;, posts_copy);
      
      this.state.commitedActions.splice(action_list_index,1)

    },
  },
  modules: {},
});
</code></pre>
<p>So I want to write a unit test for this timeTravel function with jest. I found some tutorials but it's confusing for me. So far I've come up with this.</p>
<pre><code>import Vuetify from 'vuetify';
import Vuex from 'vuex'
import { createLocalVue ,shallowMount } from '@vue/test-utils'
import ActionsList from '@/components/ActionsList.vue';

let localVue = createLocalVue();

describe('App',()=&gt;{
    let store
    let actions
    let state
    let getters

    beforeEach(()=&gt;{
        localVue.use(Vuex)
        localVue.use(Vuetify)
        state = {posts:[]}

        getters = {
            postsList: (state) =&gt; state.posts,
        }

        actions = {
            timeTravel: jest.fn()
        }

        store = new Vuex.Store({
            state,
            getters,
            actions
        })
    })

    it('dispatches timeTravel', ()=&gt;{
        const wrapper = shallowMount({
            localVue,
            store
        })

        wrapper.find('v-btn').trigger('click')

        expect()
    })
})
</code></pre>
<p>I want to test if timeTravel function is moving element from given index to another given index. So it would be great if someone can point me in the right direction which helps me to write this unit test.</p>
",https://stackoverflow.com/questions/64256875/vue-unit-testing-vuex-store-action-with-jest,"['javascript', 'unit-testing', 'vue.js', 'jestjs', 'vuex']",1046,False,3,0
Angular Material Unit Testing: Mocking a MatSelectChange event,"<p><strong>Description</strong>: I am writing unit tests for the following function:</p>
<pre><code>updateUserStatus(event: MatSelectChange | any, reportID: number) {
    const matOption = (event.source.selected as MatOption);
    const option = matOption.value;
    this.setUserActions(reportID, option.id);
}
</code></pre>
<p><strong>Test Spec</strong></p>
<pre><code>it('should test updateUserStatus', () =&gt; {
    spyOn(component, 'updateUserStatus').and.callThrough();
    spyOn(component, 'setUserActions').and.callFake(() =&gt; {});
    component.updateUserStatus({{MOCK_EVENT_HERE}}, 123456);
    expect(component.updateUserStatus).toHaveBeenCalledTimes(1);
    expect(component.setUserActions).toHaveBeenCalledTimes(1);
});
</code></pre>
<p><strong>Problem</strong>: I am finding it hard to mock the 'event' argument which is an instance of 'MatSelectChange'.</p>
<h2><strong>What have I tried so far?</strong></h2>
<p><strong>1. Copying 'event' value from browser console</strong></p>
<p>This gives me a:</p>
<blockquote>
<p>Uncaught TypeError: Converting circular structure to JSON.</p>
</blockquote>
<p><strong>2. Create a new MatSelectChange instance</strong></p>
<p>The 'MatSelect' constructor requires 12-13 arguments oh my!. Don't know how to instantiate:</p>
<pre><code>const selectChange = new MatSelectChange(new MatSelect(), 'Value');
</code></pre>
<p><em>If any other detail is missing, please let me know if that will help in understanding it better.</em></p>
",https://stackoverflow.com/questions/63637802/angular-material-unit-testing-mocking-a-matselectchange-event,"['angular', 'unit-testing', 'angular-material', 'mocking', 'jasmine']",3184,True,3,1
How to trigger transitionend with Jest unit testing,"<p>I am using angular 8 and Jest for unit testing. I have added a listener for 'transitionend' on the element, but I haven't been able to figure out how to trigger/mock the transitionend event with Jest</p>
<pre><code>this.animatedElement.nativeElement.addEventListener('transitionend', () =&gt; {
      this.transitionEnded = true;
});
</code></pre>
<p>I am trying to create a unit test that tests <code>this.transitionEnded</code> is true</p>
",https://stackoverflow.com/questions/63180216/how-to-trigger-transitionend-with-jest-unit-testing,"['javascript', 'css', 'angular', 'unit-testing', 'jestjs']",1788,True,3,2
Angular Unit testing: Testing http with real APIs,"<p>I am writing unit tests in angular CLI using karma. I want to test http calls with real API and not using mocks. Because API models are changing frequently and I'm looking for a way to be sure about my endpoint responses. Is there any solution or sample code?</p>
<p>Here is on my services that I want to test with real API:</p>
<pre class=""lang-js prettyprint-override""><code>  getCodeRequest(phone: string) {

    let params = new HttpParams();
    params = params.append('phone', String(phone));

    return this.http.get('/auth/request', { params });
  }
</code></pre>
<p>I will appreciate any tip or point.</p>
",https://stackoverflow.com/questions/65493051/angular-unit-testing-testing-http-with-real-apis,"['angular', 'api', 'unit-testing', 'testing', 'karma-jasmine']",1203,True,3,1
Unit testing Directive with arguments in Angular 2+,"<p>I have a directive which changes background color of an element during mouse over as below.</p>

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

@Directive({
  selector: '[appHighlightme]'
})
export class HighlightmeDirective {

  @Input('appHighlightme') color : string
  constructor(private el:ElementRef) { }

  @HostListener('mouseenter') onMouseEnter(){
    this.highlight(this.color || 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave(){
    this.highlight('inherit');
  }

  highlight(color){
    this.el.nativeElement.style.backgroundColor = color;
  }
}
</code></pre>

<p>I was trying to write a unit test case for this directive as below </p>

<pre><code>import { HighlightmeDirective } from './highlightme.directive';
import {ChangeDetectionStrategy, Component, DebugElement, ViewChild} from '@angular/core';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';

@Component({
  selector: 'my-test-component',
  template: '&lt;a [appHighlightme]=""color"" &gt;test&lt;/a&gt;'
})
export class TestComponent {
  color:string = 'blue';
}

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

  let component: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;;
  let inputEl: DebugElement;

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

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    inputEl = fixture.debugElement.query(By.directive(HighlightmeDirective));

  });

  it('detect hover changes', () =&gt; {
    inputEl.triggerEventHandler('mouseenter', {});
    fixture.detectChanges();
    expect(inputEl.nativeElement.style.backgroundColor).toBe(component.color);
    inputEl.triggerEventHandler('mouseleave', {});
    fixture.detectChanges();
    expect(inputEl.nativeElement.style.backgroundColor).toBe('inherit');
  });

  it('should create an instance', () =&gt; {
    const directive = new HighlightmeDirective(inputEl);
    expect(directive).toBeTruthy();
  });
});
</code></pre>

<p>The directive is working fine in other components. it accepts a color argument variable defined in the ts file and use it as the bg color when hovering the element. But when I'm trying to unit test the same, the color argument passed form the TestComponent is not getting detected by the directive and the test case is failing with the following error message.</p>

<p>Error: Expected 'yellow' to be 'blue'. - As yellow is set as the default hover color</p>
",https://stackoverflow.com/questions/61359262/unit-testing-directive-with-arguments-in-angular-2,"['angular', 'unit-testing', 'karma-jasmine', 'angular2-directives', 'mouseenter']",5089,True,3,2
Laravel unit testing automatic dependency injection not working?,"<p>With Laravel Framework 5.8.36 I'm trying to run a test that calls a controller where the __construct method uses DI, like this:</p>

<pre><code>class SomeController extends Controller {

public function __construct(XYZRepository $xyz_repository)
{
    $this-&gt;xyz_repository = $xyz_repository;
}

public function doThisOtherThing(Request $request, $id)
{
    try {
        return response()-&gt;json($this-&gt;xyz_repository-&gt;doTheRepoThing($id), 200);
    } catch (Exception $exception) {
        return response($exception-&gt;getMessage(), 500);
    }
}
}
</code></pre>

<p>This works fine if I run the code through the browser or call it like an api call in postman, but when I call the <code>doThisOtherThing</code> method from my test I get the following error:</p>

<blockquote>
  <p>ArgumentCountError: Too few arguments to function App\Http\Controllers\SomeController::__construct(), 0 passed in /var/www/tests/Unit/Controllers/SomeControllerTest.php on line 28 and exactly 1 expected</p>
</blockquote>

<p>This is telling me that DI isn't working for some reason when I run tests. Any ideas? Here's my test:</p>

<pre><code>public function testXYZShouldDoTheThing()
{
    $some_controller = new SomeController();
    $some_controller-&gt;doThisOtherThing(...args...);
    ...asserts...
}
</code></pre>

<p>I've tried things like using the bind and make methods on app in the setUp method but no success:</p>

<pre><code>public function setUp(): void
{
    parent::setUp();
    $this-&gt;app-&gt;make('App\Repositories\XYZRepository');
}
</code></pre>
",https://stackoverflow.com/questions/60497603/laravel-unit-testing-automatic-dependency-injection-not-working,"['laravel', 'dependency-injection', 'phpunit']",2770,True,3,2
StateFlow : unit testing of StateFlow in Kotlin Multiplaform,"<p>Has anyone tried StateFlow in KMP? If yes, can someone guide me on how can I write Unit Test for StateFlow? I am following MVVM architecture and am trying to create a common ViewModel that can be used by any platform.</p>
<p>In below example, I am trying to test <strong>LoginViewModel</strong> from its method <strong>login</strong>.</p>
<p><strong>LoginViewModel.kt:</strong></p>
<pre><code>@ExperimentalCoroutinesApi
class LoginViewModel(private val loginViewState: LoginViewState, private val loginService: LoginService) {
    private val _apiStateFlow = MutableStateFlow(loginViewState)
    val stateFlow: StateFlow&lt;LoginViewState&gt; = _apiStateFlow
    private val _EMAIL_REGEX = &quot;^[A-Za-z](.*)([@]{1})(.{1,})(\\.)(.{1,})&quot;
    suspend fun login(email: String, password: String) {
        if (isFormValid(email, password)) {
            _apiStateFlow.value = loginViewState.copy(isLoginApiLoading = true)
            runCatching {
                loginService.login(email, password)
            }.onSuccess {
                loginViewState.copy(isLoginApiLoading = false, loginResponse = it)
            }.onFailure {
                loginViewState.copy(isLoginApiLoading = false, errorResponse = ErrorResponse(it.message.orEmpty()))
            }
        }
    }
    fun isFormValid(email: String, password: String): Boolean {
        val isEmailValid = email.isEmailValid()
        val isPasswordValid = password.isPasswordValid()
        _apiStateFlow.value = loginViewState.copy(isValidEmail = isEmailValid, isValidPassword = isPasswordValid)
        return isEmailValid &amp;&amp; isPasswordValid
    }
    private fun String.isEmailValid() = _EMAIL_REGEX.toRegex().matches(this)
    private fun String.isPasswordValid() = length in 6..14
}
data class LoginViewState(
    val email: String = &quot;&quot;,
    val password: String = &quot;&quot;,
    val isValidEmail: Boolean = false,
    val isValidPassword: Boolean = false,
    val isLoginApiLoading: Boolean = false,
    val loginResponse: LoginResponse? = null,
    val errorResponse: ErrorResponse? = null
)
</code></pre>
<p><strong>Service.kt:</strong></p>
<pre><code>expect val platformEngine: HttpClientEngineFactory&lt;HttpClientEngineConfig&gt;
val myHttpClient: HttpClient
get() = HttpClient(platformEngine) {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
    install(Logging) {
        level = LogLevel.ALL
    }
    expectSuccess = false
    HttpResponseValidator {
        validateResponse { response: HttpResponse -&gt;
            println(&quot;Response: $response&quot;)
            val statusCode = response.status.value
            when (statusCode) {
                in 300..399 -&gt; throw RedirectResponseException(response)
                in 400..499 -&gt; throw ClientRequestException(response)
                in 500..599 -&gt; throw ServerResponseException(response)
            }
            if (statusCode &gt;= 600) {
                throw ResponseException(response)
            }
        }
        handleResponseException { cause: Throwable -&gt;
            println(&quot;Exception: $cause&quot;)
        }
    }
    defaultRequest {
        url {
            host = &quot;127.0.0.1:8080/&quot;
            protocol = URLProtocol.HTTP
        }
        timeout {
            connectTimeoutMillis = 10000
            requestTimeoutMillis = 10000
            socketTimeoutMillis = 10000
        }
    }
}
</code></pre>
<p><strong>LoginService.kt:</strong></p>
<pre><code>class LoginService(private val httpClient: HttpClient) {
    suspend fun login(email : String, password : String): LoginResponse = httpClient.post {
        body = LoginRequest(email, password)
    }
}
</code></pre>
<p><strong>LoginReqRes.kt:</strong></p>
<pre><code>data class LoginRequest(val email: String = &quot;&quot;, val password: String = &quot;&quot;)
data class LoginResponse(val name: String = &quot;&quot;, val age: Int = 0, val email: String = &quot;&quot;)
data class ErrorResponse(val message: String)
</code></pre>
",https://stackoverflow.com/questions/62900787/stateflow-unit-testing-of-stateflow-in-kotlin-multiplaform,"['unit-testing', 'kotlin', 'ktor', 'kotlin-multiplatform']",595,False,3,0
Accessing Files In webapp Folder During Unit Testing,"<p>I've seen several variations of this question on StackOverflow, but none describe my scenario exactly, or offer a solution that works for me.</p>

<p>I'm building a Java EE web game.  I'm using JUnit to do unit testing during the build process.  In my webapp folder, I have assets that users access via HTTP GET requests.  In my source code, I have corresponding Java classes that implement the logic of those assets.</p>

<p>For example, I have a class called CookingPot, which implements the logic for a cooking pot in my game.  In the webapp folder, I have a files that provide media and content for cooking pots to the user, for example:</p>

<pre><code>webapp/assets/items/CookingPot.svg (an image of the cooking pot)
webapp/assets/items/CookingPot.html (an HTML description of the cooking pot)
</code></pre>

<p>During unit testing, I'd like to make sure that for every game item (in this example, the CookingPot item), there is an SVG and HTML file in the correct place in the webapp folder.</p>

<p>How can I implement this test?  The JUnit tests are executed in the Maven build environment, which does not provide a Tomcat server to test against, so accessing them via HTTP won't work.  I've tried:</p>

<pre><code>URL svg = getClass().getResource(""/webapp/assets/items/CookingPot.svg"");
URL svg = getClass().getResource(""webapp/assets/items/CookingPot.svg"");
</code></pre>

<p>But those return null.</p>

<p>I have a feeling that there is something simple I'm missing here, but I don't know what it is.  Surely there's got to be a way to test that these files exist during the build process?</p>

<p>Thanks in advance for any help!</p>
",https://stackoverflow.com/questions/59767662/accessing-files-in-webapp-folder-during-unit-testing,"['junit', 'web-applications', 'java-ee-8']",314,True,2,1
Android unit testing issues with dagger2 and kotlin,"<p>I am trying to create a  dagger component interface in the test folder of android,but after Dagger is done with the generated class its show an error as ""Cannot access TestComponent which is a supertype of com.example.animals.di.DaggerTestAppComponent.Check your module classpath for missing or conflicting dependency"".Can you please help me to fix this issue.</p>

<pre><code>gradle dependecies:
def lifeCycleExtensionVersion = '1.1.1'
def supportVersion = '28.0.0'
def retrofitVersion = '2.3.0'
def glideVersion = '4.9.0'
def rxJavaVersion = '2.1.1'
def navVersion = '2.1.0-alpha05'
def daggerVersion = '2.14.1'
def mockitoVersion = '2.11.0'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version""
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation ""com.android.support:design:$supportVersion""
    implementation ""android.arch.lifecycle:extensions:$lifeCycleExtensionVersion""

    implementation ""androidx.navigation:navigation-fragment-ktx:$navVersion""
    implementation ""androidx.navigation:navigation-ui-ktx:$navVersion""

    implementation ""com.squareup.retrofit2:retrofit:$retrofitVersion""
    implementation ""com.squareup.retrofit2:converter-gson:$retrofitVersion""
    implementation ""com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion""

    implementation ""io.reactivex.rxjava2:rxjava:$rxJavaVersion""
    implementation ""io.reactivex.rxjava2:rxandroid:$rxJavaVersion""

    implementation ""com.github.bumptech.glide:glide:$glideVersion""

    implementation ""com.android.support:palette-v7:$supportVersion""


    implementation ""com.google.dagger:dagger:$daggerVersion""
    implementation ""com.google.dagger:dagger-android-support:$daggerVersion""
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    kapt ""com.google.dagger:dagger-compiler:$daggerVersion""
    kapt ""com.google.dagger:dagger-android-processor:$daggerVersion""


    testImplementation ""org.mockito:mockito-inline:$mockitoVersion""
    testImplementation ""android.arch.core:core-testing:1.1.1""
    kaptTest ""com.google.dagger:dagger-compiler:$daggerVersion""

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
 }

TestAppComponent:
   package com.example.animals.di

 import com.example.animals.base.BaseTest
 import dagger.Component
 import javax.inject.Singleton

@Singleton
@Component(modules = [])
interface TestAppComponent {
   fun inject(baseTest: BaseTest)
}
</code></pre>

<p>BaseTest:
        package com.example.animals.base</p>

<pre><code> import android.app.Application
 import com.example.animals.di.DaggerTestAppComponent
 import org.junit.Before
 import org.mockito.Mockito

open class BaseTest {

    val application = Mockito.mock(Application::class.java)

    @Before
     fun setUp() {
     configureDi()

    }

    private fun configureDi() {
       var testAppComponent = DaggerTestAppComponent.builder().build()

        testAppComponent.inject(this)
    }
 }
</code></pre>
",https://stackoverflow.com/questions/60985281/android-unit-testing-issues-with-dagger2-and-kotlin,"['android', 'unit-testing', 'kotlin', 'dagger-2']",706,True,2,1
Ember Octane: Unit testing async action on controller,"<p>Having the following controller and tests:</p>

<p>app/controllers/application.js</p>

<pre class=""lang-js prettyprint-override""><code>import Controller from '@ember/controller';
import { action } from '@ember/object';

export default class ApplicationController extends Controller {
  flag = false;

  @action
  raiseFlag() {
    this.flag = true;
  }

  @action
  async raiseFlagAsync() {
    await new Promise(resolve =&gt; setTimeout(resolve, 1000));
    this.flag = true;
  }
}
</code></pre>

<p>tests/unit/controllers/application-test.js</p>

<pre class=""lang-js prettyprint-override""><code>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Controller | application', function(hooks) {
  setupTest(hooks);

  test('it raises flag', function(assert) {
    let controller = this.owner.lookup('controller:application');
    assert.equal(controller.flag, false);
    controller.send('raiseFlag');
    assert.equal(controller.flag, true);
  });

  test('it raises flag asyncronously', async function(assert) {
    let controller = this.owner.lookup('controller:application');
    assert.equal(controller.flag, false);
    await controller.send('raiseFlagAsync');
    assert.equal(controller.flag, true);
  });
});
</code></pre>

<p>The first test case passes.
The second test case fails (the async one)</p>

<p>What is the ember-octane way of waiting for the async action?</p>
",https://stackoverflow.com/questions/59881057/ember-octane-unit-testing-async-action-on-controller,"['javascript', 'testing', 'ember.js', 'async-await', 'ember-octane']",606,True,2,2
Unit testing controller that returns ContentResult list object,"<p>I am setting up a unit test and having trouble.  I've seen the hello world examples, however my return type is more complex.  </p>

<p>My controller is returning a list of objects. I am getting back an object with an array of objects as below:</p>

<pre><code>Public Class ItemClass
{
    public int Id,
    public string Name
}

Public ContentResult GetItems(string criteria){
  .
  .
  .
  // List&lt;ItemClass&gt; myItemClass (this will containa list of several ItemClass)
  // ItemInfo myItemInfo (this will contain a single object similar to the return data I have outlined below)
  var model = new { ItemsList = myItemList, ItemInfo = myItemInfo}
  return Content( [here i convert my `model` to json data]);
};


.
.
.

//TestMethod starts here:


//setup code

//act
var result = controller.GetList(criteria)

//assert
    //this is where I'm having trouble

// result.content looks like this:  ""{""\""itemList\"":[{\""id\"":1,\""name\"":\""Item 1 Name\""},{\""id\"":2,\""name\"":\""Item 2 Name\""}],""listInfo"":{""info1"":1,""info2"":""bla""}}""
</code></pre>

<p>How can I deserialize result.content into an list of type <code>ItemClass</code> so that I can do assertions against it?  For example, I would like to assert that the result is not null, that there is a count of 2 items in the result and I would also want to test the existence of specific ids in the result. If there is a better way to do this type of test I'm open to suggestions.</p>
",https://stackoverflow.com/questions/60369202/unit-testing-controller-that-returns-contentresult-list-object,"['c#', 'unit-testing', 'mstest']",536,True,2,1
Unit Testing framework for Embedded platform in C++?,"<p>I am working on an embedded systems project using ACE Framework and all the development is done using eclipse IDE. I am looking for a good testing framework.
Basically the project involves parsing of incoming data and I am searching for a unit testing framework which suits my project. What are my options here?</p>
",https://stackoverflow.com/questions/59818467/unit-testing-framework-for-embedded-platform-in-c,"['c++', 'eclipse', 'unit-testing', 'ace']",994,True,2,2
Should Match Snapshot jest unit testing with Angular,"<p>Trying to do the Snapshot test with Jest in angular 10 and test application is failed</p>
<pre><code>expect(received).toMatchSnapshot()

    Snapshot name: `DestinationComponent Should Match Snapshot 1`

    - Snapshot  - 5
    + Received  + 5

    @@ -12,15 +12,15 @@
        formGroupDirective={[Function FormGroupDirective]}
        index=&quot;0&quot;
        listSvg={[Function Object]}
        loading={[Function Boolean]}
        ngForm={[Function ElementRef]}
    -   onCancelled={[Function EventEmitter]}
    -   onLoaded={[Function EventEmitter]}
    -   onServerError={[Function EventEmitter]}
    -   onSubmitted={[Function EventEmitter]}
    -   onValidationError={[Function EventEmitter]}
    +   onCancelled={[Function EventEmitter_]}
    +   onLoaded={[Function EventEmitter_]}
    +   onServerError={[Function EventEmitter_]}
    +   onSubmitted={[Function EventEmitter_]}
    +   onValidationError={[Function EventEmitter_]}
        prefilledActions={[Function Object]}
        router={[Function Router]}
        sessionMapApi={[Function Object]}
        sub={[Function Subscriber]}
        submitted=&quot;false&quot;

      73 | 
      74 |   it('Should Match Snapshot', async () =&gt; {
    &gt; 75 |     (expect(fixture) as any).toMatchSnapshot();
         |                              ^
      76 |   });
      77 | });
      78 | 

      at src/app/pages/destination/destination.component.spec.ts:75:30
      at node_modules/tslib/tslib.js:114:75
      at new ZoneAwarePromise (node_modules/zone.js/dist/zone.js:913:33)
      at Object.__awaiter (node_modules/tslib/tslib.js:110:16)
      at src/app/pages/destination/destination.component.spec.ts:74:42
      at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:386:30)
      at ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:117:43)
      at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:385:36)
      at Zone.run (node_modules/zone.js/dist/zone.js:143:47)
</code></pre>
<p><strong>date-selection.component.spec.ts</strong></p>
<pre><code>describe('DateSelectionComponent', () =&gt; {
  let component: DateSelectionComponent;
  let fixture: ComponentFixture&lt;DateSelectionComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [DateSelectionComponent, SafePipe],
      imports: [
        SharedModule,
        NgReduxTestingModule,
        RouterTestingModule.withRoutes([])
      ],
      providers: [
        {
          provide: PageAPIActions, useValue: { setPageState() { } }
        }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(DateSelectionComponent);
    component = fixture.componentInstance;
    Object.defineProperties(component, {
      page$: {
        value: of('value'),
        writable: true
      },
      page: {
        value: { destination: 'value' },
        writable: true
      },
      startDate: {
        value: new NgbDate(2019, 2, 27),
        writable: true
      },
      minDate: {
        value: new NgbDate(2019, 2, 27),
        writable: true
      }
    });
    fixture.detectChanges();
  });

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

  it('Should Match Snapshot', async () =&gt; {
    (expect(fixture) as any).toMatchSnapshot();
  });
});
</code></pre>
<p>I can see the .snap file is created, I am new to the jest unit testing, can anyone please help me what I am doing wrong, not able to find out the mistake</p>
",https://stackoverflow.com/questions/63887446/should-match-snapshot-jest-unit-testing-with-angular,"['javascript', 'angular', 'typescript', 'jestjs', 'angular-jest']",935,True,2,1
Linker error with Unity (C unit testing framework),"<p>I've littered through Stackoverflow trying to get Unity unit test framework (<a href=""https://www.throwtheswitch.org/unity"" rel=""nofollow noreferrer"">https://www.throwtheswitch.org/unity</a>) linked and built on CMAKE so that I can write unit tests but I keep hitting this same error:</p>

<pre><code>Undefined symbols for architecture x86_64:
  ""_setUp"", referenced from:
      _UnityDefaultTestRun in libunity.a(unity.c.o)
  ""_tearDown"", referenced from:
      _UnityDefaultTestRun in libunity.a(unity.c.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [bin/test_problem2_59.exe] Error 1
make[1]: *** [tests/CMakeFiles/test_problem2_59.exe.dir/al
</code></pre>

<p>I have documented my final attempt here <a href=""https://github.com/aamarin/computer_systems/tree/dev"" rel=""nofollow noreferrer"">https://github.com/aamarin/computer_systems/tree/dev</a> with the latest commit being the unstable commit.  I'm not sure what else I'm missing in computer_systems/tests/CMakeLists.txt to get this working.  Just looking for some guidance and maybe an explanation I might be missing from here <a href=""https://gitlab.com/CLIUtils/modern-cmake/-/blob/master/examples/extended-project/src/CMakeLists.txt"" rel=""nofollow noreferrer"">https://gitlab.com/CLIUtils/modern-cmake/-/blob/master/examples/extended-project/src/CMakeLists.txt</a>.  Guidance on better structuring my folder structure is helpful as well.</p>
",https://stackoverflow.com/questions/61114392/linker-error-with-unity-c-unit-testing-framework,"['c', 'unit-testing', 'cmake', 'unity-test-framework']",600,True,2,1
Typesafe Config: Overriding values for unit testing purposes,"<p>In a unit test of a class that requires a <code>config: Config</code>, I'd like to declare visually (not in a config file located in another place) the assumed configurations settings for the test.</p>

<p>So for example, I'd like to do something like this:</p>

<pre><code>class myClassSpec extends AnyFlatSpec{
  val myTestingConfigForThisTestCase = 3L
  val config = ConfigFactory.load()
                .withValue(""my-config-path"", myTestingConfigForThisTestCase)
  ...
}
</code></pre>

<p>However, <code>withValue</code> expects a <code>ConfigValue</code> and there seem to be no implicit conversions between basic types and that.</p>

<p>Any ideas on a simple solution?</p>
",https://stackoverflow.com/questions/62272967/typesafe-config-overriding-values-for-unit-testing-purposes,"['scala', 'unit-testing', 'typesafe-config']",2366,True,2,1
Unit testing of HttpsCallable cloud functions - online mode,"<p>I am designing a backend api (for android and iOS apps) around <a href=""https://firebase.google.com/docs/functions/callable"" rel=""nofollow noreferrer"">HttpsCallable</a> cloud functions. It becomes quite cumbersome to test them through the app, so I wish to switch to unit testing the functions (before production deployment) using the <code>firebase-functions-test</code> tool. I have been following this <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">unit testing tutorial</a>. </p>

<p>I am having some issues running the unit tests in online mode. Let me provide some details.  </p>

<p>Here is my `package.json' content:</p>

<pre><code>{
  ""name"": ""functions"",
  ""description"": ""Cloud Functions for Firebase"",
  ""scripts"": {
    ""lint"": ""eslint ."",
    ""serve"": ""firebase serve --only functions"",
    ""shell"": ""firebase functions:shell"",
    ""start"": ""npm run shell"",
    ""deploy"": ""firebase deploy --only functions"",
    ""logs"": ""firebase functions:log"",
    ""test"": ""mocha --reporter spec""
  },
  ""engines"": {
    ""node"": ""8""
  },
  ""dependencies"": {
    ""@google-cloud/tasks"": ""^1.9.0"",
    ""@googlemaps/google-maps-services-js"": ""^2.0.2"",
    ""chai"": ""^4.2.0"",
    ""firebase-admin"": ""^8.6.0"",
    ""firebase-functions"": ""^3.3.0"",
  },
  ""devDependencies"": {
    ""eslint"": ""^5.12.0"",
    ""eslint-plugin-promise"": ""^4.0.1"",
    ""firebase-functions-test"": ""^0.1.7"",
    ""mocha"": ""^7.1.1""
  },
  ""private"": true
}
</code></pre>

<p>I am using google APIs (<em>Directions</em>, <em>Geocoding</em> etc) from firebase backend, therefore to be able to access them while running my tests, I configured my tests located at <code>test/index.test.js</code> as recommended in the <em>Unit testing tutorial</em> as follows:</p>

<pre><code>const firebaseConfig = {
  apiKey: ...,
  authDomain: ...,
  databaseURL: ""https://my-project.firebaseio.com"",
  projectId: ""my-project"",
  storageBucket: ""my-project.appspot.com"",
  messagingSenderId: ********,
  appId: *********
};


const test = require('firebase-functions-test')(firebaseConfig
  , 'path_to_json_keyfile/myproject.json');
</code></pre>

<p>Below is the sample test code. Note that all my callable functions return <a href=""https://firebase.google.com/docs/reference/node/firebase.functions.HttpsError"" rel=""nofollow noreferrer"">HttpsError</a>, and the test below, simply checks for the <code>code</code> field of <code>HttpsError</code>, if its <code>ok</code>, the test passes. The functions I am testing reside in a separate <code>rides.js</code> file, which the <code>index.js</code> exports as <code>exports.rides = require(./rides.js)</code> (not shown below)</p>

<pre><code>const chai = require('chai');
const assert = chai.assert;

describe('Cloud functions', () =&gt; {
  let rideFunctions;
  before(() =&gt; {
    rideFunctions = require('../index.js');
  });

  after(() =&gt; {
    test.cleanup();
  });

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

    it('should return ok', async () =&gt; {
      data = {
        riderType: 1,
        pickup_lat: 37.0,
        pickup_lng: -122,
        dropoff_lat: 37.01,
        dropoff_lng: -122.01,
        scheduledTime: 1585939000,
        ts: 1585939000,
        tz_id: ""uslax""
      }

      context = {
        auth: {
          uid: AUTH_ID_FOR_USER_ACCOUNT
        }
      };

      const wrappedGetRideEstimate = test.wrap(rideFunctions.rides.getRideEstimate);

      let httpsError = await wrappedGetRideEstimate(data, context);
      return assert.equal(httpsError.code, 'ok');
    });


  })

  describe('testCallable', () =&gt; {
    it('should return ok', async () =&gt; {
      data = {}
      context = {}
      const wrappedTestCallable = test.wrap(rideFunctions.rides.testCallable);
      let httpsError = await wrappedTestCallable(data, context);
      return assert.equal(httpsError.code, 'ok');

    })
  })


})
</code></pre>

<p><strong>Problem</strong></p>

<ol>
<li>My simple <code>testCallable</code> function of the form </li>
</ol>

<pre><code>exports.testCallable = functions.https.onCall((data, context) =&gt; {
    console.log('testCallable');
    return new functions.https.HttpsError('ok', '', '');
})
</code></pre>

<p>passes the test (as expected) but inexplicably, it seems it is running in the offline mode, as there is no record of it on cloud function logs in Firebase Console. Also, if I disable connectivity of my laptop, the test result remains the same suggesting that somehow this function is running in the offline mode. </p>

<ol start=""2"">
<li><p>My <code>getRideEstimate</code> function which calls the google <code>Directions</code> API, returns a lengthy <code>400</code> error indicating some issue with forming the request to Directions API. I don't know if this error is related to the first problem, but since the Directions API call is embedded deeper inside the <code>getRideEstimate</code> function, it does suggest that the function is getting called, but somehow the API call is failing. </p></li>
<li><p>Is there any other way to test HttpsCallable functions in online mode?</p></li>
</ol>
",https://stackoverflow.com/questions/61037187/unit-testing-of-httpscallable-cloud-functions-online-mode,"['javascript', 'firebase', 'google-cloud-functions', 'firebase-tools', 'google-directions-api']",987,False,2,1
Android: Mock a Context for Fragment unit testing,"<p>I have a fragment that uses the delegation pattern when a button is clicked. </p>

<pre class=""lang-kotlin prettyprint-override""><code>class FutureMeetingEventViewFragment @Inject constructor(): Fragment() {

    @Inject
    lateinit var bundleUtilityModule: BundleUtilityModule
    lateinit var parcelableMeetingEvent: ParcelableMeetingEvent

    private var delegate: IEventDetailsDelegate? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)

        if(context is IEventDetailsDelegate) {
            delegate = context
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)

        val binding: ViewDataBinding = DataBindingUtil.inflate&lt;ViewDataBinding&gt;(inflater, R.layout.layout_future_meeting_event_fragment, container,false)
        DaggerUtilityModuleComponent.create().inject(this)
        this.parcelableMeetingEvent = this.bundleUtilityModule.getTypeFromBundle(BundleData.MEETING_EVENT_DATA.name, arguments)

        binding.setVariable(BR.meetingEvent, this.parcelableMeetingEvent)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.setCTAClickEvent()
    }

    private fun setCTAClickEvent() {
        future_event_card.setOnClickListener {
            delegate?.onEventClicked(this, this.parcelableMeetingEvent)
        }
    }
}
</code></pre>

<p>A problem I can see in the unit test is that when I click the button, because the IEventDetailsDelegate field will be null, the test will always fail. My unit test so far is simply testing if the correct data is displayed on the view:</p>

<pre class=""lang-kotlin prettyprint-override""><code>
@RunWith(AndroidJUnit4::class)
class GivenAFutureMeetingEventFragmentIsDisplayed  {

    private var fragmentId: Int = 0

    private lateinit var fragmentArgs: Bundle
    private lateinit var scenario: FragmentScenario&lt;FutureMeetingEventViewFragment&gt;

    @Before
    fun setup() {
        fragmentId = FutureMeetingEventViewFragment().id

        fragmentArgs = Bundle()
        fragmentArgs.apply {
            putParcelable(BundleData.MEETING_EVENT_DATA.name, ParcelableMeetingEvent(
                ""Test Description"",
                ""Test Summary"",
                ""12344556"",
                DateTime(""2020-03-14T17:57:59+00:00""),
                DateTime(""2020-03-14T18:57:59+00:00""),
                ""Somewhere across the universe""
            ))
        }

        scenario = launchFragmentInContainer&lt;FutureMeetingEventViewFragment&gt;(
            fragmentArgs,
            fragmentId
        )
    }

    @Test
    fun thenACorrectlyMappedMeetingEventShouldBePassedToTheFragment() {
        onView(withId(R.id.spec_future_meeting_event_start_day)).check(matches(withText(""Saturday"")))
        onView(withId(R.id.spec_future_meeting_event_start_time)).check(matches(withText(""5:57:59 PM"")))
        onView(withId(R.id.spec_future_meeting_event_end_time)).check(matches(withText(""6:57:59 PM"")))
        onView(withId(R.id.spec_future_meeting_event_summary)).check(matches(withText(""Test Summary"")))
        onView(withId(R.id.spec_future_meeting_event_description)).check(matches(withText(""Test Description"")))
    }

    @Test
    fun thenTheContainerShouldBeClickable() {
        onView(withId(R.id.future_event_card)).check(matches(isClickable()))
    }
}

</code></pre>

<p>I guess there's two questions in this post: </p>

<ol>
<li>Can I mock out a context that implements the IEventDetailsDelegate and assign it to my mock fragment? </li>
<li>Should I test the event on an actual activity that implements the interface? </li>
</ol>
",https://stackoverflow.com/questions/61437363/android-mock-a-context-for-fragment-unit-testing,"['android', 'android-fragments', 'kotlin', 'android-junit']",1034,False,2,0
Unit testing Kafka streams with groupByKey/windowedBy/count,"<p>My question is similar to: <a href=""https://stackoverflow.com/questions/57480927/how-to-unit-test-a-kafka-stream-application-that-uses-session-window"">How to unit test a kafka stream application that uses session window</a></p>

<p>Topology looks like</p>

<pre><code>.filter()
.groupByKey()
.windowedBy(SessionWindows.with(30).grace(5))
.count()
.toStream()
.selectKey((k, v)-&gt;k.key())
.to(outTopic)
</code></pre>

<p>When I run this application, and send data like:</p>

<pre><code>key1, {somejson}
key1, {somejson}
key1, {somejson}
</code></pre>

<p>In the output topic, I correctly see the record after 30 seconds as expected</p>

<pre><code>key1, 3
</code></pre>

<p>When I write a unit test for the same (after reading the other question about advancedWallClockTime, my test code looks like:</p>

<pre><code>final Instant now = Instant.now();

// Send messages with one second difference timestamps
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, ""key1"", json, now.toEpochMilli()));
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, ""key1"", json, now.plusMillis(1000L).toEpochMilli()));
testDriver.pipeInput(consumerRecordFactory.create(inputTopicName, ""key1"", json, now.plusMillis(2000L).toEpochMilli()));

testDriver.advanceWallClockTime(35000L)
</code></pre>

<p>Then I try to compare the results</p>

<pre><code>ProducerRecord&lt;String, Long&gt; life = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
Assert.assertEquals(lifevalue, Long.valueOf(3));
</code></pre>

<p>I expect it to be 3 but it seems its always 1. But if I write something like:</p>

<pre><code>List&lt;ProducerRecord&lt;String, Long&gt;&gt; expectedList = Arrays.asList(
  new ProducerRecord&lt;String, Long&gt;(outputTopicName, ""key1"", 1L),
  new ProducerRecord&lt;String, Long&gt;(outputTopicName, ""key1"", 2L),
  new ProducerRecord&lt;String, Long&gt;(outputTopicName, ""key1"", 3L)
);

for (ProducerRecord&lt;String, Long&gt; expected : expectedList) {
    ProducerRecord&lt;String, Long&gt; actual = testDriver.readOutput(outputTopicName, stringSerde.deserializer(), longSerde.deserializer());
    Assert.assertEquals(expected.value(),  actual.value());
}
</code></pre>

<p>then my test passes.</p>

<p>What I am doing wrong? Eventually, I would like to add data for two different keys and test that both of them are coming with count: 3L.</p>
",https://stackoverflow.com/questions/62075992/unit-testing-kafka-streams-with-groupbykey-windowedby-count,"['apache-kafka', 'apache-kafka-streams']",350,True,2,1
ag-grid API Undefined in Angular unit testing,"<p>I am writing the unit test case for Ag-grid in angular.</p>
<p><strong>test.component.ts:</strong></p>
<pre class=""lang-js prettyprint-override""><code>public gridApi: GridApi; 
public gridColumnApi;

constructor(private service: Service) {
 this.initializeAgGrid(); // this method just initializing the grid
}

ngOnInit(): void {
 this.setHraDashboardData();
}

onGridReady(params) {
 this.gridApi = params.api;
 this.gridColumnApi = params.columnApi;
 this.gridApi.sizeColumnsToFit();
}

setHraDashboardData() {
 this.service.getData(1).then((data) =&gt; {
   this.uiData = data;
   this.rowData = this.generateRowData(this.data); // this method writing some logic for UI
   this.gridApi.setRowData(this.rowData);
 });
}
</code></pre>
<p><strong>test.component.spec.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>beforeEach(() =&gt; {
  fixture = TestBed.createComponent(HraFormComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('grid API is available after `detectChanges`', async() =&gt; {
  await fixture.whenStable().then(()=&gt;{
    fixture.detectChanges();
    const elm = fixture.debugElement.nativeElement;
    const grid = elm.querySelector('#Grid');
    const firstRowCells = grid.querySelectorAll('div[row-id=&quot;0&quot;] div.ag-cell-value');
    const values = Array.from(firstRowCells).map((cell: any) =&gt; cell.textContent.trim());

    // assert
    expect(component.rowData[0].title).toEqual(values[0]);
  });
});
</code></pre>
<p>Now above test case is getting failed to due to <code>component.gridApi</code> is <code>undefined</code>, so it's not able to assign value for the grid <code>this.gridApi.setRowData(this.rowData)</code>.</p>
",https://stackoverflow.com/questions/65449177/ag-grid-api-undefined-in-angular-unit-testing,"['angular', 'unit-testing', 'ag-grid', 'ag-grid-angular']",3659,True,2,1
How to Mock GetDiscoveryDocumentAsync When Unit Testing HttpClient?,"<p>I'm trying to write some unit tests for a HttpClient service, and have run into an issue when trying to mock out parts of the code within my GetAccessToken() function. </p>

<p>The service takes in an IHttpClientFactory. From the reading I've done so far it seems that to mock this properly I must mock the IHttpClientFactory, getting it to return a new HttpClient that relies on a mocked HttpMessageHandler, which I have done like this: </p>

<pre><code>var mockHttpClientFactory = new Mock&lt;IHttpClientFactory&gt;();

var mockHttpMessageHandler = new Mock&lt;HttpMessageHandler&gt;();
mockHttpMessageHandler.Protected()
    .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(""SendAsync"", ItExpr.IsAny&lt;HttpRequestMessage&gt;(), ItExpr.IsAny&lt;CancellationToken&gt;())
    .ReturnsAsync(new HttpResponseMessage
        {
         StatusCode = HttpStatusCode.OK,
         Content = new StringContent(""{'name':thecodebuzz,'city':'USA'}""),
        });

var client = new HttpClient(mockHttpMessageHandler.Object);
mockHttpClientFactory.Setup(x =&gt; x.CreateClient(It.IsAny&lt;string&gt;())).Returns(client);

_httpClientService = new HttpClientService(mockHttpClientFactory.Object, mockConfig.Object); 
</code></pre>

<p>This aspect works and I've been able to call CreateClient() which is working fine. However the function I'm trying to test calls my GetAccessToken() function, which in turn makes a call to client.GetDiscoveryAccessToken(). I'm guessing the GetDiscoveryAccessToken() function needs to be mocked, but I'm unsure how to proceed. </p>

<p>I've tried creating a mock of the client with a mocked method and returning this when CreateClient is called like so:</p>

<pre><code> var discoDoc = // Mocked disco doc code;

 var client = new Mock&lt;HttpClient&gt;(mockHttpMessageHandler.Object);
 client.Setup(x =&gt; x.GetDiscoveryDocumentAsync(It.IsAny&lt;string&gt;())).Returns(discoDoc);

 mockHttpClientFactory.Setup(x =&gt; x.CreateClient(It.IsAny&lt;string&gt;())).Returns(client);

 _httpClientService = new HttpClientService(mockHttpClientFactory.Object, mockConfig.Object);
</code></pre>

<p>Unfortunately I get this error: ""Cannot convert from 'Moq.Mock' to 'System.Net.Http.HttpClient'"" on the line where I tell the CreateClient function what to return. I'm guessing this is because I need to be returning a real HttpClient rather than a Mocked one. </p>

<p>Any ideas about where I can go from here? </p>
",https://stackoverflow.com/questions/62130584/how-to-mock-getdiscoverydocumentasync-when-unit-testing-httpclient,"['.net', 'unit-testing', 'httpclient', 'moq', 'httpclientfactory']",1163,True,2,2
Unit testing - onGridReady - Ag-grid event in Angular,"<p>I am having a function like below in my component file like below</p>
<pre class=""lang-js prettyprint-override""><code>onGridReady(params) {
  this.gridApi = params.api;
  this.columnApi = params.columnApi;
  this.gridApi.setDomLayout('autoHeight');
  this.gridApi.sizeColumnsToFit();
  params.api.setRowData(this.deviceConfigurations);
}
</code></pre>
<p>For the above function I am writing the spec like the below one</p>
<pre class=""lang-js prettyprint-override""><code>describe('#onGridReady()', () =&gt; {
    const params = {
      api: new MockGridApi(),
      ColumnApi: new MockColumnApi(),
    };

    it('call the function', () =&gt; {
      spyOn(component, 'onGridReady').and.callThrough();
      component.onGridReady(params);

      expect(component.onGridReady).toHaveBeenCalled();
    });
  });
</code></pre>
<p>The spec passes as well as the coverage is done for the above function. But I would like to know whether is it the correct way or writing the spec or do I need to write more specs like to <code>sizeColumnsToFit()</code> has been called etc.,
Could anyone can give your view about it.</p>
",https://stackoverflow.com/questions/64121707/unit-testing-ongridready-ag-grid-event-in-angular,"['angular', 'karma-jasmine', 'angular-test', 'karma-coverage', 'angular-unit-test']",6961,True,2,1
Unit Testing location in async-await in angular,"<p>I am using Angular 9+ with karma test runner and jasmine test framework for unit tests.</p>
<p>I wanted to unit test only <em><code>app component</code></em> which has a dependency injection:</p>
<p><code>app.component.ts</code></p>
<pre><code>import { Component, EmbeddedViewRef } from '@angular/core';
import * as moment from 'moment-timezone';
import { OtherServiceService } from './other-service.service';
import { Location } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(private sampleService: OtherService, private location: Location){}

    async func(){
        await this.sampleService.func2().toPromise();
        console.log('Async call completed');
        this.location.go('/index.html');
    }
}
</code></pre>
<p><code>other-service.service.ts</code></p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class OtherServiceService {

  constructor(private http: HttpClient) { }

  func2(){
    return this.http.post('' , null);
  }
}
</code></pre>
<p>The unit test i have tried so far:</p>
<pre><code>import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { AppComponent } from './app.component';
import { OtherServiceService } from './other-service.service';

const locationStub = {
  go: jasmine.createSpy('go')
}

describe('AppComponent', () =&gt; {
  let otherServiceStub;
  let fixture, component;
  beforeEach(async(() =&gt; {
    otherServiceStub = jasmine.createSpyObj(['func2']);

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        {provide: OtherServiceService , useValue: otherServiceStub},
        {provide: Location, useValue: locationStub}
    ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

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

  it('should create the app', () =&gt; {
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it('should check for correct logs',fakeAsync(() =&gt; {
    otherServiceStub.func2.and.returnValue(of('Garbage'));
    const location = fixture.debugElement.injector.get(Location);
    let spyObj = spyOn(console,'log');
    component.func();
    tick();
    expect(spyObj).toHaveBeenCalledWith('Async call completed');
    expect(location.go).toHaveBeenCalledWith('/index.html');
 }));


});

</code></pre>
<p>On running ng test --code-coverage, it always shows error <strong><code>Expected spy go to have been called with: [ '/index.html' ] but it was never called.</code></strong>.</p>
<p>On the coverage report, it shows the line as covered (this.location.go) , but the test fails, and I can't seem to understand why. I have also taken help from <a href=""https://stackoverflow.com/questions/48202042/angular-how-to-test-a-component-which-requires-a-location"">this</a>, but to no success.</p>
<p><strong><code>UPDATE 1.0</code></strong>:</p>
<p>I have tried as suggested by @AliF50:</p>
<pre><code>  async func(){
    await this.sampleService.func2().toPromise();
    console.log('Async call completed');
    this.location.go('/index.html');
    console.log('After location go in component');
  } 
</code></pre>
<pre><code>  it('should check for correct logs',fakeAsync(() =&gt; {
    otherServiceStub.func2.and.returnValue(of('Garbage'));
    let spyObj = spyOn(console,'log');
    component.func();
    tick();
    const location = fixture.debugElement.injector.get(Location);
    expect(spyObj).toHaveBeenCalledWith('Async call completed');
    console.log('Before location go in test');
    expect(location.go).toHaveBeenCalledWith('/index.html');
    console.log('After location go in test');
 }));
</code></pre>
<p><strong>But to my suprise <em>none</em> of the <code>console logs</code> are being printed, even though it shows lines as covered.</strong></p>
<p><strong><code>UPDATE 2.0</code></strong>:</p>
<p>As suggested by @AliF50:</p>
<pre><code>  it('should check for correct logs',fakeAsync(() =&gt; {
    otherServiceStub.func2.and.returnValue(of('Garbage'));
    let spyObj = spyOn(console,'log').and.callThrough();
    component.func();
    tick();
    const location = fixture.debugElement.injector.get(Location);
    expect(spyObj).toHaveBeenCalledWith('Async call completed');
    console.log('Before location go in test');
    expect(location.go).toHaveBeenCalledWith('/index.html');
    console.log('After location go in test');
 }));
</code></pre>
<p><strong>All the <code>console logs</code> are being printed, but the error still remains.</strong></p>
<p><strong><code>UPDATE 3.0</code></strong>:
<strong>Any luck anyone? It is still an open question</strong></p>
<p><strong><code>UPDATE 4.0</code></strong>:
<strong>Thanks to Andrei. Question is solved now.</strong></p>
",https://stackoverflow.com/questions/65295364/unit-testing-location-in-async-await-in-angular,"['angular', 'unit-testing', 'async-await']",3523,True,2,3
Unit Testing navigator.permissions.query({ name: &#39;geolocation&#39; }) using Jest (React),"<p>I Tried to mock this function</p>

<pre><code>const location = window.navigator &amp;&amp; window.navigator.geolocation;
if (location) {
  location.getCurrentPosition(
    (position) =&gt; {
      handleChangeLocation(position.coords.latitude, position.coords.longitude);
    },
    (error) =&gt; {
      console.log(error);
    },
  );
}
navigator.permissions
  .query({ name: 'geolocation' })
  .then((permission) =&gt; {
    permission.onchange = function () {
      if (permission.state === 'granted') {
        location.getCurrentPosition((position) =&gt; {
          handleChangeLocation(position.coords.latitude, position.coords.longitude);
        });
      } else if (permission.state === 'denied') {
        // Todo
      }
    };
  });
</code></pre>

<p>so far what i've tried is
Create Global Navigator at setupTest.js</p>

<pre><code>const mockGeolocation = {
  getCurrentPosition: jest.fn()
    .mockImplementationOnce((success) =&gt; Promise.resolve(success({
      coords: {
        latitude: 51.1,
        longitude: 45.3,
      },
    }))),
};
global.navigator.geolocation = mockGeolocation;
</code></pre>

<p>but ended up at error</p>

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

<p>I tried to solve this by adding<code>jest.spyOn(window.navigator.permissions.query({ name: 'geolocation' }), 'onchange', 'get').mockReturnValueOnce('granted');</code>
but i think there's some mistake cause it's says undefined.</p>
",https://stackoverflow.com/questions/62319726/unit-testing-navigator-permissions-query-name-geolocation-using-jest-re,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",1944,True,2,2
Unit testing functions with global variables in R,"<h1>Preamble: package structure</h1>
<p>I have an R package that contains an <code>R/globals.R</code> file with the following content (simplified):</p>
<pre class=""lang-r prettyprint-override""><code>utils::globalVariables(&quot;COUNTS&quot;)
</code></pre>
<p>Then I have a function that simply uses this variable. For example, <code>R/addx.R</code> contains a function that adds a number to <code>COUNTS</code></p>
<pre class=""lang-r prettyprint-override""><code>addx &lt;- function(x) {
    COUNTS + x
}
</code></pre>
<p>This is all fine when doing a <code>devtools::check()</code> on my package, there's no complaining about <code>COUNTS</code> being out of the scope of <code>addx()</code>.</p>
<h1>Problem: writing a unit test</h1>
<p>However, say I also have a <code>tests/testthtat/test-addx.R</code> file with the following content:</p>
<pre><code>test_that(&quot;addition works&quot;, expect_gte(fun(1), 1))
</code></pre>
<p>The content of the test doesn't really matter here, because when running <code>devtools::test()</code> I get an &quot;object 'COUNTS' not found&quot; error.</p>
<p>What am I missing? How can I correctly write this test (or setup my package).</p>
<h1>What I've tried to solve the problem</h1>
<ol>
<li>Adding <code>utils::globalVariables(&quot;COUNTS&quot;)</code> to <code>R/addx.R</code>, either before, inside or after the function definition.</li>
<li>Adding <code>utils::globalVariables(&quot;COUNTS&quot;)</code> to <code>tests/testthtat/test-addx.R</code> in all places I could think of.</li>
<li>Manually initializing <code>COUNTS</code> (e.g., with <code>COUNTS &lt;- 0</code> or <code>&lt;&lt;- 0</code>) in all places of <code>tests/testthtat/test-addx.R</code> I could think of.</li>
<li>Reading some examples from other packages on GitHub that use a similar syntax (<a href=""https://github.com/search?p=1&amp;q=utils%3A%3AglobalVariables&amp;type=Code&amp;utf8="" rel=""nofollow noreferrer"">source</a>).</li>
</ol>
",https://stackoverflow.com/questions/65220769/unit-testing-functions-with-global-variables-in-r,"['r', 'unit-testing', 'global-variables', 'r-package']",741,True,1,2
"Hyperledger Fabric nodejs chaincode unit testing in nodejs,","<p>I have developed a custom chaincode for my application in nodejs, I need to perform unit test to validate the functionality using any frameworks such as jest mocha chai, etc. I did did find Hyperledger fabric mock stub testing but it doesnt support fabric-contract-api as far as my knowledge. I also read about some truffle method but did not try. Is there any way to test chaincode in nodejs.</p>
",https://stackoverflow.com/questions/63019285/hyperledger-fabric-nodejs-chaincode-unit-testing-in-nodejs,"['node.js', 'hyperledger-fabric', 'blockchain', 'truffle', 'chaincode']",790,True,1,2
d3 is not defined in unit testing jest,"<p>error showing d3 is not defined when run test command ""npm test"".
<a href=""https://i.stack.imgur.com/Cv2uM.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Cv2uM.png"" alt=""enter image description here""></a></p>

<p>Below image is my test script
<a href=""https://i.stack.imgur.com/naCaM.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/naCaM.png"" alt=""enter image description here""></a></p>

<p>Pie chart code is below image</p>

<p><a href=""https://i.stack.imgur.com/0f6Ml.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0f6Ml.png"" alt=""e""></a></p>
",https://stackoverflow.com/questions/59798490/d3-is-not-defined-in-unit-testing-jest,"['d3.js', 'jestjs', 'gulp-npm-test']",758,False,1,0
Unit testing a vue component that uses dependency,"<p>I'm trying to test my SiWizard component that uses external dependencies. It imports modules from the syncfusion library.</p>

<p><em>SiWizard.vue imports</em></p>

<pre><code>import SiFooter from ""@/components/subComponents/SiFooter.vue"";
import { Prop, Component, Vue } from ""vue-property-decorator"";
import { TabPlugin, TabComponent, SelectingEventArgs } from ""@syncfusion/ej2-vue-navigations"";
import { VNode } from ""vue"";

Vue.use(TabPlugin);
</code></pre>

<p>And this is what my test looks like, using vue js test utils and jest. Just to keep things simple my test case should pass and configured a single prop.</p>

<p><em>siWizard.spec.ts</em></p>

<pre><code>import { shallowMount, Wrapper } from ""@vue/test-utils"";
import SiWizard from ""../../src/components/SiWizard.vue"";

let wrapper: Wrapper&lt;SiWizard &amp; { [key: string]: any }&gt;;

describe(""testing SiWizard"", () =&gt; {
  test(""Test add mode"", () =&gt; {
    wrapper = shallowMount(SiWizard, {
      propsData: {
        mode: ""add""
      }
    });

    expect(true).toBe(true)
  });
</code></pre>

<p>When running the siWizard.spec.ts I get weird errors. 
<a href=""https://i.stack.imgur.com/RvumW.png"" rel=""nofollow noreferrer"">Error without mocking, test still passes</a></p>

<p>My guess is that properties in the test environment can't access the dependency properties used in the SiWizard component. Therefor I have to mock the TabPlugin using Jest. So I tried to mock the dependency using jest.mock.</p>

<pre><code>import { shallowMount, Wrapper } from ""@vue/test-utils"";
import SiWizard from ""../../src/components/SiWizard.vue"";

// import { TabPlugin } from ""@syncfusion/ej2-vue-navigations"";

jest.mock(""../../node_modules/@syncfusion/ej2-navigations"" , () =&gt; { jest.fn() });

let wrapper: Wrapper&lt;SiWizard &amp; { [key: string]: any }&gt;;

describe(""testing SiWizard"", () =&gt; {
  test(""Test add mode"", () =&gt; {
    wrapper = shallowMount(SiWizard, {
      propsData: {
        mode: ""add""
      }
    });

    expect(true).toBe(true)
  });
</code></pre>

<p>Resulting in a test that fails and giving the following error <a href=""https://i.stack.imgur.com/SLuJX.png"" rel=""nofollow noreferrer"">Error and failing test</a></p>

<p>I'm not sure if I need to mock anything because my first test still passes but it only gives me errors. Can anyone tell me if I mock correctly or do I need to do something else?</p>
",https://stackoverflow.com/questions/62170277/unit-testing-a-vue-component-that-uses-dependency,"['typescript', 'unit-testing', 'vue.js', 'syncfusion', 'ej2-syncfusion']",1802,False,1,2
Laravel-Vue unit testing error &quot;SyntaxError: Unexpected token {&quot;,"<p>I'm trying to write unit tests for Vue, set up in a Laravel environment. I followed <a href=""https://dev.to/tuandm/how-to-test-vue-components-with-laravel-mix-and-mocha-3kgc"" rel=""nofollow noreferrer"">this article</a> to set up the project for testing. But it doesn't work as expected and I get this error when I run <code>npm test</code>.</p>
<pre><code>&gt; @ test G:\Unit testing\Vue-Laravel
&gt; mochapack --webpack-config=node_modules/laravel-mix/setup/webpack.config.js --require tests/js/setup.js tests/js/\*\*/\*.spec.js

(node:3224) UnhandledPromiseRejectionWarning: G:\Unit testing\Vue-Laravel\tests\js\setup.js:3
import { mount } from '@vue/test-utils';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at exports.requireOrImport (G:\Unit testing\Vue-Laravel\node_modules\mocha\lib\esm-utils.js:20:12)
    at Object.exports.handleRequires (G:\Unit testing\Vue-Laravel\node_modules\mocha\lib\cli\run-helpers.js:94:34)
    at mochaChecks (G:\Unit testing\Vue-Laravel\node_modules\mochapack\lib\cli\argsParser\parseArgv\mocha\parseMochaArgs.js:60:19)
(node:3224) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
 WEBPACK  Compiling...

  [=========================] 98% (after emitting)

 DONE  Compiled successfully in 198ms                                                                                          12:25:43 AM
  [=========================] 100% (completed)

 WEBPACK  Compiled successfully in 198ms

 MOCHA  Testing...



  0 passing (0ms)

 MOCHA  Tests completed successfully&quot;
</code></pre>
<h3>setup.js</h3>
<pre><code>require('jsdom-global')();

import { mount } from '@vue/test-utils';
import expect from 'expect';
import App from '../../../resources/js/App.vue';

describe('App.vue', () =&gt; {
  it('says Hello Vue!', () =&gt; {
    const wrapper = mount(App);
    expect(wrapper.html()).toContain('Hello Vue!');
  });
});
</code></pre>
<h3>App.vue</h3>
<pre><code>&lt;template&gt;
  &lt;div&gt;
      &lt;h1&gt;
          {{ msg }}
      &lt;/h1&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
    name: 'app-component',
    data(){
        return {
            msg : &quot;Hello Vue!&quot;
        }
    }
}
&lt;/script&gt;
</code></pre>
<h3>Git hub repository</h3>
<p>This <a href=""https://github.com/nizar-dev01/laravel-mix-testing"" rel=""nofollow noreferrer"">repository</a> contains the whole code.</p>
",https://stackoverflow.com/questions/62490846/laravel-vue-unit-testing-error-syntaxerror-unexpected-token,"['javascript', 'laravel', 'unit-testing', 'vue.js', 'vuejs2']",306,False,1,1
React - unit testing HOC’s wrapped component - testing state,"<p>I want to test state of my ReactJS application using Enzyme.
Simple test - if state will change, modal is showing up - but I get error:
<code>ShallowWrapper::state() can only be called on class components</code>
My component is class component.</p>

<pre><code> class Component extends PureComponent&lt;ComponentProps&gt; {

  public state = {
    hasError: false,
  };

  public render() {
    const { hasError } = this.state;
    return (
      &lt;&gt;
        &lt;Modal
          isOpen={hasError}
          type=""error""
        /&gt;
        &lt;button onClick={this.onBtnClik}
      &lt;/&gt;
    );
  }

private onBtnClik = () =&gt; this.setState({ hasError: true})

 export default compose(
  withRouter,
  withStyles(styles),
  connect(mapStateToProps, mapDispatchToProps),
)(Component) as any;
</code></pre>

<p>As you see I have a lot of HOC's and I cannot test my state. I found this article:
<a href=""https://medium.com/c-hive/test-hocs-wrapped-component-with-jest-and-enzyme-e9155f80a217"" rel=""nofollow noreferrer"">https://medium.com/c-hive/test-hocs-wrapped-component-with-jest-and-enzyme-e9155f80a217</a>
but: <code>wrapper = shallow(shallow(&lt;MyComponent /&gt;).get(0));</code> still not helping me so I am a little confused and will be very grateful for any advice.</p>

<p>My test:</p>

<pre><code>  it('should open Modal when error state is true', () =&gt; {
    const wrapper = shallow(shallow(&lt;Component /&gt;).get(0));
    expect(wrapper.state('hasError')).toBe(true);
  });
</code></pre>
",https://stackoverflow.com/questions/61951613/react-unit-testing-hoc-s-wrapped-component-testing-state,"['reactjs', 'unit-testing', 'testing', 'enzyme', 'higher-order-components']",720,False,1,1
Unit Testing on a NodeJS + Typescript AWS Lambda,"<p>Which one is the best way to unit test a lambda implemented in NodeJS using TypeScript like this dummy one:</p>

<pre class=""lang-js prettyprint-override""><code>import {Callback} from ""aws-lambda"";

export interface BinaryEvent {
  number1: number
  number2: number
}

export interface Result {
  result: number
}

export type BinaryOperation = (number1: number, number2: number) =&gt; number;

export type BinaryOperationHandler = ({number1, number2}: BinaryEvent, context: any, callback: Callback&lt;Result&gt;) =&gt; void;

export const addition: BinaryOperationHandler = ({number1, number2}, context, callback) =&gt; {
  setTimeout(() =&gt; callback(null, {result: (number1 + number2)}), 1000);
}
</code></pre>
",https://stackoverflow.com/questions/62068266/unit-testing-on-a-nodejs-typescript-aws-lambda,"['node.js', 'typescript', 'amazon-web-services', 'unit-testing', 'aws-lambda']",1501,True,2,1
Spring WebFlux: Unit Testing subscribe function of Mono,"<p>I have the following classes/interfaces:</p>

<pre class=""lang-java prettyprint-override""><code>public interface Api {
    Mono&lt;Object&gt; update();
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>@Service
public class Service {
    @Autowired
    private Api api;
    private List&lt;Object&gt; list;

    public void update() {
        api.update().subscribe(result -&gt; list.add(result), Throwable::printStackTrace);    
    }
}
</code></pre>

<p>I'm trying to perform a unit test using Mockito of the consumer function when I subscribe to the Mono that is being returned by my Api. So far, my test class looks as follows</p>

<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {
    @Mock
    private Mono&lt;Object&gt; mono;
    @MockBean
    private Api api;
    @Autowired
    private Service service;

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

    @Test
    public void testUpdate() {
        when(api.update()).thenReturn(mono);
        doAnswer((Answer&lt;Void&gt;) invocation -&gt; {
            System.out.println(""FOO"");
            Consumer&lt;Object&gt; consumer = invocation.getArgument(0);
            consumer.accept(testObject)
            return null;
        }).when(mono).subscribe(any(Consumer.class), any(Consumer.class));

       service.update();
    }
}
</code></pre>

<p>First, I am seeing that the code inside doAnswer() never gets invoked. Secondly, since Mockito's any() returns null and the error consumer of subscribe function expects non-null I'm running into NullPointerException when I run my test.</p>

<p>What would be the best approach of going about unit testing my subscribe's consumer function?</p>
",https://stackoverflow.com/questions/60606855/spring-webflux-unit-testing-subscribe-function-of-mono,"['java', 'spring', 'testing', 'mockito', 'reactor']",1757,False,1,0
SharePoint visual webpart unit testing in visual studio,"<p>I need to know whether we can create test cases for custom webparts that are build for SharePoint web applications. I have created custom webpart for my SharePoint list with asp.net controls (asp:textbox, asp:dropdown etc..) and added functions like populating dropdown in page_load, used spquery for querying items and displayed in asp gridview </p>

<pre><code> protected void Page_Load(object sender, EventArgs e)
{
  if(!IsPostBack)
   {
     // Check new or edit item and populate saved values in controls on edit item
    }
}

Protected void btnSave_Click(object sender, EventArgs e)
{
  // Action done on save click
}

</code></pre>

<p>I have used Nunit for creating unit test cases for console applications in development phase. It is very useful for me to cover all test cases also reduces testing phase time and bugs.</p>

<p>But I don't know how to implement unit testing in webparts page load function, button click actions etc..</p>

<p>I am new to SharePoint as well as Unit testing. It will be very greatful, if someone help me to handle this by providing some examples for the above cases.</p>
",https://stackoverflow.com/questions/62103951/sharepoint-visual-webpart-unit-testing-in-visual-studio,"['c#', 'asp.net', 'visual-studio', 'unit-testing', 'sharepoint-2013']",57,False,1,0
Unit testing method that uses IMemoryCache extension method,"<p>I am trying to write a unit test using MSTest and Moq for a method that uses an extension method of IMemoryCache. Situation:</p>

<pre><code>public class ClassToTest
{        
  private IMemoryCache Cache { get; }

  public ClassToTest(IMemoryCache cache)
  {          
    Cache = cache;
  }

  public async Task&lt;SomeType&gt; MethodToTest(string key)
  {
    // Get is an extension method defined in Microsoft.Extensions.Caching.Memory
    var ci = Cache.Get&lt;CachedItem&lt;T&gt;&gt;(key);

    // Do stuff with cached item
  }
}
</code></pre>

<p>How can I unit test this?</p>

<p>So far i tried:</p>

<pre><code>[TestMethod]
public void TestMethodToTest()
{
  IServiceCollection services = new ServiceCollection();
  services.AddMemoryCache();

  var serviceProvider = services.BuildServiceProvider();
  var memoryCache = serviceProvider.GetService&lt;IMemoryCache&gt;();

  ClassToTest testClass = new ClassToTest(memoryCache);
}
</code></pre>

<p>This gives me the following error: ""'IServiceCollection' does not contain a definition for 'AddMemoryCache' and no accessible extension method 'AddMemoryCache' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)"".</p>

<p>Does anyone know how to unit test this method? Preferably without changing the method itself.
Is there a standard way to do this?
Any help is appriciated.</p>
",https://stackoverflow.com/questions/60336704/unit-testing-method-that-uses-imemorycache-extension-method,"['c#', 'unit-testing', 'moq', 'asp.net-core-3.1']",2183,True,1,1
Client Side Unit Testing Meteor/React w/Enzyme,"<p>so i've been stuck for several days on an issue while implementing Unit Testing and Integration testing in a large production application that was built in Meteor/React tech stack. I am using the meteortesting:mocha package as recommended by the meteor documentation and enzyme.</p>
<p>The issue i am having is that i am not really grasping how i can mock the withTracker functionality. I am trying to use our dev database as the source for the test users and mock data. All of the props are generated in the tracker and then sent to the component it wraps. (Code sample below). Another issue i am having is that we are using meteor:universe for i18n internationalization. When mounting the component it shows plain text instead of the translated content. Wondering if there's a work around. Thanks in advance!</p>
<p><strong>Component I am testing:</strong></p>
<pre><code>import React, { useState } from &quot;react&quot;;
import ABCComponent from &quot;./ABCComponent&quot;;
import XYZ from &quot;./XYZComponent&quot;;
import * as ROUTE_CONSTANTS from &quot;../../global/RoutesConstants&quot;;
import { withRouter } from &quot;react-router-dom&quot;;
import { withTracker } from &quot;meteor/react-meteor-data&quot;;
import UserAssessments from &quot;../../collections/UserAssessments&quot;;
import moment from &quot;moment-timezone&quot;;
import { i18n } from &quot;meteor/universe:i18n&quot;;

const SortDashboard = (props) =&gt; {
  const [isSkillsSort, setIsSkillSort] = useState(true);

  return (
   &lt;div&gt;
       {/* Contains some logic to set 'isSetSkillSort' state true or false (business logic hidden for security purposes*/}
      {isSkillsSort ? (
        &lt;ABCComponent user={props.user} skillsSorts={props.skillsSorts} employeeList={props.directReportEmp} /&gt;
      ) : (
        &lt;XYZComponent
          user={props.user}
          importanceSorts={props.importanceSorts}
          employeeList={props.directReportEmp}
        /&gt;
      )}
    &lt;/div&gt;
  );
};

const SortDashboardTracker = withTracker((props) =&gt; {
  if (!props.user) return {};

  const abcSubscription = Meteor.subscribe(&quot;abcSubscription&quot;);

  if (abcSubscription.ready()) {
    const rawData = UserAssessments.find(
      { &quot;assessor._id&quot;: Meteor.user().profile._id },
      { sort: { updatedDate: -1 } }
    ).fetch();

    rawData.forEach((assessment) =&gt; {
        //Do Something (business logic hidden for security purposes)
    });
  }

  const xyzSubscription = Meteor.subscribe(&quot;xyzSubscription&quot;);

  let directReportEmp = [];

  if (xyzSubscription.ready()) {
    directReportEmp = Meteor.users.find({ &quot;profile.managerId&quot;: Meteor.user().username }).fetch();
  }

  return { importanceSorts, skillsSorts, directReportEmp };
})(SortDashboard);

export default withRouter(SortDashboardTracker);
</code></pre>
<p>My Test:</p>
<pre><code>import {Meteor} from 'meteor/meteor';
import React from 'react';
import chai from 'chai';
import sinon, { mock } from 'sinon'
import {mount, shallow, configure, render} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import {mockManager,mockEmp1,mockEmp2,mockEmp3,mockUser} from '../../mockUsers'
import SortDashboard from '../../../../imports/components/cllWizard/SortDashboard';
import { withRouter, BrowserRouter as Router } from &quot;react-router-dom&quot;;

configure({adapter: new Adapter()});
if (Meteor.isClient) {
    describe('WizardComponent', ()=&gt; {
        //let returnedText
         //importing the mock user we created for testing purposes
         const currentUser = mockUser
         let props = {user: currentUser}
         beforeEach(() =&gt; {
 
             // now Meteor.user() will return the user we just imported
             sinon.stub(Meteor, 'user');
             Meteor.user.returns(currentUser);
 
             // needed in methods
             sinon.stub(Meteor, 'userId');
             Meteor.userId.returns(currentUser._id); 
         });
 
         //afterEach specifies that we want to restore the user after running the test
         afterEach(() =&gt; {
             Meteor.user.restore();
             Meteor.userId.restore();
         });

        it('CLIENT: should render the Sort Dashboard', () =&gt; {
            const wrapper = mount(&lt;Router&gt;&lt;SortDashboard.WrappedComponent {...props}/&gt;&lt;/Router&gt;)
            console.log(wrapper.debug())
        });
    });
}
</code></pre>
<p>TLDR;</p>
<ul>
<li>Need to test a client side component that uses withTracker and withRouter</li>
<li>Need to be able to see the translated text from meteor:universe:i18n in the test</li>
<li>Pulling mock data from the db instead of manually creating it.</li>
</ul>
<p>The issue may very well be my approach and lack of understanding. Please correct me where-ever necessary. Thanks in advance!</p>
",https://stackoverflow.com/questions/64267755/client-side-unit-testing-meteor-react-w-enzyme,"['reactjs', 'meteor', 'jestjs', 'mocha.js', 'enzyme']",109,False,1,0
Challenge Activity - C++ Unit Testing of a Class,"<blockquote>
  <p>Write a unit test for addInventory(), which has an error. Call
  redSweater.addInventory() with parameter sweaterShipment. Print the
  shown error if the subsequent quantity is incorrect. Sample output for
  failed unit test given initial quantity is 10 and sweaterShipment is
  50:</p>

<pre><code>Beginning tests.
   UNIT TEST FAILED: addInventory()
Tests complete.
</code></pre>
  
  <p>Note: UNIT TEST FAILED is preceded by 3 spaces.</p>
</blockquote>

<p>Yes, this is an assignment for a C++ programming class. I have tried to add various member objects from the below class to no avail, unfortunately I am stuck and would like some hints, not answers, on how to learn and proceed. Here is the code I have so far:</p>

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

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

private:
   int quantityRemaining;
};

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

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

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

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

   sweaterInventoryBefore = redSweater.getQuantityRemaining();
   cin &gt;&gt; sweaterShipment;

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

   // FIXME add unit test for addInventory

   /* Your solution goes here  */
      redSweater.addInventory(sweaterShipment);
   if (redSweater.addInventory(sweaterShipment) != 50){
      cout &lt;&lt; ""   UNIT TEST FAILED: addInventory()\n"";
   }

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

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

<p>EDIT: SOLVED, solution below</p>

<pre><code>   // FIXME add unit test for addInventory

   /* Your solution goes here  */
   redSweater.addInventory(sweaterShipment);
   if (redSweater.getQuantityRemaining() != sweaterShipment){
      cout &lt;&lt; ""   UNIT TEST FAILED: addInventory()\n"";
   }
</code></pre>
",https://stackoverflow.com/questions/59869837/challenge-activity-c-unit-testing-of-a-class,"['c++', 'unit-testing']",13393,True,1,1
Unit testing in Asp.Net Core MVC Web Application,"<p>I am having a hard time figuring out how to do unit testing in my MVC Web App. Although it is not a really hard concept to grasp, I was not able to find out whether I need a specific framework for this or respect some certain steps, given its multi-layered architecture. I would be very glad if you could give me some tips or code snippets so I could have an idea on what I should actually do. I will give you an example from my project:</p>

<p><strong>PhaseController</strong></p>

<pre><code>    public IActionResult Create()
    {

        return View();
    }

    [HttpPost]
    public IActionResult Create(Phase phase)
    {
        int releaseId = (int)TempData[""id""];
        string connectionString = Configuration[""ConnectionStrings:DefaultConnection""];
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sql = ""CreatePhase"";

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                // adding parameters
                SqlParameter parameter = new SqlParameter
                {
                    ParameterName = ""@Name"",
                    Value = phase.Name,
                    SqlDbType = SqlDbType.VarChar,
                    Size = 50
                };
                command.Parameters.Add(parameter);

                parameter = new SqlParameter
                {
                    ParameterName = ""@ReleaseId"",
                    Value = releaseId,
                    SqlDbType = SqlDbType.Int
                };
                command.Parameters.Add(parameter);

                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
        }

        return RedirectToAction(""Index"", ""Phase"", new { id = releaseId });
    }
</code></pre>

<p><strong>Phase Model</strong></p>

<pre><code>namespace Intersection.Models
{
    public class Phase
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int ReleaseId { get; set; }
       // public IEnumerable&lt;Phase&gt; phases { get; set; }
    }
}
</code></pre>

<p>Take these two as an example - how should my test class look like in order to properly test the Create() method (The POST one as well)?</p>

<p><strong>EDIT:</strong></p>

<p>Following @Nkosi's reply, I am adding a different method from another controller:</p>

<pre><code>public IActionResult Create()
    {
        List&lt;Intersection.Models.Environment&gt; environmentList = new List&lt;Intersection.Models.Environment&gt;();

        string connectionString = Configuration[""ConnectionStrings:DefaultConnection""];
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string sql = ""ReadEnvironments"";
            SqlCommand command = new SqlCommand(sql, connection);
            command.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader dataReader = command.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    Intersection.Models.Environment environment = new Intersection.Models.Environment();
                    environment.Id = Convert.ToInt32(dataReader[""Id""]);
                    environment.Name = Convert.ToString(dataReader[""Name""]);
                    environmentList.Add(environment);
                }
            }

            ViewBag.Environments = environmentList;
            return View();
        }
    }

    [HttpPost]
    public IActionResult Create(Application application)
    {
        string connectionString = Configuration[""ConnectionStrings:DefaultConnection""];
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sql = ""CreateApplication"";

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                // adding parameters
                SqlParameter parameter = new SqlParameter
                {
                    ParameterName = ""@Name"",
                    Value = application.Name,
                    SqlDbType = SqlDbType.VarChar,
                    Size = 50
                };
                command.Parameters.Add(parameter);

                parameter = new SqlParameter
                {
                    ParameterName = ""@Environment"",
                    Value = application.Environment,
                    SqlDbType = SqlDbType.Int
                };
                command.Parameters.Add(parameter);

                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
        }

        return RedirectToAction(""Index"", ""Application"");
    }
</code></pre>
",https://stackoverflow.com/questions/59648106/unit-testing-in-asp-net-core-mvc-web-application,"['c#', 'asp.net-mvc', 'unit-testing', 'asp.net-core']",541,True,1,2
Unit testing custom STL-compatible containers and iterators,"<p>I've just implemented a custom iterator type for a custom container. The container models the C++17 <a href=""https://en.cppreference.com/w/cpp/named_req/ReversibleContainer"" rel=""nofollow noreferrer""><em>ReversibleContainer</em></a>, and its iterators (both const and non-const) model <a href=""https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator"" rel=""nofollow noreferrer""><em>LegacyRandomAccessIterator</em></a>.</p>
<p>My question is; is there some sort of built-in thing in <code>std</code> that I can use to test if both the container and its iterators adhere to the specified named requirements, or do I have to write all the tests myself (which is mostly doable for me but I'd rather not reinvent the wheel; and also I'm not sure I'm enough of a template wizard to really thoroughly prove that e.g. types and such are correct)?</p>
<p>Things like (I know this is one of many), e.g. this from the operational semantics of <code>operator &lt;</code>:</p>
<pre><code>custom_container::iterator a = ...;
custom_container::iterator b = ...;
assert((a &lt; b) == (b - a &gt; 0));
</code></pre>
<p>And that return types are correct, etc., and such.</p>
<hr />
<p>I've managed to find <em>some</em> capabilities already, for example <em>&lt;type_traits&gt;</em> has some useful utilities like:</p>
<pre><code>if (!std::is_copy_constructible&lt;custom_container::iterator&gt;::value)
   /* fail test */ ;
</code></pre>
<p>Which is good for some of the fundamental named requirements at least.</p>
",https://stackoverflow.com/questions/65350197/unit-testing-custom-stl-compatible-containers-and-iterators,"['c++', 'unit-testing', 'testing', 'stl', 'c++17']",129,True,1,1
How to unit testing OidcSecurityService.checkAuth function with Jasmine?,"<p>I am using Jasmine for unit testing in Angular. And I am using the OidcSecurityService service for security. Now I want to unit test this piece for the automatic login:</p>
<pre><code>export class AppComponent implements OnInit {
  title = 'cityflows-client';
  constructor(public oidcSecurityService: OidcSecurityService, private router: Router, public platform: Platform) {}

  ngOnInit() {
    this.oidcSecurityService
      .checkAuth()

      .subscribe(isAuthenticated =&gt; {
        if (!isAuthenticated) {
          if ('/autologin' !== window.location.pathname) {
            this.write('redirect', window.location.pathname);
            this.router.navigate(['/autologin']);
          }
        }
        if (isAuthenticated) {
          this.navigateToStoredEndpoint();
        }
      });
  }
</code></pre>
<p>and so the unit test looks like this:</p>
<pre><code>describe('AppComponent', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      providers:    [ {provide: OidcSecurityService, useClass: OidcSecurityServiceStub} ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', () =&gt; {
    expect(component).toBeTruthy();
  }); 
});
</code></pre>
<p>And the stub looks like this:</p>
<pre><code>export class OidcSecurityServiceStub {
  getToken() {
    return 'some_token_eVbnasdQ324';
  }

  checkAuth(url: string) {
    return of(url);
  }

  authorize(authOptions?: AuthOptions) {
    if (authOptions) {
      return authOptions.urlHandler('http://localhost');
    } else {
      return null;
    }
  }
}
</code></pre>
<p>But i see in the coverage report this:</p>
<p>by the if that the else part is not taken.</p>
<p>So what I have to change? Thank you</p>
<pre><code>  it('should redirect user to login page if user is not logged in', () =&gt; {
    
    expect(component).toBeTruthy();
  });
</code></pre>
",https://stackoverflow.com/questions/64366686/how-to-unit-testing-oidcsecurityservice-checkauth-function-with-jasmine,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'istanbul']",690,True,1,1
Issue while Unit Testing ASP.Net Core with Mediatr,"<p>I am using ASP.Net Core 3.1 Repository Pattern and Unit of Work Using Dapper .
I have use mediator as</p>
<pre><code>using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
 
namespace TaskManagementApp.Api.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    [ApiController]
    public class ApiController : ControllerBase
    {
        private IMediator _mediator;
        protected IMediator Mediator =&gt; _mediator ??= HttpContext.RequestServices.GetService&lt;IMediator&gt;();
    }
}
</code></pre>
<p>i am facing issue how can i write unit test to set value for HttpContext.RequestServices.GetService</p>
<p>here is my controller to be unit tested</p>
<pre><code>namespace OneCubeCoaching.API.WebApi.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    public class ContactController : BaseApiController
    {
        [Authorize]
        [HttpGet(&quot;GetAll&quot;)]
        public async Task&lt;IActionResult&gt; Index()
        {
            return Ok(await Mediator.Send(new GetAllClientQuery()));
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/65124319/issue-while-unit-testing-asp-net-core-with-mediatr,"['unit-testing', 'asp.net-core', 'moq', 'xunit', 'mediatr']",785,False,1,1
Restoring test database for unit testing in Neo4j,"<p>I would like to unit test CRUD operations against a pre-populated Neo4j database.</p>

<p>I am thinking that a way to do this might be to:</p>

<ul>
<li>Create a an empty database (let's call it <code>testDB</code>)</li>
<li>Create a database backup (let's call it <code>testingBackup</code>)</li>
<li>On running tests:

<ul>
<li>Delete any data from <code>testDB</code></li>
<li>Populate <code>testDB</code> from <code>testingBackup</code></li>
<li>Run unit test queries on the now populated <code>testDB</code></li>
</ul></li>
</ul>

<p>I am aware of the backup / restore functions, the load / dump functions and the export to csv / load from csv etc.  However, I'm not sure which of these will be most appropriate to use and can be automated most easily.  I'm on Ubuntu and using python.</p>

<p>I would need to be able to quickly and easily alter the backup data as the application evolves.</p>

<p>What is the best approach for this please?</p>
",https://stackoverflow.com/questions/61588218/restoring-test-database-for-unit-testing-in-neo4j,"['unit-testing', 'neo4j']",423,True,1,1
Enable mocking for unit testing a library in C,"<p>In our environment we're encountering a problem regarding mocking functions for our library unit tests.
The thing is that instead of mocking whole modules (.c files) we would like to mock single functions. </p>

<p>The library is compiled to an archive file and linked statically to the unit test. Without mocking there isn't any issue. </p>

<p>Now when trying to mock single functions of the library we would get multiple definitions obviously.</p>

<p>My approach now is to use the <code>weak</code> function attribute when compiling/linking the library so that the linker takes the mocked (non-weak) function when linking against the unit test. I already tested it and it seems to work as expected.</p>

<p>The downside of this is that we need many attribute declarations in the code.</p>

<p><strong>My final approach would be to pass some compile or link arguments to the compiler, that every function is automatically declared as a weak symbol.</strong></p>

<p>The question now is: Is there anything to do this in a nice way?</p>

<p>btw: We use clang 8 as a compiler.</p>
",https://stackoverflow.com/questions/59932124/enable-mocking-for-unit-testing-a-library-in-c,"['c', 'unit-testing', 'clang', 'static-libraries']",760,False,7,2
Laravel Unit Testing for update method not working,"<p>I am trying to unit test the update function in a resource controller and I keep getting an error Call to undefined method assertStatus(). Here is my code: $this-&gt;withoutExceptionHandling();</p>
<pre><code>$this-&gt;withoutExceptionHandling();
    $timesheet = factory(TimeSheets::class)-&gt;create();

    $user = factory(UsersLoginModel::class)-&gt;create();

    $data = [
        'subject' =&gt; $this-&gt;faker-&gt;text,
        'subjectmatter' =&gt; $this-&gt;faker-&gt;text,
        'description' =&gt; $this-&gt;faker-&gt;text,
    ];
    ;
    $update = $this-&gt;actingAs($user)-&gt;json('PATCH','timesheets/update'.$timesheet-&gt;id, $data);
    $this-&gt;assertStatus(200);

    $this-&gt;assertEquals($data['subject'], $timesheet-&gt;subject);
    $this-&gt;assertEquals($data['subjectmatter'], $timesheet-&gt;subjectmatter);
    $this-&gt;assertEquals($data['description'], $timesheet-&gt;description);
</code></pre>
",https://stackoverflow.com/questions/62950089/laravel-unit-testing-for-update-method-not-working,"['laravel', 'testing']",426,False,1,1
Stub file imports in Angular 2+ Unit Testing,"<p>My project has a lot of utility functions that perform some data transformations, etc.
These functions are not in class and are reused in many utility files.</p>
<p>I'm very new to angular testing. Searched for quite some time and I couldn't find a way to stub the imports of a tested file. Here's the example:</p>
<p><strong>/utils/helpers.ts</strong></p>
<pre><code>export const sumNumber = (a: number, b: number): number =&gt; {
  return a + b;
}
</code></pre>
<p><strong>/utils/file-i-want-to-test.ts</strong></p>
<pre><code>import { sumNumber } from &quot;./helpers&quot;;

export const sumArrays = (arr1: number[], arr2: number[]): number[] =&gt; {
  const len = arr1.length &gt; arr2.length ? arr1.length : arr2.length;
  const result = new Array(len).fill(0);

  return result.map((_, index) =&gt; sumNumber(arr1[index] || 0, arr2[index] || 0));
}
</code></pre>
<p><strong>/utils/file-i-want-to-test.spec.ts</strong></p>
<pre><code>import { sumArrays } from './file-i-want-to-test';

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

  describe('Function - sumArrays', () =&gt; {

    it('should return empty array', () =&gt; {
      const actual = sumArrays([], []);
      expect(actual).toEqual([]);
    });

    it('should call sumValue 2 times', () =&gt; {
      const actual = sumArrays([1, 2], [3, 4]);

      // How to test that sumArray is actually calling his dependency sumNumber?
    });
  });
});
</code></pre>
<p><strong>Problem</strong></p>
<p>In order to unit test function <em>sumArrays</em> properly, I need to stub it's dependency <em>sumNumber</em>.
How it can be done?</p>
",https://stackoverflow.com/questions/64221651/stub-file-imports-in-angular-2-unit-testing,"['angular', 'typescript', 'unit-testing', 'stubbing', 'angular-unit-test']",213,True,1,1
ERROR: https://www (unittest.loader._FailedTest) while Unit Testing,"<p>Currently trying to write a unittest for a particular function. The error is shown below: </p>

<pre><code>E
======================================================================
ERROR: https://www (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'https://www'

----------------------------------------------------------------------
Ran 1 test in 0.000s

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

<p>While the funtion itself has not been called within the Test function, I am trying to initialize a class <code>Hasher</code> inside the test. Commenting out the initialization line leads to the program running. </p>

<pre><code>class Test(unittest.TestCase): 

def test_YT(self): 
        self.H = Hasher()
        self.assertTrue(True)
</code></pre>

<p>The code for the class is shown below: </p>

<pre><code>class Hasher:

    import hashlib 

    def __init__(self, hash_algo='md5'): 
        print('we getting here')
        # TODO: support for more hash algos
        self.hash_algo = hash_algo 


    def hash_file(self, filename):

        return hashlib.md5(open(filename, 'rb').read()).hexdigest()


    def compare_file_txt(self, filename, hash_txt_file):
        # Useful for when there is an MD5 txt in the folder

        hash1 = self.hash_file(filename)

        if hash1 == open(hash_txt_file).readline():
            return True

        return False


    def YT_create_hash(self, link, output_loc='test_hash.txt'):

        DL = Downloader()
        file_name = DL.YT_extract(link)
        hash_txt = self.hash_file(os.getcwd() + '/' + file_name)
        o_file = open(output_loc, 'w')
        o_file.write(hash_txt)
        o_file.close()
</code></pre>

<p>There's nothing in the class initialization which indicates that it is using <code>'https://www'</code>, so not really sure where this error is coming from. </p>

<p>My imports are in the form of: </p>

<pre><code>from Hasher import *
from Downloader import *
</code></pre>

<p>And my file structure right now is: </p>

<p><a href=""https://i.stack.imgur.com/Ds1iI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Ds1iI.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/60885590/error-https-www-unittest-loader-failedtest-while-unit-testing,"['python', 'python-3.x', 'unit-testing', 'python-3.7', 'python-unittest']",7379,True,1,1
Exclude @SpringBootApplication class for unit testing with @RestClientTest,"<p>I have a simple service class that uses <code>RestTemplate</code>. I am testing it with <code>@RestClientTest</code> and expecting to initialize only required service bean</p>

<pre><code>@SpringBootApplication
class DemoApplication {
    @Bean fun restTemplate() = RestTemplateBuilder().build()

    @Bean fun xyzService() = XyzService()
}

@Service
class MyServiceImpl(private val restTemplate: RestTemplate): MyService {
    override fun fetch(id: String) {
        print(restTemplate.getForObject(URI(""http://localhost:9090""), String::class.java))
    }
}

@RestClientTest(MyServiceImpl::class)
@AutoConfigureWebClient(registerRestTemplate = true)
class MyServiceTest {
    @Autowired
    private lateinit var mockServer: MockRestServiceServer
    @Autowired
    private lateinit var myService: MyService

    @Test
    fun test(){
        mockServer.expect(ExpectedCount.once(), MockRestRequestMatchers.requestTo(URI(""http://localhost:9090"")))
            .andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
            .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(""hello world""))

        myService.fetch(""123"")

    }
}
</code></pre>

<p>I want to exclude the <code>DemoApplication</code> from being initialized in the test, only beans of service classes to be tested. Problem is that the bean initialization of <code>xyzService</code> fails (it has dependency on RabbitTemplate), and I don't want to mess up the test code with mocks.</p>
",https://stackoverflow.com/questions/60600976/exclude-springbootapplication-class-for-unit-testing-with-restclienttest,"['spring-boot', 'unit-testing', 'kotlin', 'spring-test', 'junit5']",337,False,1,1
Mocking and Validating Results in RxSwift Unit Testing,"<p>I have just started learning RxSwift and trying to build a sample application to practice these concepts. </p>

<p>I have written a QuestionViewModel that loads list of questions from QuestionOps class. QuestionOps has a function getQuestions that returns Single&lt;[Question]>.</p>

<p>Problem that I am facing is, how to mock the behavior of QuestionOps class while testing QuestionViewModel.</p>

<pre><code>public class QuestionsListViewModel {

    public var questionOps: QuestionOps!

    private let disposeBag = DisposeBag()
    private let items = BehaviorRelay&lt;[QuestionItemViewModel]&gt;(value: [])
    public let loadNextPage = PublishSubject&lt;Void&gt;()
    public var listItems: Driver&lt;[QuestionItemViewModel]&gt;
    public init() {
        listItems = items.asDriver(onErrorJustReturn: [])

        loadNextPage
            .flatMapFirst { self.questionOps.getQuestions() }
            .map { $0.map { QuestionItemViewModel($0) } }
            .bind(to: items)
            .disposed(by: disposeBag)
    }
}
</code></pre>

<pre><code>public class QuestionOps {

    public func getQuestions() -&gt; Single&lt;[Question]&gt; {

        return Single.create { event -&gt; Disposable in

            event(.success([]))
            return Disposables.create()
        }
    }
}
</code></pre>

<p>I have created this MockQuestionOps for test purpose:</p>

<pre><code>public class MockQuestionOps : QuestionOps {

    //MARK: -
    //MARK: Responses
    public var getQuestionsResponse: Single&lt;[Question]&gt;?

    public func getQuestions() -&gt; Single&lt;[Question]&gt; {
        self.getQuestionsResponse = Single.create { event -&gt; Disposable in

            return Disposables.create()
        }
        return self.getQuestionsResponse!
    }
}
</code></pre>

<p>In my test case I am doing the following:</p>

<pre><code>/// My idea here is to test in following maner:
/// - at some point user initates loading
/// - after some time got network response with status true
func testLoadedDataIsDisplayedCorrectly() {

    scheduler = TestScheduler(initialClock: 0)
    let questionsLoadedObserver = scheduler.createObserver([QuestionItemViewModel].self)

    let qOps = MockQuestionOps()
    vm = QuestionsListViewModel()
    vm.questionOps = qOps
    vm.listItems
        .drive(questionsLoadedObserver)
        .disposed(by: disposebag)

    // User initiates load questions
    scheduler.createColdObservable([.next(2, ())])
        .bind(to: vm.loadNextPage)
        .disposed(by: disposebag)

    // Simulating question ops behaviour of responding
    // to get question request

    /// HERE: -----------    
    /// This is where I am stuck
    /// How should I tell qOps to send particular response with delay

    scheduler.start()

    /// HERE: -----------
    /// How can I test list is initialy empty
    /// and after loading, data is correctly loaded
}
</code></pre>
",https://stackoverflow.com/questions/59813484/mocking-and-validating-results-in-rxswift-unit-testing,"['ios', 'rx-swift', 'rxtest']",2027,True,1,1
Stuck with unit testing largest number in array,"<p>I am a bit new to C# and unit testing, and we have an assignment in school that I have a hard time understanding, and under the circumstances of corona and school at home, it has been difficult for me to get help from my teacher.</p>

<p>My assignment is to make a method that finds the largest number in an array, and then test it. The array shall also be allowed to be empty.</p>

<p>This is what I have so far:</p>

<pre><code>public class Large
{
    public int Find(int[] mynumbers)
    {
        int mylargest = mynumbers[0];

        for (int i = 0; i &lt; mynumbers.Length; i++)
        {
            if (mynumbers[i] &gt; mylargest) mylargest = mynumbers[0];
        }
        return mylargest;
    }
}
</code></pre>

<p>My teacher made this method but I don't really understand the loop.
I tried to make a test method, but it keeps returning the first integer in my array, as the expected number.</p>

<pre><code>[TestMethod]
public void TestMethod1()
{
    //arrange
    Large mynumber = new Large();

    //act
    int[] myarray = { 3, 5, 1, 7, 3, 8 };
    int result = mynumber.Find(myarray);

    //assert
    Assert.AreEqual(3, result);
}
</code></pre>

<p>When I try this, my test gets passed. But when I change the result (which should have been the biggest), it fails.</p>

<p>What am I not getting?</p>

<p>To sum up:</p>

<ul>
<li>I have to test my method, to see that it indeed finds the largest number</li>
<li>I have to test my method so it won't throw and exception when the array is empty</li>
<li>I don't understand it at all, and my teacher can't explain it to me...</li>
</ul>
",https://stackoverflow.com/questions/61442068/stuck-with-unit-testing-largest-number-in-array,"['c#', 'arrays', 'unit-testing', 'methods']",599,True,1,1
Django Rest Framework unit testing for PUT request,"<p><strong>""test_put_method_success"" is showing AssertionError: 404 != 200. How to solve it?</strong>  ......................</p>

<pre><code>class BasicTest(APITestCase):
    def setUp(self):
        self.client = Client()
        self.user = User(username=""admin"", email=""admin@gmail.com"")
        self.user.is_staff = True
        self.user.set_password('admin')
        self.user.save()


    def test_put_method_success(self):
        url = ""http://127.0.0.1:8000/settings/modules/1/""
        data = {
            'modulename': ""Module test update"",
            'activation_status': ""Active""
        }

        self.assertTrue(self.client.login(username=""admin"", password=""admin""))
        response = self.client.put(url, data, format='json')
        print(response.status_code)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
</code></pre>

<p><strong>urls.py</strong></p>

<pre><code>from rest_framework import routers

router = routers.DefaultRouter()
router.register('modules', views.ModuleView)

urlpatterns = [
    path('', include(router.urls)),
]
</code></pre>
",https://stackoverflow.com/questions/61226627/django-rest-framework-unit-testing-for-put-request,"['django', 'django-rest-framework', 'python-unittest', 'django-testing']",552,True,1,1
&quot;Security&quot; class not found when doing unit testing,"<p>I'm discovering unit testing with phpunit and I want to test some method inside my service. </p>

<p>Here is my test code to do so: </p>

<pre><code>&lt;?php

namespace App\Tests;

use App\Services\SortingDataSearchedProductService;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SearchedProductTest extends WebTestCase
{

    private $sortingDataSearchedProductService;

    public function setUp()
    {
        self::bootKernel();
        $container = self::$container;
        $this-&gt;sortingDataSearchedProductService = $container-&gt;get(SortingDataSearchedProductService::class);
    }

    public function testFindStatusLinkedToGrantedRoles() {
        $grantedRolesList = [];

        $this-&gt;sortingDataSearchedProductService-&gt;findStatusLinkedToGrantedRoles($grantedRolesList);
    }

}
</code></pre>

<p>But when I try my test here is what I get:</p>

<blockquote>
  <p>Cannot autowire service ""App\Form\CpomAf\SearchProductType"": argument ""$security"" of method ""__construct()"" references class ""Symfony\Component\Security\Core\Security"" but no such service exists.</p>
</blockquote>

<p>I think I get this error because the testing is going through the page where the function I want to test is. Here is the service I want to test : </p>

<pre><code>&lt;?php

namespace App\Services;


use App\Entity\Custom\SearchProduct;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Security;
use App\Entity\User;
use Symfony\Component\Yaml\Yaml;

/**
 * Class SortingDataSearchedProductService
 * @package App\Services
 */
class SortingDataSearchedProductService
{
    /**
     * @var Security
     */
    private $security;


    /**
     * SortingDataSearchedProductService constructor
     * @param Security $security
     */
    public function __construct(Security $security)
    {
        $this-&gt;security = $security;
    }

    /**
     * Form Data
     * @param SearchProduct $searchedData
     *
     * @return array
     */
    public function findDataOfSearchWithConditions(SearchProduct $searchedData): array
    {
        /** @var User $user */
        $user = $this-&gt;security-&gt;getUser();
        $userPermissions = $user-&gt;getPermissions();

        return $this-&gt;findStatusLinkedToGrantedRoles(
            $userPermissions
        );
    }

    /**
     * Get array of final list of granted roles
     *
     * @param array $userPermissions
     * @return array
     */
    public function findStatusLinkedToGrantedRoles(array $userPermissions): array
    {
        //Getting the list of role linked to status from yaml file
        $permissionStatusList = Yaml::parseFile(dirname(__DIR__).'/../config/roles.yaml');
        $arrayPermissionListStatus = $permissionStatusList[0];

        //Declaration array status list
        $statusList = [];

        //Getting status linked to permissions
        foreach ($userPermissions as $userPermission) {
            if (array_key_exists($userPermission, $arrayPermissionListStatus)) {
                foreach ($arrayPermissionListStatus[$userPermission] as $status) {
                    array_push($statusList, $status);
                }
            }
        }

        //Deleting double values
        return  array_values(array_unique($statusList));
    }

}
</code></pre>

<p>I understand my error refers to my formtype file but in the service I'm targetting the only thing that links to my form is <strong>$searchedData</strong> which this the data returned by the submission of my form (that I'm not using yet). Hence, I'm not sure why it's going through my form type file and why it doesn't consider Security as a class. </p>

<p>I tried to use MockBuilder like so in my set up but it didn't help. Maybe I'm using unit testing in the wrong way ? </p>

<pre><code>$this-&gt;getMockBuilder('Symfony\Component\Security\Core\SecurityContextInterface')
           -&gt;disableOriginalConstructor()
           -&gt;getMock();
</code></pre>

<p><strong>EDIT</strong> </p>

<p>Here is the content inside my autoload classmap file after I did the dump autoload command : </p>

<pre><code>    &lt;?php

// autoload_classmap.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Collator' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/Collator.php',
    'IntlDateFormatter' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/IntlDateFormatter.php',
    'JsonException' =&gt; $vendorDir . '/symfony/polyfill-php73/Resources/stubs/JsonException.php',
    'Locale' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/Locale.php',
    'NumberFormatter' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/NumberFormatter.php',
    'SqlFormatter' =&gt; $vendorDir . '/jdorn/sql-formatter/lib/SqlFormatter.php',
);
</code></pre>

<p>I if remember correctly it regenerates the list of all classes that need to be included in the project. So it means that security is there isn't it? </p>
",https://stackoverflow.com/questions/61060162/security-class-not-found-when-doing-unit-testing,"['symfony', 'phpunit']",183,False,1,0
Unit testing asynchronous code including setInterval in Angular,"<p>I am using Angular 7+.</p>
<p><strong><code>Summary of the problem :</code></strong></p>
<p>I have a code inside which there is a <code>setInterval</code> method which calls a url method of a service to retrieve data every <code>1000 milliseconds</code>. Also note that i do not want my program to first wait for 1000 ms and then call the url method, i.e why i have <em>pre called</em> the method <em><strong>only once</strong></em> before setInterval. Do let me know how to <code>test</code> this exact same behaviour. Also please do not bother much about the implementation as it is done according to <strong>business requirement which i cannot disclose</strong>.</p>
<p><strong><code>Problem Statement:</code></strong></p>
<p>Suppose i have a url to which i check every 1 second whether i am getting data or not. The call to this url is made inside a function <code>getDataFromUrl</code> , inside a <code>service</code> injected into the component.</p>
<p>Please refer the code below.</p>
<pre><code>someStorage = {};

constructor(private service: someService){}
ngOnDestroy(){
   clearInterval(this.clearPeriodicRefresh);
}

ngOnChanges(){
    let context = this;
    this.periodicRefresh(context);
    this.clearPeriodicRefresh = setInterval(function(){
        this.periodicRefresh(context);
    },1000);
}

periodicRefresh(self){
    self.service.getDataFromUrl(url).subscribe(res =&gt; {
        someStorage[res] = true;
    },
    err =&gt;{
       console.log(&quot; Error Occured &quot;); 
    });
}

</code></pre>
<p>Now i am unit testing the code like this:</p>
<pre><code>it('should check for async data from url', fakeAsync()=&gt;{
    someServiceStub.getDataFromUrl.and.returnValue(of(&quot;chandni chowk&quot;));
    fixture.detectChanges();
    expect(component.someStorage[&quot;chandni chowk&quot;]).toBe(true); // executes successfully
    
    setInterval(()=&gt;{
        someServiceStub.getDataFromUrl.and.returnValue(of(&quot;delhi&quot;));    
    },1000);
    
    tick(1000); // in milliseconds
    discardPeriodicTasks();
    
    expect(component.someStorage[&quot;delhi&quot;]).toBe(true);          // throws error
    
}));
</code></pre>
<p>The second expect statement shows :</p>
<pre><code>ERROR : expected undefined to be true
</code></pre>
<p>I do not know the reason why . However, if i do a <strong><code>tick(2000)</code></strong> instead of <strong><code>tick(1000)</code></strong>, then it works. Again i am not sure why it gets skipped earlier.</p>
<p><strong><code>NOTE</code></strong> : Any timer between 1000 and 2000 i.e for example till <code>tick(1900)</code> throws the same error, and anytime after 2000 milliseconds works fine.</p>
<p><strong>Also please tell me how to write better tests if there is any other way for this.</strong></p>
",https://stackoverflow.com/questions/62394625/unit-testing-asynchronous-code-including-setinterval-in-angular,"['angular', 'unit-testing', 'asynchronous']",250,False,0,0
Unit testing firebase admin SDK authentication on node.JS,"<p>Is there any way I can write unit tests for firebase authentication to store locally? I want to do something like mongodb-memory-server, so all the data saved doesn't persists when the tests are over. I want to create some tests to those two functions specifically:</p>
<pre><code>async function createResearcherOnFirebase(email, password) {
  return admin.auth().createUser({
    email,
    password,
  }).then((researcherRecord) =&gt; researcherRecord.uid).catch(() =&gt; false);
}


async function grantResearcherRole(uid) {
  return admin.auth().setCustomUserClaims(uid, { researcher: true })
    .then(() =&gt; true).catch(() =&gt; false);
}
</code></pre>
",https://stackoverflow.com/questions/63163853/unit-testing-firebase-admin-sdk-authentication-on-node-js,"['node.js', 'firebase', 'firebase-authentication', 'jestjs', 'firebase-admin']",1106,True,0,1
Unit Testing in Production Folder and Source Folder,"<p>I have created an installer for my java project. Using the installer, the user can install the software specifying where the program should be installed, where the program data folder should be located, so on and so forth. After the program is installed, like any other windows software he can open it and start using. The project basically makes some processing on files, and then writes those files to the program data folder something like C:\Program Data\MyProduct\data\myoutput.png .</p>
<p>Now, when I want to unit test the logic of saving files into the right place, I can't use the above location which is so-called production environment. Because, a developer who works on it doesn't have to install the software to test how the program works, or if he wants to see the output of his change. Instead, what I did is that during the execution of the program, I retrieve the information of where the program is running. If the program is running on production environment it uses this production path for outputting, if it runs on eclipse, it creates some dummy folder inside the source code folder to save the output of the processing so that the developer can check the output instead of tangling with the production folder.</p>
<p>Accordingly, I want to write unit test for the logic of saving of a file to the right place, like how the document is processed and then successfully saved into the folder. However, I don't want to touch to production folder because a developer who checked out the source code might not have installed the program just for running unit tests. Because he runs the program on eclipse, a dummy folder will be created and he will check from there.(these created folders are removed after the unit tests automatically via the unit test code). But in this case, I'll be able to check only if the file is saved correctly inside the source code dummy folder. It basically wont detect if the production folder logic is fine.</p>
<p>How could I change my approach on it to check things more correctly?</p>
",https://stackoverflow.com/questions/62511702/unit-testing-in-production-folder-and-source-folder,"['java', 'unit-testing', 'junit', 'mockito', 'junit5']",144,False,0,0
moq for mediator using generics in unit testing,"<p>I use cqrs and mediatr in .net core 3 webapi project. I want to unit test controller methods behavior, so when the method is called, mediator does it work as expected. I wrote testing code for one method and it works fine. Many code is omitted for brevity, I only used code which causes the error. So, working test:</p>

<pre><code>        var mockScrapedAd = ScrapedAd.CreateMockAd(DateTime.Now); //result of controller method

         mediatrMock.Setup(m =&gt;
             m.Send(It.IsAny&lt;QueryDetails&gt;(),
                 It.IsAny&lt;CancellationToken&gt;())).
             ReturnsAsync(() =&gt; mockScrapedAd); //mock for mediator,
         // so when something with QueryDetails type is called, it should return result from above

        var ret = await controller.Details(0); //should send QueryDetails via Mediatr

        Assert.Equal(mockScrapedAd, ret.Value); //all good?

       mediatrMock.Verify(x =&gt; x.Send(It.IsAny&lt;QueryDetails&gt;(), //was it called at all?
           It.IsAny&lt;CancellationToken&gt;()));
</code></pre>

<p>This test works, but I will have to duplicate code for each controller method. The only thing that changes here is type of mediatr request (QueryDetails here) and mock for return.
So I tried to use generic method like here:</p>

<pre><code>    async Task TestBase&lt;TK,K&gt;(TK expectedResult,Func&lt;Task&lt;ActionResult&lt;TK&gt;&gt;&gt; callControllerMethod)
    {

        mediatrMock.Setup(m =&gt;
            m.Send(It.IsAny&lt;K&gt;(),
                It.IsAny&lt;CancellationToken&gt;())).ReturnsAsync(() =&gt; expectedResult);

        var ret = await callControllerMethod();

        Assert.Equal(expectedResult, ret.Value);

       mediatrMock.Verify(x =&gt; x.Send(It.IsAny&lt;K&gt;(),
           It.IsAny&lt;CancellationToken&gt;()));

    }
</code></pre>

<p>And the test suite will be easier:</p>

<pre><code>     var mockScrapedAd = ScrapedAd.CreateMockAd(DateTime.Now);            

        await TestBase&lt;ScrapedAd,QueryDetails&gt;(mockScrapedAd, async () =&gt; await controller.Details(0));
</code></pre>

<p>Basically all I changed is moved QueryDetails inside generic method. Mediator fails to recognize it and response is not called. What's wrong here?</p>
",https://stackoverflow.com/questions/61136158/moq-for-mediator-using-generics-in-unit-testing,"['c#', 'generics', 'moq', 'xunit', 'mediator']",2510,False,0,0
Problems implementing ToString specialization for unit testing c++,"<p>Right now i'm busy writing an event based queue. I wanted to do some unit testing but i'm running into an error. In Microsoft Visual Studio, when making a unit test project, you have to implement this function for each type you do an assert on:</p>
<pre><code>namespace Microsoft
{
    namespace VisualStudio
    {
        namespace CppUnitTestFramework
        {
            template&lt;&gt; static std::wstring ToString&lt;T&gt;&gt;(const class T&amp; t)
            {
                //code goes here
            }
        }
    }
}
</code></pre>
<p>the problem is that the queue is not changing the object that was passed into it. because of this i wanted to write a unit test that verified that the object pointed to in the queue, was the same address as the object outside of the queue. I wrote the test as follows:</p>
<pre><code>TEST_METHOD(REGISTERED_PROCESSORS_HAVE_ACCURATE_ADDRESSES_IN_QUEUE_MANAGER)
{
    QueueProcessor queue;
    ActionProcessor processor;

    processor.loadFromJson({ {actionProcessorProperties::QUEUE_NAME, &quot;alpha&quot;} });
    
    queue.registerProcessor(&amp;processor);

    Assert::AreEqual(&amp;processor, queue.processors[&quot;alpha&quot;][0]);
}
</code></pre>
<p>i then get this error:</p>
<pre><code>Test writer must define specialization of ToString&lt;Q* q&gt; for your class class std::basic_string&lt;wchar_t,struct std::char_traits&lt;wchar_t&gt;,class std::allocator&lt;wchar_t&gt; &gt; __cdecl Microsoft::VisualStudio::CppUnitTestFramework::ToString&lt;class ActionProcessor&gt;(class ActionProcessor *).
</code></pre>
<p>so how do I implement <code>ToString</code> on a pointer? when I try putting the data type in the compiler complains. Also how do I then display the pointer as a string value?</p>
<p>thanks for the help.</p>
<h3>edit:</h3>
<p>i found the unit test works fine if you convert the pointers to uintptr_t. However the type conversion mid assert kinda messes up the readability of the code. Is there a cleaner solution?</p>
<pre><code>TEST_METHOD(REGISTERED_PROCESSORS_HAVE_ACCURATE_ADDRESSES_IN_QUEUE_MANAGER)
{
    QueueProcessor queue;
    ActionProcessor processor;

    processor.loadFromJson({ {actionProcessorProperties::QUEUE_NAME, &quot;alpha&quot;} });
    
    queue.registerProcessor(&amp;processor);

    Assert::AreEqual(reinterpret_cast&lt;uintptr_t&gt; (&amp;processor),
                     reinterpret_cast&lt;uintptr_t&gt;(queue.processors[&quot;alpha&quot;][0]));
}
</code></pre>
",https://stackoverflow.com/questions/61264252/problems-implementing-tostring-specialization-for-unit-testing-c,"['c++', 'visual-studio', 'unit-testing']",286,True,0,1
Cannot shallowMount a Vue Compoent for unit testing,"<p>I'm new to Vue, but have a project with a login page. I can run it fine, but I'm trying to retro-add unit-testing (I know, I'm doing this backwards). I'm using Mocha + Chai and vue test utils. when I try to shallowMount I get an error saying that it cannot read a property. Here is the full error text:</p>

<pre><code>  1) Login
       Has login text:
     TypeError: Cannot read property 'email' of undefined
      at Proxy.render (webpack:///./src/views/user/Login.vue?./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options:65:34)
      at VueComponent.Vue._render (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:3640:22)
      at VueComponent.updateComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4168:21)
      at Watcher.get (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4582:25)
      at new Watcher (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4569:45)
      at mountComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4175:3)
      at VueComponent.Vue.$mount (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:8512:10)
      at init (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:3232:13)
      at createComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:6053:9)
      at createElm (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:6001:9)
      at VueComponent.patch [as __patch__] (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:6611:7)
      at VueComponent.Vue._update (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4039:19)
      at VueComponent.updateComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4168:10)
      at Watcher.get (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4582:25)
      at new Watcher (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4569:45)
      at mountComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4175:3)
      at VueComponent.Vue.$mount (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:8512:10)
      at mount (webpack:///./node_modules/@vue/test-utils/dist/vue-test-utils.js?:13265:21)
      at shallowMount (webpack:///./node_modules/@vue/test-utils/dist/vue-test-utils.js?:13278:10)
      at Context.eval (webpack:///./tests/unit/login.spec.js?:17:87)
      at processImmediate (internal/timers.js:439:21)
</code></pre>

<p>Here is my packages file:</p>

<pre><code>{
  ""name"": ""client"",
  ""version"": ""0.1.0"",
  ""private"": true,
  ""scripts"": {
    ""serve"": ""vue-cli-service serve"",
    ""build"": ""vue-cli-service build"",
    ""test:unit"": ""vue-cli-service test:unit"",
    ""test:e2e"": ""vue-cli-service test:e2e"",
    ""test"": ""mochapack --webpack-config webpack.config.js --require tests/setup.js tests/**/*.spec.js""
  },
  ""dependencies"": {
    ""axios"": ""^0.19.2"",
    ""core-js"": ""^3.6.4"",
    ""vue"": ""^2.6.11"",
    ""vue-axios"": ""^2.1.5"",
    ""vue-router"": ""^3.1.5"",
    ""vuelidate"": ""^0.7.5"",
    ""vuetify"": ""^2.1.0"",
    ""vuex"": ""^3.1.2""
  },
  ""devDependencies"": {
    ""@vue/cli-plugin-babel"": ""^4.2.0"",
    ""@vue/cli-plugin-e2e-cypress"": ""^4.2.0"",
    ""@vue/cli-plugin-router"": ""^4.2.0"",
    ""@vue/cli-plugin-unit-mocha"": ""^4.2.0"",
    ""@vue/cli-plugin-vuex"": ""^4.2.0"",
    ""@vue/cli-service"": ""^4.2.0"",
    ""@vue/test-utils"": ""^1.0.0-beta.31"",
    ""chai"": ""^4.1.2"",
    ""jsdom"": ""^16.1.0"",
    ""jsdom-global"": ""^3.0.2"",
    ""mocha"": ""^7.0.1"",
    ""mochapack"": ""^1.1.13"",
    ""node-sass"": ""^4.12.0"",
    ""sass"": ""^1.19.0"",
    ""sass-loader"": ""^8.0.2"",
    ""vue-cli-plugin-vuetify"": ""^2.0.4"",
    ""vue-template-compiler"": ""^2.6.11"",
    ""vuetify-loader"": ""^1.3.0""
  }
}
</code></pre>

<p>Here is my component code:</p>

<pre><code>&lt;template&gt;
  &lt;v-container fluid fill-height&gt;
    &lt;v-layout align-center justify-center&gt;
      &lt;v-flex xs12 sm8 md4&gt;
        &lt;v-card class=""elevation-12""&gt;
          &lt;v-toolbar color=""primary"" dark flat&gt;
            &lt;v-toolbar-title&gt;Login form&lt;/v-toolbar-title&gt;
          &lt;/v-toolbar&gt;
          &lt;v-card-text&gt;
            &lt;v-form @submit.prevent=""login""&gt;
              &lt;v-text-field
                autofocus
                v-model=""email""
                label=""Email""
                prepend-icon=""mdi-account-circle""
                @blur=""$v.email.$touch()""
              /&gt;
              &lt;div class=""red--text text--lighten-1"" v-if=""$v.email.$error""&gt;
                &lt;div v-if=""!$v.email.required""&gt;
                  &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                  Email is required
                &lt;/div&gt;
                &lt;div v-if=""!$v.email.email""&gt;
                  &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                  Invalid email address.
                &lt;/div&gt;
              &lt;/div&gt;

              &lt;v-text-field
                v-model=""password""
                :type=""showPassword ? 'text' : 'password'""
                label=""Password""
                prepend-icon=""mdi-lock""
                :append-icon=""showPassword ? 'mdi-eye' : 'mdi-eye-off'""
                @click:append=""showPassword = !showPassword""
                @blur=""$v.password.$touch()""
              /&gt;

              &lt;div
                class=""red--text text--lighten-1""
                v-if=""$v.password.$error &amp;&amp; !$v.password.required""
              &gt;
                &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                Password is required
              &lt;/div&gt;

              &lt;v-btn
                type=""submit""
                color=""success""
                name=""button""
                :disabled=""$v.$invalid""
              &gt;
                Login now
              &lt;/v-btn&gt;

              &lt;v-btn
                text
                small
                color=""primary""
                :to=""{ name: 'forgotPassword' }""
              &gt;
                Forgot your password?
              &lt;/v-btn&gt;

              &lt;div v-if=""error"" class=""red--text text--lighten-1""&gt;
                &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                {{ getLoginErrorMsg() }}
              &lt;/div&gt;
            &lt;/v-form&gt;
          &lt;/v-card-text&gt;
        &lt;/v-card&gt;
      &lt;/v-flex&gt;
    &lt;/v-layout&gt;
  &lt;/v-container&gt;
&lt;/template&gt;

&lt;script&gt;
import { required, email } from ""vuelidate/lib/validators"";

export default {
  name: ""Login"",

  data() {
    return {
      email: """",
      password: """",
      error: null,
      showPassword: false
    };
  },

  validations: {
    email: {
      required,
      email
    },
    password: {
      required
    }
  },

  methods: {
    login() {
      console.log(""Entering component login method"");

      this.$store
        .dispatch(""user/login"", {
          username: this.email,
          password: this.password
        })
        .then(() =&gt; {
          console.log(
            'this.$store.getters[""user/passwordChangeRequired""]' +
              this.$store.getters[""user/passwordChangeRequired""]
          );
          if (this.$store.getters[""user/passwordChangeRequired""]) {
            console.log(""push to changePassword"");
            this.$router.push({ name: ""changePassword"" });
          } else {
            console.log(""pushing to home"");
            this.$router.push({ name: ""home"" });
          }
        })
        .catch(err =&gt; {
          this.error = err.response;
        });
    },

    getLoginErrorMsg() {
      if (this.error.status == 401) {
        return ""Invalid username or password"";
      } else {
        // return `Login failed: {this.error.statusText}`;
        return ""failed"";
      }
    }
  }
};
&lt;/script&gt;

&lt;style&gt;&lt;/style&gt;
</code></pre>

<p>Here is the test file:</p>

<pre><code>import { expect } from ""chai"";
import { mount, shallowMount } from ""@vue/test-utils"";
import Login from ""../../src/views/user/Login.vue"";

describe(""Login"", () =&gt; {

  it(""Has login text"", () =&gt; {
    // const wrapper = mount(Login);
    const wrapper = shallowMount(Login);
    // not getting here.
    expect(2).to.equal(2);
  });
});
</code></pre>

<p>Note: neither mount or shallowMount works. They both throw the same error.</p>

<p>Here is my webpack.config.js file:</p>

<pre><code>const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      // this will apply to both plain `.js` files
      // AND `&lt;script&gt;` blocks in `.vue` files
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      // this will apply to both plain `.css` files
      // AND `&lt;style&gt;` blocks in `.vue` files
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    // make sure to include the plugin for the magic
    new VueLoaderPlugin()
  ]
}
</code></pre>

<p>I've spent hours googling and I can't really find anything. So, I'm clearly doing something really stupid, because no one else seems to be having this issue. Please tell me why it is throwing this error and unable to shallowMount or mount this vue component.</p>
",https://stackoverflow.com/questions/60158928/cannot-shallowmount-a-vue-compoent-for-unit-testing,"['unit-testing', 'vuejs2', 'vue-component']",555,True,0,1
Unit-testing Injector after manually injecting Router (APP_INITIALIZER),"<p>In <code>app.module.ts</code>, I have the following:</p>

<pre><code>{provide: APP_INITIALIZER, useFactory: appServiceFactory, multi: true, deps: [AppService]}
</code></pre>

<p>I was trying to add <code>Router</code> dependency in <code>AppService</code>, but I was getting the following error:</p>

<pre><code>Cannot instantiate cyclic dependency! ApplicationRef...
</code></pre>

<p>I added <code>Injector</code> to my <code>AppService</code> constructor, and manually added <code>Router</code>:</p>

<pre><code>private get router() {
    return this.injector.get(Router);
}
</code></pre>

<p>I successfully use it like so:</p>

<pre><code>this.router.navigate([ routePath ], {queryParams: {type: paramType}})
    .then(() =&gt; {
        return resolve();
    });
</code></pre>

<p>===</p>

<p>For testing, I added <code>Injector</code> to providers, and also stubbed the <code>Router</code>:</p>

<pre><code>let injector: Injector;

const routerStub = {navigate: jasmine.createSpy('navigate')};

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        imports: [],
        providers: [
            AppService,
            ...,
            Injector,
            {provide: Router, useValue: routerStub}
        ]
    });

    injector = TestBed.get(Injector);

    spyOn(injector, 'get').and.returnValue(routerStub);
});
</code></pre>

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

<pre><code>ERROR LOG: 'Unhandled Promise rejection:', 'Cannot read property 'then' of undefined', '; Zone:', 'ProxyZone', '; Task:', 'jasmine.onComplete', '; Value:', TypeError: Cannot read property 'then' of undefined
TypeError: Cannot read property 'then' of undefined
</code></pre>

<p>I tried replacing <code>Router</code> in providers with <code>RouterTestingModule</code> in imports, but still the same error.</p>

<p>Any ideas?</p>

<p>Thank you!</p>

<p>===</p>

<p>Edit: Added <code>routerStub</code></p>

<p>Edit 2: Resolution</p>

<p>Thanks to @Inge Olaisen's input, I was able to resolve the error. Answer(s):</p>

<h1>1 - Stub router with <code>useClass</code> (w/ promise) instead of <code>useValue</code></h1>

<pre><code>class MockRouter {
    navigate(routePath: any[], params: any) {
        return new Promise&lt;boolean&gt;(resolve =&gt; resolve(true));
    }
}

...

{provide: Router, useClass: MockRouter}

...

injector = TestBed.get(Injector);

spyOn(injector, 'get').and.returnValue(routerStub); // Not needed anymore
</code></pre>

<h1>2 - Use <code>RouterTestingModule</code></h1>

<pre><code>let injector: Injector;
let router: Router;

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule
        ],
        providers: [
            AppService,
            ...,
            Injector,
            {provide: Router, useValue: routerStub}
        ]
    });

    injector = TestBed.get(Injector);
    router = TestBed.get(Router);

    spyOn(router, 'navigate').and.returnValue(new Promise&lt;boolean&gt;(resolve =&gt; resolve(true)))
});
</code></pre>
",https://stackoverflow.com/questions/59904192/unit-testing-injector-after-manually-injecting-router-app-initializer,"['angular', 'unit-testing', 'dependency-injection', 'karma-jasmine', 'angular-router']",361,True,0,1
Clojure Unit Testing for Java in Android Studio?,"<p>I'm writing unit-tests in Clojure for a Java library I'm working on.</p>

<p>I'm just writing the tests in separate project that refers to my Java project, running them from the command line with Lein.</p>

<p>But I'm now going back to work on some Android code in Android Studio.</p>

<p>I'd like to continue the same practice there. Ie. writing tests in Clojure. </p>

<p>Is there a way to integrate this into Android Studio (ie. write the Clojure code in Android Studio and compile / run it against the Android project)?</p>
",https://stackoverflow.com/questions/61946522/clojure-unit-testing-for-java-in-android-studio,"['java', 'android', 'android-studio', 'clojure', 'leiningen']",55,False,0,0
unit testing Embedded Source Code using GTEST / GMOCK,"<p>I am newbie to unit testing , I have basic doubt regarding unit testing , I have <strong>middle ware code</strong> which needs to be <strong>unit tested</strong> using <strong>gtest/gmock</strong> , My Middle ware Code talks with Stack code which come as library  .so and my stack library talks with Embedded Hardware ,  So below are few questions I have</p>
<p>(1) Does Unit Testing means , It should  done without Hardware ?, I mean writing stub code for stack since stack talks with H/w and test middle ware functionality on PC  , In that case developers has to know what events stack sends, when some operation is performed and mimic it in stub code</p>
<p><strong>or</strong></p>
<p>(2) Unit Testing means testing by writing test cases from middle ware code which will talk with stack and then to H/w and catch events from from H/W , then to stack and then to Application and , Assert on Events ,  to test whether test case is  case Pass/Fail</p>
<p>Below is diagram , I intend to unit testing to middle ware code using gtest , My Middle ware is application and stack is .so</p>
<p><a href=""https://i.stack.imgur.com/n1jqj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/n1jqj.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63371203/unit-testing-embedded-source-code-using-gtest-gmock,"['unit-testing', 'embedded', 'googletest']",649,True,0,2
Unit testing for REST API using node Js,"<p>I want to write unit testing for my REST API calls(Using mocha and chai).
Can anyone provide me better guide or any previously written code ,so that I can perform easily.</p>
",https://stackoverflow.com/questions/64692710/unit-testing-for-rest-api-using-node-js,"['api', 'unit-testing', 'mocha.js', 'chai']",399,True,0,1
(Google unit Testing) invalid use of void expression,"<p>I'm attempting to run a unit test and keep getting this error. Is it not possible to test void functions with no return type? Also, I haven't passed in any arguments to my virtual void member functions so could that be it as well?</p>
<pre><code>#ifndef __FACTORY_TEST_HPP__
#define __FACTORY_TEST_HPP__
#include &quot;gtest/gtest.h&quot;
#include &quot;USN_Fleet_Factory.h&quot;
#include &quot;USN_Ship.h&quot;
#include &quot;GF_Class.h&quot;
#include &quot;T_Class.h&quot;
#include &quot;AB_Class.h&quot;
#include &quot;WH_Class.h&quot;
#include &lt;iostream&gt;

TEST(FactoryTestSet, ShipNameTest) {
    USN_Fleet_Factory* makeAShip;
    USN_Ship *make;
    makeAShip = new USN_Ship_Factory;
    make = makeAShip-&gt;CreateAircraftCarrier(&quot;Aircraft Carrier&quot;);
    EXPECT_EQ(make-&gt;ShipName(), &quot;- USS Gerald R. Ford&quot;);

}
#endif //__FACTORY_TEST_HPP__ 
</code></pre>
",https://stackoverflow.com/questions/62286504/google-unit-testing-invalid-use-of-void-expression,['c++'],157,False,0,0
TestNG how to test exceptions in unit testing,"<p>I need to test the Exception but it gets the following error.</p>
<pre><code>org.testng.TestException: 
Method ContactIdentifierHelperTest.test()
[pri:0, instance:se.cambio.contactadministration.contact.helper.ContactIdentifierHelperTest@6d7b4f4c]
 should have thrown an exception of type class SpiderException
</code></pre>
<p>Test method:</p>
<pre><code>  @Test(expectedExceptions = { SpiderException.class })
  public void test()  {
    ContactData contactData = getContactData();
    contactIdentifierHelper.getSpellId(contactData);
  }
</code></pre>
<p>Method tested:</p>
<pre><code>  public String getSpellId(final ContactData contactData)
  {
    String s = null;
    try
    {
      s = someMethod();
    }
    catch (SpiderException e)
    {
      e.printStackTrace();
    }
    return s;
  }
</code></pre>
<p>Where have I gone wrong in this?</p>
",https://stackoverflow.com/questions/64676111/testng-how-to-test-exceptions-in-unit-testing,"['java', 'unit-testing', 'exception', 'testng']",161,True,0,2
regarding unit testing in node js with sinon,"<pre><code>class FetchTenant {

    constructor (){
        this.Config = this._getConfig();
        this.Token = this._getToken();
        this.TenantMap = new Map();
    }

    async getTenantId(Id){

        if(!this.TenantMap[Id]){
            const serviceid = await this._getInfo(Id, false);
            this.TenantMap[Id] = serviceid;
        }

        return this.TenantMap[Id];
    }

    _getConfig() {
        return get_env_from_local({ name: 'env_1' });
    }

    async _getToken() {

        const options = {
          method: 'POST',
          uri: `${this.Config.url}`,
          json: true,
          resolveWithFullResponse: false,
          transform2xxOnly: true,
          transform: body =&gt; body.access_token,
          auth: {
            username: this.Config.clientid,
            password: this.Config.clientsecret
          },
          form: {
            grant_type: 'client_credentials'
          },
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        };

        return request(options)
          .catch(err =&gt; {
            logger.error('Could not get Token', err.statusCode, err.message);
            return null;
        });
    }

    async _getInfo(Id, newtoken) {
        if(newtoken){
            this.accessToken = await this._getToken();
            if(this.accessToken == null){
              logger.error(`fetching token failed`);
              return null;
            }
        }

        const options = {
          method: 'GET',
          uri: `${this.Config.url}/xyz/${Id}`,
          json: true,
          resolveWithFullResponse: false,
          transform2xxOnly: true,
          transform: body =&gt; body.tenantId,
          auth: {
            bearer: this.accessToken
          },
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          }
        };

        return request(options)
          .catch(err =&gt; {
              if(err.statusCode != 401) {
                logger.error(`Could not get tenant id`, err.statusCode, err.message);
                return null;
              }
              else {
                return this._getServiceInstanceInfo(Id, true);
              }
          });
    }

}

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

<p>this is the class that i have created.</p>

<p>how to write a unit test for this class using sinon (stub and mock),i have to test only the public functions and the only public function here is <code>getTenantId(Id)</code> where in all the other private functions have a http request which can give either a valid response or an error.</p>

<p>is there any way to test the public function by mocking all the other private functions. i want to pre-define the data which will be returned by each private function and the primary data they fetch from env and use to send the request.</p>
",https://stackoverflow.com/questions/59784255/regarding-unit-testing-in-node-js-with-sinon,"['node.js', 'mocking', 'sinon', 'stub']",158,False,0,1
What does SetUp do in odoo unit testing?,"<p>in odoo there are some examples like this</p>

<pre class=""lang-py prettyprint-override""><code>def setUp(self):
        super(TestClass, self).setUp()
        # write tests here
</code></pre>

<p>what does this mean because writing the same code in a separate method will give same result</p>
",https://stackoverflow.com/questions/62247199/what-does-setup-do-in-odoo-unit-testing,"['python', 'unit-testing', 'odoo-13']",64,True,0,1
C++ Unit testing - using hardcoded or generated array,"<p>Let's say I'writing c++ driver for controlling some device on the serial bus. This is simplified version of the problem.
I have class <code>DeviceDriver</code> that have <code>std::vector&lt;unsigned char&gt; transmitFrames(int deviceNumber)</code> method. It returns two significant bytes followed by constant number of zero values. The pattern is:</p>

<p><code>transmitFrames(0)</code> should return <code>{0xFF, 0xFF}</code>,
<code>transmitFrames(1)</code> should return <code>{0xFF, 0xFF, 0x00, 0x00}</code>,
<code>transmitFrames(2)</code> should return <code>{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00}</code>...</p>

<p>When testing this method should I use hardcoded expected arrays or should I generate it somewhere?
Hardcoded version it's nearly impossible to write because <code>transmitFrames(100)</code> will return the vector of many values. Generated version would be okay but what about algorithm? It will be the same as in the class. This would break DRY rule and of course testing algorithm would have still bug. I'm using googletest framework. How to deal with problems like long arrays in unit testing?</p>
",https://stackoverflow.com/questions/61596302/c-unit-testing-using-hardcoded-or-generated-array,"['c++', 'unit-testing', 'googletest', 'googlemock']",172,False,0,0
Angular unit testing - how to test different route.snapshot.paramMap,"<p>In my ngOnInit function, I look at the URL and see if a parameter exists within that URL. If it does, certain actions are taken. If not, other actions are taken.</p>
<pre><code>this.userId = this.route.snapshot.paramMap.get('id');

if ( (this.userId == '') || ( this.userId === null ) )
{
    ...
}else
{
    ...
}
</code></pre>
<p>I can mock the route.snapshot.paramMap in my test setup, but I obviously want to able to test for the case where the id is set in the route and the case where it is not set. How can I run both of these tests?</p>
<pre><code>    TestBed.configureTestingModule({
        declarations: [ ProfileComponent ],
        providers: [ { provide: FuseTrans },
                     { provide: ActivatedRoute,     useValue : ActivatedRouteStub },
                     { provide: MatDialog,          useValue : DialogStub },
                     { provide: UserService,        useClass : UserServiceStub },
                     { provide: AuthService,        useValue : AuthServiceStub },
                     { provide: FirebaseService,    useValue : FirebaseServiceStub },
                     { provide: MatSnackBar,        useValue : SnackBarStub },
                     { provide: AngularFireStorage, useValue : AngularStorageStub } ]

    });
</code></pre>
<p>Here is the route stub. I can obviously get the test to run with any value at the &quot;get&quot; method. However, how do I automate the process of changing this value and rerunning the test?</p>
<pre><code>public ActivatedRouteStub() {
    return { 'snapshot': {
                'url': [{ 'path': 1 }, { 'path': 2 }],
                'paramMap' : {
                    'get' : ()=&gt;1,
                    'set' : ()=&gt;{},
                }
            }
        
    }
}
</code></pre>
",https://stackoverflow.com/questions/62526330/angular-unit-testing-how-to-test-different-route-snapshot-parammap,"['angular', 'unit-testing', 'karma-jasmine', 'angular-test']",428,False,1,0
Unit Testing in Angular not.toBe(true) vs toBeFalsy(),"<p>I am writing a Angular Unit Testing which I am facing with an error.
If I write toBeFalsy() the test will fail.
But If I write not.toBe(true) the test will work.</p>

<p>May someone help me.</p>

<pre><code>let fixture: ComponentFixture&lt;RootComponent&gt;;
let debugElement: DebugElement;

beforeEach(async () =&gt; {
    fixture = TestBed.createComponent(RootComponent);
    await executeChangeDetection(fixture);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement.query(By.css('#overlay'));
  });


it('should hide overlay and reset timeout', () =&gt; {
    const appState = new ApplicationStateService(null as any);
    appState.timeout = false;
    component.isTimeoutOverlayVisible = appState.timeout;
    fixture.detectChanges();
    expect(debugElement.nativeElement).toBeFalsy();
  });
</code></pre>

<p><strong>toBeFalsy()</strong> the test will fail but as message will come that.<br>
<code>Expected &lt;overlay id=""overlay""&gt;...&lt;/overlay&gt; to be falsy.</code></p>

<p><strong>not.toBe(true)</strong> the test will work.</p>
",https://stackoverflow.com/questions/59632008/unit-testing-in-angular-not-tobetrue-vs-tobefalsy,"['angular', 'jasmine', 'protractor', 'karma-jasmine']",3596,True,1,1
How to Mock REST API in unit testing?,"<p>I am using RestTemplate <code>exchange HttpMethod.POST</code> method to POST to an endpoint. In my test file I am testing for <code>success</code> of the POST method. However with my current tests I am getting <code>401 Unauthorized  error</code> when POST request is made. I need help to Mock the API while making POST request in test file</p>

<p>Here is my main file</p>

<pre><code>
@Component
public class DataTestRepo {

    private final RestTemplate restTemplate;
    private final String url;
    private final AllBuilder headersBuilder;

    public DataTestRepo(
            @Qualifier(Oauth.BEAN_NAME) AllBuilder headersBuilder,
            RestTemplate restTemplate, String url) {
        this.headersBuilder = headersBuilder;
        this.restTemplate = restTemplate;
        this.url = url;
    }
    public ResponseEntity&lt;String&gt; postJson(Set&lt;String&gt; results) {
        ResponseEntity&lt;String&gt; result = null;

        try {
            JSONObject jsonObject = new JSONObject(body);

            HttpEntity&lt;String&gt; request = new HttpEntity&lt;String&gt;(jsonObject.toString(), null);
            restTemplate.getMessageConverters().add(stringConvertor);
            result = restTemplate.exchange(url, HttpMethod.POST,
                    new HttpEntity&lt;&gt;(request, getHttpHeaders()), String.class);
         } 
        return result;
    }
}
</code></pre>

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

<pre><code>@RunWith(MockitoJUnitRunner.class)
@TestPropertySource
public class DataTestRepoTest {

    private static final String url = ""http://localhost:8080/data/name"";

    @Mock
    private DataTestRepo DataTestRepo;
    RestTemplate restTemplate = new RestTemplate();

    @Test
    public void restTemplateHttpPost_success() throws URISyntaxException {
        URI uri = new URI(url);
        Set&lt;String&gt; mockData = Stream.of(""A"",""B"").collect(Collectors.toSet());
        Map&lt;String, String&gt; body = new HashMap&lt;&gt;();
        body.put(""Name"", ""Aws"");
        JSONObject jsonObject = new JSONObject(body);

        HttpEntity&lt;String&gt; request = new HttpEntity&lt;&gt;(jsonObject.toString(), null);

        ResponseEntity&lt;String&gt; result = restTemplate.exchange(uri, HttpMethod.POST,
                new HttpEntity&lt;&gt;(request, DataTestRepo.getHttpHeaders()), String.class);

        Assert.assertEquals(201, result.getStatusCodeValue());
    }
}


</code></pre>
",https://stackoverflow.com/questions/59921249/how-to-mock-rest-api-in-unit-testing,"['java', 'spring', 'post', 'mocking', 'resttemplate']",4844,True,1,2
C# Unit testing Complex multi threaded database reads,"<p>I have a scenario where the most efficient approach to reading a lot of data and processing it is to  have a thread looking at a table for each hour of the day to produce a list of files in that hour. For each of the rows returned the thread, loads the file data (Oracle BLOB) into memory, processes it, tidies up and moves onto the next file.</p>

<p>So if we get a file at 12:00 and 14:00 in a day;</p>

<ol>
<li>we get threads looking for rows between 00:00 and 12:00 that return no data and finish quickly</li>
<li>We get the 12:00 thread getting a single row, reading the blob and processing it, take a bit more time</li>
<li>Thread looking at 13:00 getting no rows</li>
<li>14:00 same as 12:00</li>
<li>15:00 - 23:00 same as item one.</li>
</ol>

<p>So how do I stop my mock objects on IDbCommand mocks returning the wrong IDataReader mocks?</p>

<p>I am using Moq and the moq extension for IDataReader. In the test I have setup</p>

<pre><code>        Mock&lt;IDBConnectionFactory&gt; mainDbFactory = new Mock&lt;IDBConnectionFactory&gt;();
        Mock&lt;IDBConnectionFactory&gt; repoDbFactory = new Mock&lt;IDBConnectionFactory&gt;();
        Mock&lt;IRecoveryControlCallback&gt; callbacks = new Mock&lt;IRecoveryControlCallback&gt;();
        Mock&lt;IDbConnection&gt; dbMainConnection = new Mock&lt;IDbConnection&gt;();
        Mock&lt;IDbCommand&gt; dbMainCommand = new Mock&lt;IDbCommand&gt;();
        Mock&lt;IDataReader&gt; dbNoFileRowReader = new Mock&lt;IDataReader&gt;();
        Mock&lt;IDataReader&gt; dbFileRowReader = new Mock&lt;IDataReader&gt;();
        Mock&lt;IDataReader&gt; dbLoadFile1Reader = new Mock&lt;IDataReader&gt;();
        Mock&lt;IDataReader&gt; dbLoadFile2Reader = new Mock&lt;IDataReader&gt;();

        // Handle call backs!
        callbacks.Setup(c =&gt; c.OnRecoveryStartedEvent(It.IsAny&lt;string&gt;())).Callback(new Action&lt;string&gt;(LogCallBack));

        // setup main mocks
        mainDbFactory.Setup(c =&gt; c.CreateRead()).Returns(dbMainConnection.Object);
        dbMainConnection.Setup(c =&gt; c.CreateCommand()).Returns(dbMainCommand.Object);
        dbMainCommand.SetupSequence(c =&gt; c.ExecuteScalar())
                     .Returns(mainStartDate)
                     .Returns(mainEndDate);

        dbNoFileRowReader.SetupDataReader(new List&lt;FileNameRow&gt;());
        dbFileRowReader.SetupDataReader(new List&lt;FileNameRow&gt;()
                     {
                         new FileNameRow() { fil_idr = 1, fil_nme = ""file_one.xml""},
                         new FileNameRow() { fil_idr = 2, fil_nme = ""file_two.xml""},
                     });

        dbLoadFile1Reader.SetupDataReader(new List&lt;FileLoadRecord&gt;()
                     {
                         new FileLoadRecord() { fil_con_dtl = LoadFile(""file_one.xml"") }
                     });

        dbLoadFile2Reader.SetupDataReader(new List&lt;FileLoadRecord&gt;()
                     {
                         new FileLoadRecord() { fil_con_dtl = LoadFile(""file_two.xml"") }
                     });

        dbMainCommand.SetupSequence(c =&gt; c.ExecuteReader())
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbFileRowReader.Object)
                     .Returns(dbLoadFile1Reader.Object)
                     .Returns(dbFileRowReader.Object)
                     .Returns(dbLoadFile2Reader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
                     .Returns(dbNoFileRowReader.Object)
</code></pre>

<p>Now, what I am seeing is that the threads with no things to do are moving so fast they take the data meant for the 'LoadFile' method and fail the test. If I move the LoadData result sets to the end the method gets empty result sets and fails as well.</p>
",https://stackoverflow.com/questions/62261760/c-unit-testing-complex-multi-threaded-database-reads,"['c#', 'database', 'multithreading', 'unit-testing', 'moq']",116,False,1,0
Unit testing LiveData emissions in combination with RxJava,"<p>I have been facing an issue unit testing our business logic. The problem is when I wanted to unit test all the emissions of the livedata. Right now I only get the last emitted value but I wanted to unit test all the values that get emitted one by one.</p>

<p>Here is my rough setup.</p>

<p>Here is how my viewModel <code>onSaveEvent</code> click event looks like</p>

<pre><code>        disposable.add(finalSource
        .observeOn(schedulerProvider.ui())
            .doOnSubscribe {
                // show spinner
                _myLiveData.value = Loading(toShow = true, loadingMessage = ""Loading"")
            }
            .doAfterTerminate {
                // remove spinner
                _myLiveData.value = Loading(toShow = false)

            }
            .subscribe { resource -&gt;
                // Update either on success or error.
                _myLiveData.value = resource
        }
    )
</code></pre>

<p>My view model test looks something like this.</p>

<pre><code>@Test
fun testOnSaveEvent() {
    // Other setup code.
    Mockito.`when`(myRepo.onSave()).thenReturn(mockSingle)
    myViewModel.onSaveEvent(salesTaxCompanyInfo)

    testScheduleProvider.ui().triggerActions()

    // I see that the value is of type Loading
    val firstValue = myViewModel.myLiveData.getOrAwaitValue()

    // The next value is also Loading, although I would like to see the success event.
    val secondValue = myViewModel.myLiveData.getOrAwaitValue()
}
</code></pre>

<p>Ideally, I am looking for something on the lines <code>TestCoroutineDispatcher</code> listed here: <a href=""https://medium.com/androiddevelopers/testing-two-consecutive-livedata-emissions-in-coroutines-5680b693cbf8"" rel=""nofollow noreferrer"">https://medium.com/androiddevelopers/testing-two-consecutive-livedata-emissions-in-coroutines-5680b693cbf8</a></p>

<p>While I understand that LiveData only holds the last value it receives I wanted to know if there is any we can unit test the emissions one by one.</p>
",https://stackoverflow.com/questions/62105549/unit-testing-livedata-emissions-in-combination-with-rxjava,"['android', 'unit-testing', 'mvvm', 'rx-java', 'viewmodel']",242,False,1,0
Unit Testing with Model::Find Fails in Laravel,"<p>I am creating unit tests for my rather large Laravel application.</p>
<p>This test passes all assertions. It creates a new database entry for the advertising status model.</p>
<pre><code>/** @test **/
public function create_a_new_advertising_status_test()
{
    $status = AdvertisingStatus::create(['name' =&gt; 'Test']);
    $this-&gt;assertNotNull($status);
    $this-&gt;assertCount(1, AdvertisingStatus::all());
    $this-&gt;assertEquals($status-&gt;name, $this-&gt;advertisingStatus['name']);
}
</code></pre>
<p>This test fails the NotNull assertion as it says $status is null, which means that the Find method is failing.</p>
<pre><code>/** @test **/
public function edit_an_existing_advertising_status_entry()
{
    $status = AdvertisingStatus::create(['name' =&gt; 'Test']);
    // $status = AdvertisingStatus::first(); // This successfully finds the database entry
    $status = AdvertisingStatus::find(1); // This fails to find the database entry
    $status-&gt;name = 'Edit';
    $status-&gt;save();

    $this-&gt;assertNotNull($status);
    $this-&gt;assertCount(1, AdvertisingStatus::all());
    $this-&gt;assertEquals($status-&gt;name, &quot;Edit&quot;);
}
</code></pre>
<p>It appears like the find function and subsequently the where function takes too long to locate the entry, so the test renders the $status variable null.</p>
<p>Aside from using the <code>Model::first()</code> function, does anyone have any idea how to overcome this?</p>
<p>I'm wondering if it's because my application is extremely large and takes a long time to run because I'm using <code>RefreshDatabase</code></p>
",https://stackoverflow.com/questions/62694718/unit-testing-with-modelfind-fails-in-laravel,"['laravel', 'unit-testing', 'phpunit']",396,True,0,1
Unit testing Kafka-streams with TopologyTestDriver and Micronaut,"<p>When I try to run a basic unit test I get the following error:</p>

<pre><code>java.lang.IllegalArgumentException: Unknown topic: streams-wordcount-output

    at org.apache.kafka.streams.TopologyTestDriver.getRecordsQueue(TopologyTestDriver.java:705)
    at org.apache.kafka.streams.TopologyTestDriver.readRecord(TopologyTestDriver.java:777)
    at org.apache.kafka.streams.TestOutputTopic.readRecord(TestOutputTopic.java:100)
    at at.wrwks.bmp.projekthistorie.streams.WordCountIntegrationTest.test(WordCountIntegrationTest.kt:70)
</code></pre>

<p>This is the stream code (based on the Micronaut documentation:</p>

<pre><code>@Factory
class WordCountStream {

    @Singleton
    @Named(STREAM_WORD_COUNT)
    fun wordCountStream(builder: ConfiguredStreamBuilder): KStream&lt;String, String&gt; {
        // set default serdes
        val props: Properties = builder.configuration
        props[StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG] = Serdes.String()::class.jvmName
        props[StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG] = Serdes.String()::class.jvmName
        props[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = ""earliest""
        val source: KStream&lt;String, String&gt; = builder.stream(INPUT)
        val groupedByWord: KTable&lt;String, Long&gt; = source
            .flatMapValues { value -&gt; value.toLowerCase().split(""\\W+"") }
            .groupBy({ _, word -&gt; word }, Grouped.with(Serdes.String(), Serdes.String()))
            //Store the result in a store for lookup later
            .count(Materialized.`as`(WORD_COUNT_STORE))
        groupedByWord
            //convert to stream
            .toStream()
            //send to output using specific serdes
            .to(OUTPUT, Produced.with(Serdes.String(), Serdes.Long()))
        return source
    }

    companion object {
        const val STREAM_WORD_COUNT = ""word-count""
        const val INPUT = ""streams-plaintext-input""
        const val OUTPUT = ""streams-wordcount-output""
        const val WORD_COUNT_STORE = ""word-count-store""
    }
}
</code></pre>

<p>This is the test code:</p>

<pre><code>@Tag(""integration"")
@MicronautTest(application = ProjekthistorieApplication::class)
class WordCountIntegrationTest {
    companion object {
        val builder = mockk&lt;ConfiguredStreamBuilder&gt;()
    }
    @Inject
    private lateinit var context: ApplicationContext
    @Inject
    private lateinit var wordCountStream: KStream&lt;String, String&gt;
    @Inject
    private lateinit var wordCountStreamFactory: WordCountStream
    lateinit var inputWordCount: TestInputTopic&lt;String, String&gt;
    lateinit var outputWordCount: TestOutputTopic&lt;String, Long&gt;
    lateinit var wordCount: TestOutputTopic&lt;String, Long&gt;
    lateinit var testDriver: TopologyTestDriver
    private lateinit var before: LocalDateTime

    @MockBean
    fun configuredStreamBuilder(): ConfiguredStreamBuilder {
        return builder
    }

    @BeforeEach
    fun setUp() {

    }

    @AfterEach
    fun tearDown() {
        testDriver.close()
    }

    @Test
    fun test() {
        before = LocalDateTime.now()
        val streamsBuilder = StreamsBuilder()
        every { builder.stream&lt;String, String&gt;(WordCountStream.INPUT) } returns streamsBuilder.stream(WordCountStream.INPUT)
        val config = Properties()
        config[StreamsConfig.APPLICATION_ID_CONFIG] = ""bmp.projekthistorie.test""
        config[StreamsConfig.BOOTSTRAP_SERVERS_CONFIG] = ""dummy:1234""
        testDriver = TopologyTestDriver(streamsBuilder.build(), config)
        inputWordCount = testDriver.createInputTopic(WordCountStream.INPUT, Serdes.StringSerde().serializer(), Serdes.StringSerde().serializer())
        outputWordCount = testDriver.createOutputTopic(WordCountStream.OUTPUT, Serdes.StringSerde().deserializer(), Serdes.LongSerde().deserializer())
        wordCount = testDriver.createOutputTopic(WordCountStream.STREAM_WORD_COUNT, Serdes.StringSerde().deserializer(), Serdes.LongSerde().deserializer())

        inputWordCount.pipeInput(""word word la la"")
        val readRecord = outputWordCount.readRecord()

        Assertions.assertThat(readRecord).isNotNull()
    }
}
</code></pre>

<p>What do I miss?</p>
",https://stackoverflow.com/questions/62192535/unit-testing-kafka-streams-with-topologytestdriver-and-micronaut,"['unit-testing', 'kotlin', 'apache-kafka-streams', 'junit5', 'micronaut']",3513,False,0,2
Node.js Mocha unit testing not changing object value,"<p>I'm using Mocha/Chai/Sinon to develop some unit tests on a Node.js application (Express). I made a fake request/response object to pass to the function that I'm trying to test. Inside one of my stubs, the value of the property <code>statusCode</code> of the response object is changed to <code>200</code>. However, at the end of the test, Mocha reports it as being the default value for the property (500, in this case).</p>
<p>Here is the test code:</p>
<pre><code>it('should return status 200 if product was saved', function(){
    //fake objects
    const fakeReq = {
        flash(){return true},
        body:{
            title: '',
            price: 0,
            description: ''
        },
        file: {
            path: 'path'
        },
        session: {
            user: ''
        }
    }
    const fakeRes = {
        statusCode: 500,
        redirect(){
            this.statusCode = 200; //this successfully changes to 200
            return this;
        }
    }
    //fake methods
    sinon.stub(expressValidator, 'validationResult').callsFake(fakeValidation);
    sinon.stub(Product.prototype, 'save').callsFake(sinon.fake.resolves('ok'));

    //expectations
    adminController.postAddProduct(fakeReq, fakeRes, ()=&gt;{});
    sinon.restore();
    expect(fakeRes.statusCode).to.equal(200); //test fails returning 500
});
</code></pre>
<p>Here is the method that I want to test, more specifically, the <code>product.save()</code> call, at the end:</p>
<pre><code>exports.postAddProduct = (req, res, next) =&gt; {
  const validationErrors = validationResult(req);
  if (!validationErrors.isEmpty()) {
    req.flash('validationErrors', validationErrors.array());
    return res.status(422).redirect('/admin/add-product');
  }
  const title = req.body.title;
  const image = req.file;
  const price = req.body.price;
  const description = req.body.description;
  if(!image){
    req.flash('validationErrors', [{param:'productImage', msg: 'Insira uma imagem válida!'}]);
    return res.status(422).redirect('/admin/add-product');
  }
  const product = new Product({
    title: title,
    price: price,
    imageUrl: image.path,
    description: description,
    userId: req.session.user
  });
  product.save()
    .then(results =&gt; {
      return res.redirect('/admin/products');
    })
    .catch(err =&gt; {
      next(new Error(err));
    });
};
</code></pre>
<p><strong>EDIT:</strong>
Changed the test function to use a spy in order to check if the <code>redirect</code> method was being called, but it's always returning false. I'm thinking that it might be because Js doesn't pass by reference, unless the contents of the object gets changed. New testing code:</p>
<pre><code>const fakeRes = {
        status(code){
            this.statusCode = code;
            return this;
        },
        redirect(){return true;},
        statusCode: 500
    }
    const redirectSpy = sinon.spy(fakeRes, 'redirect');

    //fake methods
    sinon.stub(expressValidator, 'validationResult').callsFake(fakeValidation);
    sinon.stub(Product.prototype, 'save').callsFake(sinon.fake.resolves('ok'));

    //expectations
    adminController.postAddProduct(fakeReq, fakeRes, ()=&gt;{});
    sinon.restore();
    expect(redirectSpy.withArgs('/admin/products').calledOnce).to.be.true;
});
</code></pre>
",https://stackoverflow.com/questions/64793791/node-js-mocha-unit-testing-not-changing-object-value,"['node.js', 'unit-testing', 'mocha.js', 'chai', 'sinon']",350,False,0,0
Android - Unit testing response handler class HttpException codes,"<p>I'm writing a class to unit test my ResponseHandler class. Do I need to write a method for every possible HTTP error code that I am considering in the getErrorMessage function?
One for 400, 401, 403, 404, 503, etc?</p>
<p><strong>ResponseHandler.kt</strong></p>
<pre><code>enum class ErrorCodes(val code: Int) {
    SocketTimeOut(-1),
    NoConnection(0)
}

class ResponseHandler {

    fun &lt;T : Any&gt; handleSuccess(data: T): Resource&lt;T&gt; {
        return Resource.success(data)
    }

    fun &lt;T : Any&gt; handleException(e: Exception): Resource&lt;T&gt; {
        return when (e) {
            is HttpException -&gt; Resource.error(getErrorMessage(e.code()), null)
            is SocketTimeoutException -&gt; Resource.error(getErrorMessage(ErrorCodes.SocketTimeOut.code), null)
            is IOException -&gt; Resource.error(getErrorMessage(ErrorCodes.NoConnection.code), null)
            else -&gt; Resource.error(getErrorMessage(Int.MAX_VALUE), null)
        }
    }

    private fun getErrorMessage(code: Int): String {
        return when (code) {
            ErrorCodes.SocketTimeOut.code -&gt; &quot;Timeout&quot;
            ErrorCodes.NoConnection.code -&gt; &quot;No Connection&quot;
            HttpURLConnection.HTTP_BAD_REQUEST -&gt; &quot;Bad request&quot;
            HttpURLConnection.HTTP_UNAUTHORIZED -&gt; &quot;Unauthorized&quot;
            HttpURLConnection.HTTP_FORBIDDEN -&gt; &quot;Forbidden&quot;
            HttpURLConnection.HTTP_NOT_FOUND -&gt; &quot;Not found&quot;
            HttpURLConnection.HTTP_UNAVAILABLE -&gt; &quot;Service Unavailable&quot;
            else -&gt; &quot;Something went wrong&quot;
        }
    }
}
</code></pre>
<p><strong>ResponseHandlerTest.kt</strong></p>
<pre><code>    @Test
    fun `when exception is HttpException and code is 404 then return Not found error message`() {
        val httpException = HttpException(Response.error&lt;List&lt;StylesData&gt;&gt;(HttpURLConnection.HTTP_NOT_FOUND, mock()))
        val result = responseHandler.handleException&lt;List&lt;StylesData&gt;&gt;(httpException)
        assertEquals(&quot;Not found&quot;, result.message)
    }

    @Test
    fun `when exception is SocketTimeoutException then return Timeout error message`() {
        val socketTimeoutException = SocketTimeoutException()
        val result = responseHandler.handleException&lt;List&lt;StylesData&gt;&gt;(socketTimeoutException)
        assertEquals(&quot;Timeout&quot;, result.message)
    }

    @Test
    fun `when exception is IOException then return No connection error message`() {
        val ioException = IOException()
        val result = responseHandler.handleException&lt;List&lt;StylesData&gt;&gt;(ioException)
        assertEquals(&quot;No Connection&quot;, result.message)
    }
</code></pre>
",https://stackoverflow.com/questions/64397125/android-unit-testing-response-handler-class-httpexception-codes,"['android', 'unit-testing', 'kotlin', 'testing']",460,True,0,1
Angular Unit Testing : Expect undefined to equal true,"<p>I am new in programming and this is the first time im asked to do unit testing in Angular and im a lil bit confused...
I want to test this method in my component.ts:</p>

<pre><code>isInputHidden = true;

showInput(){this.isInputHidden = false;}
</code></pre>

<p>spec.ts : </p>

<pre><code>it('should show the input', () =&gt; {
component.isInputHidden == false;
let showInput = component.showInput();
expect(showInput).toBe(true);
</code></pre>

<p>})</p>

<p>When i run this test i get these errors : In jasmine ==> Expect undefined to equal true.
In Terminal ==>  Argument of type 'true' is not assignable to parameter of type 'Expected'.
Someone can help me to figure out what should i change? </p>
",https://stackoverflow.com/questions/61248430/angular-unit-testing-expect-undefined-to-equal-true,"['angular', 'typescript', 'unit-testing']",2202,True,0,1
How to mock external methods for unit testing,"<p>I want to mock methods for testing in Go. I am unable to figure out any steps/pattern that is usually followed to mock.</p>
<p>Consider below code and help me out in understanding.</p>
<p><strong>package fetchClient</strong></p>
<p><em>client.go</em></p>
<pre><code>type Client struct {
    URL     string
}

type ClientData struct {
    ID      string       
}

func (p *Client) GetURL(ID string) (*ClientData) {
    data := &amp;ClientData{}
    //Some work to store client information into data struct and return it 
    return data
}
</code></pre>
<p><strong>package fetchClientData</strong></p>
<p><em>FetchData.go</em></p>
<pre><code>// Function GetData that accepts a client ID as argument and returns client URL
func GetData(ID string) (*fetchClient.Client.URL) {
    param := (*Client).GetURL(ID) 
    return param
}
</code></pre>
<p><em>FetchData_test.go</em>
//Want to know how to mock as asked in below question.</p>
<p><em><strong>Question</strong></em>: How to mock a fake GetURL function in FetchData_test.go file so that it does not call actual GetURL function in FetchData.go file, instead mock it.</p>
",https://stackoverflow.com/questions/65078834/how-to-mock-external-methods-for-unit-testing,"['unit-testing', 'go', 'methods', 'interface', 'mocking']",466,True,-2,1
Unit testing AsyncStorage in React Native with Jest,"<p>I am learning React Native and Jest testing.</p>

<p>I have a piece of code where I am storing some value in an AsyncStorage when a button is clicked. When the button is clicked I call the below method.</p>

<pre><code>saveState = () =&gt; {
    AsyncStorage.setItem('saveState', 'button clicked');      
}
</code></pre>

<p>Now I would want to unit test the above method to see if my Async storage is working fine or not.</p>

<p>I was able to create a snapshot and also test remaining functionalities of the method but not this one. But I am not quite familiar in how to do so?</p>

<p>2nd edit ------</p>

<pre><code>jest.mock('react-native', () =&gt; ({
    setItem: jest.fn()
}));


describe('&lt;MyComponent/&gt;', () =&gt; {
  let tnCScreen
  let props
  let instance

  beforeEach(() =&gt; {
    tnCScreen = shallow(&lt;MyComponent {...props} /&gt;)
    instance = tnCScreen.instance()
  })

  test('test saveState method is called', () =&gt; {
    expect(instance.saveState()).toBeCalled
    expect(AsyncStorage.setItem).toBeCalledWith('saveState', 'button clicked');
  })

})
</code></pre>

<p>When I try the above I get below error</p>

<pre><code>expect(received).toBeCalledWith(...expected)
Matcher error: received value must be a mock or spy function
Received has value: undefined
</code></pre>
",https://stackoverflow.com/questions/61156760/unit-testing-asyncstorage-in-react-native-with-jest,"['react-native', 'unit-testing', 'jestjs', 'enzyme']",1805,True,-1,1
Unit testing an external HTTP request in .NET,"<p>I have the following method:</p>
<pre><code>  private async Task&lt;Result&gt; TryGetResult (string request)
        {
            var httpClient = new HttpClient(); 
            var result = await httpClient.GetAsync(request);
            if (result.IsSuccess)
            {
                var body = await result.Content.ReadAsStringAsync();
                var deserializedResult = JsonConvert.DeserializeObject&lt;Result&gt;(body);
                return deserializedResult ;
            }

            if ( result.StatusCode == (HttpStatusCode)429 )
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
                return await TryGetResult(request);
            }
        }
</code></pre>
<p>This takes in this string request:
<code>var request =  $&quot;https://atlas.microsoft.com/search/address/json ... //(private keys omitted)</code></p>
<p>I want to unit test the method and stub out the request so that I don't make a real call. I have limited experience unit testing C# and am struggling to work out how to stub this? Please can anyone point me in the right direction?</p>
<p>I have tried looking at similar articles and googling but cannot find the stubbing of a string request like this and wonder if I'm going in the wrong direction with trying to test?</p>
",https://stackoverflow.com/questions/62880263/unit-testing-an-external-http-request-in-net,"['c#', '.net', 'nunit']",180,True,0,1
Unit testing a Vuetify Data Table with Jest,"<p>I have created a Vue.js application with Vuetify and am now trying to unit test a component containing a Vuetify Data Table. The Data Table is populated from a backend REST API using Axios which works fine when I run the application, however in my unit test (where I mock out Axios with Jest) the Data Table is never populated</p>

<p>Here is the source for my Component </p>

<pre><code>&lt;template&gt;
  &lt;v-container fluid&gt;
    &lt;v-card&gt;
      &lt;v-card-title&gt;
        Results
        &lt;v-spacer&gt;&lt;/v-spacer&gt;
        &lt;v-text-field
          v-model=""search""
          append-icon=""mdi-magnify""
          label=""Search""
          single-line
          hide-details
        &gt;&lt;/v-text-field&gt;
      &lt;/v-card-title&gt;
      &lt;v-data-table
        :headers=""headers""
        :items=""results""
        :search=""search""
        :loading=""loading""
        loading-text=""Loading results...""
        :custom-sort=""customSort""
      &gt;
        &lt;template v-slot:item.startTime=""{item}""&gt;{{formatDate(item.startTime)}}&lt;/template&gt;
        &lt;template v-slot:item.endTime=""{item}""&gt;{{formatDate(item.endTime)}}&lt;/template&gt;
      &lt;/v-data-table&gt;
    &lt;/v-card&gt;
  &lt;/v-container&gt;
&lt;/template&gt;

&lt;script&gt;
import axios from 'axios';
import moment from 'moment';

function dateArrayToMoment(date) {
  return moment()
    .year(date[0])
    .month(date[1])
    .date(date[2])
    .hour(date[3])
    .minute(date[4]);
}

export default {
  name: 'ResultsList',
  data() {
    return {
      loading: true,
      search: '',
      headers: [
        { text: 'Task', align: 'start', sortable: false, value: 'title' },
        { text: 'State', value: 'state' },
        { text: 'Start Time', value: 'startTime' },
        { text: 'End Time', value: 'endTime' },
        { text: 'Result', value: 'resultMessage' }
      ],
      results: []
    };
  },
  mounted() {
    this.loadResults();
  },
  methods: {
    async loadResults() {
      try {
        let response = await axios.get('BACKEND_SERVER/results', {});
        this.results = response.data;
        this.loading = false;
        // eslint-disable-next-line no-debugger
      } catch (error) {
        // eslint-disable-next-line no-console
        console.error(error);
        // you can handle different errors differently
        // or just display an error message instead of your table using a &lt;v-if&gt; tag
        // or navigate to an error page
      }
    },
    formatDate(date) {
      return dateArrayToMoment(date).format('YYYY-MM-DD hh:mm');
    },
    customSort(items, index, isDesc) {
      items.sort((a, b) =&gt; {
        if (index[0] == 'startTime' || index[0] == 'endTime') {
          if (!isDesc[0]) {
            return (
              dateArrayToMoment(b[index]).toDate() -
              dateArrayToMoment(a[index]).toDate()
            );
          } else {
            return (
              dateArrayToMoment(a[index]).toDate() -
              dateArrayToMoment(b[index]).toDate()
            );
          }
        }
      });
      return items;
    }
  }
};
&lt;/script&gt;
</code></pre>

<p>And here is the test spec that tests the component</p>

<pre class=""lang-js prettyprint-override""><code>import Vue from 'vue'
import Vuetify from 'vuetify'
import ResultsList from '@/components/ResultsList'
import { mount, createLocalVue } from '@vue/test-utils'
import axios from 'axios'
import flushPromises from 'flush-promises';

Vue.use(Vuetify)

const localVue = createLocalVue()

var results = [
  {
    'id': 1,
    'state': 'COMPLETED',
    'startTime': [2020, 4, 21, 19, 42],
    'endTime': [2020, 4, 21, 19, 42],
    'type': 'Example Scheduled Task',
    'title': 'Example Scheduled Task at 2020-04-21 19:42:00',
    'resultMessage': 'Task finished successfully'
  },
  {
    'id': 2,
    'state': 'COMPLETED',
    'startTime': [2020, 4, 22, 13, 36],
    'endTime': [2020, 4, 22, 13, 36],
    'type': 'Example Scheduled Task',
    'title': 'Example Scheduled Task at 2020-04-22 13:36:00',
    'resultMessage': 'Task finished successfully'
  },
  {
    'id': 3,
    'state': 'COMPLETED',
    'startTime': [2020, 4, 22, 13, 37],
    'endTime': [2020, 4, 22, 13, 37],
    'type': 'Example Scheduled Task',
    'title': 'Example Scheduled Task at 2020-04-22 13:37:00',
    'resultMessage': 'Task finished successfully'
  }
];

// Use Jest to mock the Axios
jest.mock('axios');

describe('ResultsList.vue', () =&gt; {
  let vuetify

  beforeEach(() =&gt; {
    vuetify = new Vuetify()

    axios.get.mockResolvedValue(results);
  })

  it('should have a custom title and match snapshot', async () =&gt; {
    const wrapper = mount(ResultsList, {
      localVue,
      vuetify,
      propsData: {
        title: 'Foobar',
      },
    })

    await flushPromises()

    // With jest we can create snapshot files of the HTML output
    expect(wrapper.html()).toMatchSnapshot()

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

<p>As you can see I use Jest to mock out Axios so it returns some test data and use Jest to verify a snapshot. </p>

<p>The problem is the snapshot doesn't contain any data (test or otherwise) despite calling flushPromises to ensure all promises are resolved before taking the snapshot.</p>

<p>Here is the snapshot. As you can see no data is displayed in the Data Table, test or otherwise.</p>

<pre><code>// Jest Snapshot v1

exports[`ResultsList.vue should match snapshot 1`] = `
&lt;div class=""container container--fluid"" title=""Foobar""&gt;
  &lt;div class=""v-card v-sheet theme--light""&gt;
    &lt;div class=""v-card__title""&gt;
      Results
      &lt;div class=""spacer""&gt;&lt;/div&gt;
      &lt;div class=""v-input v-input--hide-details theme--light v-text-field v-text-field--single-line""&gt;
        &lt;div class=""v-input__control""&gt;
          &lt;div class=""v-input__slot""&gt;
            &lt;div class=""v-text-field__slot""&gt;&lt;label for=""input-4"" class=""v-label theme--light"" style=""left: 0px; position: absolute;""&gt;Search&lt;/label&gt;&lt;input id=""input-4"" type=""text""&gt;&lt;/div&gt;
            &lt;div class=""v-input__append-inner""&gt;
              &lt;div class=""v-input__icon v-input__icon--append""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-magnify theme--light""&gt;&lt;/i&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=""v-data-table theme--light""&gt;
      &lt;div class=""v-data-table__wrapper""&gt;
        &lt;table&gt;
          &lt;colgroup&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
          &lt;/colgroup&gt;
          &lt;thead class=""v-data-table-header""&gt;
            &lt;tr&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""Task"" class=""text-start""&gt;&lt;span&gt;Task&lt;/span&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""State: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;State&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""Start Time: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;Start Time&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""End Time: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;End Time&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""Result: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;Result&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/thead&gt;
          &lt;tbody&gt;
            &lt;tr class=""v-data-table__empty-wrapper""&gt;
              &lt;td colspan=""5""&gt;No data available&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      &lt;div class=""v-data-footer""&gt;
        &lt;div class=""v-data-footer__select""&gt;Rows per page:&lt;div class=""v-input v-input--hide-details v-input--is-label-active v-input--is-dirty theme--light v-text-field v-select""&gt;
            &lt;div class=""v-input__control""&gt;
              &lt;div role=""button"" aria-haspopup=""listbox"" aria-expanded=""false"" aria-owns=""list-17"" class=""v-input__slot""&gt;
                &lt;div class=""v-select__slot""&gt;
                  &lt;div class=""v-select__selections""&gt;
                    &lt;div class=""v-select__selection v-select__selection--comma""&gt;10&lt;/div&gt;&lt;input aria-label=""$vuetify.dataTable.itemsPerPageText"" id=""input-17"" readonly=""readonly"" type=""text"" aria-readonly=""false"" autocomplete=""off""&gt;
                  &lt;/div&gt;
                  &lt;div class=""v-input__append-inner""&gt;
                    &lt;div class=""v-input__icon v-input__icon--append""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-menu-down theme--light""&gt;&lt;/i&gt;&lt;/div&gt;
                  &lt;/div&gt;&lt;input type=""hidden"" value=""10""&gt;
                &lt;/div&gt;
                &lt;div class=""v-menu""&gt;
                  &lt;!----&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=""v-data-footer__pagination""&gt;–&lt;/div&gt;
        &lt;div class=""v-data-footer__icons-before""&gt;&lt;button type=""button"" disabled=""disabled"" class=""v-btn v-btn--disabled v-btn--flat v-btn--icon v-btn--round v-btn--text theme--light v-size--default"" aria-label=""Previous page""&gt;&lt;span class=""v-btn__content""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-chevron-left theme--light""&gt;&lt;/i&gt;&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;
        &lt;div class=""v-data-footer__icons-after""&gt;&lt;button type=""button"" disabled=""disabled"" class=""v-btn v-btn--disabled v-btn--flat v-btn--icon v-btn--round v-btn--text theme--light v-size--default"" aria-label=""Next page""&gt;&lt;span class=""v-btn__content""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-chevron-right theme--light""&gt;&lt;/i&gt;&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
`;
</code></pre>
",https://stackoverflow.com/questions/61484502/unit-testing-a-vuetify-data-table-with-jest,"['vue.js', 'jestjs', 'axios', 'vuetify.js']",4018,True,0,1
Unit testing a controller method with parameter validation,"<p>I am looking to write a unit test for a controller method defined as follows (the actual regex is much more complex, it's simplified here)</p>
<pre><code>  [HttpGet, Route(@&quot;/abc/{X}/{Y}&quot;)] /*,  
        public async Task&lt;IActionResult&gt; GetData(
            [FromRoute, Required, RegularExpression(@&quot;^[\w]{4,12}$&quot;)]  string X,
            [FromRoute, Required, RegularExpression(@&quot;^[\w]{2,24}$&quot;)]  string Y
            )
        {
             ... 
        }
</code></pre>
<p>Now, as noted in other questions, the validation doesn't work from unit tests. However I'm hoping someone could shed some light on how to do a unit test for code that's using top-level parameters as shown above, as all discussion I've found so far focused around model validation.</p>
<p>FWIW, I'm using Net 5.</p>
",https://stackoverflow.com/questions/64981807/unit-testing-a-controller-method-with-parameter-validation,"['c#', '.net', 'asp.net-mvc', 'asp.net-core-mvc', '.net-5']",267,True,0,1
Testing recursive class methods using unit testing python,"<pre><code>class Login:


    def admin_login(self):
        user_name = input('Enter UserName: -')
        password = input('please enter password:- ')
        try:
            with open(r'/home/Downloads/amis/config.yaml') as file:
                credentials = yaml.load(file)
                if credentials['userid'] == user_name and credentials['password'] == password:
                     admin_op = AdminOps(credentials)
                     admin_op.admin_ops()
                else:
                     print(""please enter correct login creds"")
                     self.admin_login()

        except:
            print('err')
            self.admin_login()
</code></pre>

<p><em>I am testing this class method and i am trying to mock the method then it is not even going into this method for testing. Can anyone help me writing unit test for this class method.</em></p>

<p>I tried this for the wrong credentials.</p>

<pre><code>@mock.patch('users.logins.input', create=True)
def test_admin_login_fail(self,ext, inp1):
    inp1.side_effect = ['qqq', 'qqq']
    login_cls = Login()
    login_cls.admin_login()
    with mock.patch('file path') as mock_login:
        assert mock_login.called
</code></pre>
",https://stackoverflow.com/questions/61767636/testing-recursive-class-methods-using-unit-testing-python,"['python-3.x', 'unit-testing', 'class', 'recursion', 'pytest']",176,False,0,1
Reactjs unit testing array filter includes not working,"<p>I am trying to test the following <code>onColumnToggle</code> function, which is used to toggle some columns in a table (using Primereact <a href=""https://primefaces.org/primereact/showcase/#/datatable/coltoggle"" rel=""nofollow noreferrer"">Column Toggler</a>): </p>

<pre><code>       constructor() {
            super();
            this.state = {
                selectedColumns: []
            }
        }

       componentDidMount() {
        this.setState({
            selectedColumns: this.props.columnProps,
          })
        }

        onColumnToggle(event) {
        let selectedColumns = event.value;

        let orderedSelectedColumns = this.props.columnProps.filter(obj =&gt; selectedColumns.includes(obj));

        this.setState({selectedColumns: orderedSelectedColumns});
    }
</code></pre>

<p>The function in my application is working fine and the toggling works like in the documentation. I am having some difficulties testing the method. At the moment I have the following:</p>

<pre><code>    describe('MyComponent', () =&gt; {
    let wrapper;
    let instance;
    beforeEach(() =&gt; {
        MyComponent.defaultProps = {
            columns: [
                {field: 'vin', header: 'Vin'},
                {field: 'year', header: 'Year'},
                {field: 'brand', header: 'Brand'},
                {field: 'color', header: 'Color'}
            ]
        };

        wrapper = shallow(&lt;MyComponent columnProps={MyComponent.defaultProps.columns}/&gt;);
        instance = wrapper.instance();
        jest.clearAllMocks();
    });

    describe('onColumnToggle function', () =&gt; {
        it('should change ""selectedColumns"" state', () =&gt; {
            const columnMock = {
                 value: [
                   {field: 'year', header: 'Year'},
                   {field: 'brand', header: 'Brand'}
                ]
             }
            instance.onColumnToggle(columnMock);
            expect(wrapper.state('selectedColumns')).toEqual(columnMock.value)
        })
    })
</code></pre>

<p>I expect that my <code>selectedColumns</code> state becomes equal to my <code>columnMock</code> value. Instead, I get the following error:</p>

<pre><code>    Error: expect(received).toEqual(expected) // deep equality

- Expected
+ Received

- Array [
-   Object {
-     ""field"": ""year"",
-     ""header"": ""Year"",
-   },
-   Object {
-     ""field"": ""brand"",
-     ""header"": ""Brand"",
-   },
- ]
+ Array []
</code></pre>

<p>Debugging the issue shows that the filtering part of <code>onColumnToggle</code> function doesn't filter out the common values from the two arrays and <code>orderedSelectedColumns</code> gives back an empty array. If I console log <code>selectedColumns.includes(obj)</code> then it evaluates to <code>false</code> every time. What am I doing wrong? The function works as expected in my application.</p>
",https://stackoverflow.com/questions/61501826/reactjs-unit-testing-array-filter-includes-not-working,"['reactjs', 'jestjs', 'primereact']",1389,True,0,1
How to mock Angular BehaviourSubject when Unit Testing,"<p>I would like to test my AppComponent when receives a <code>BehaviourSubject</code> update or change of state, so my goal is to mock the <code>authService.authEvent</code> in my <code>AppComponent</code>:</p>
<pre><code>export class AppComponent implements OnInit, OnDestroy {
  
  user: any
  loggedIn = false
  
  constructor(
    private router: Router,
    private authService: AuthService
  ) {}

  ngOnInit(): void {
    this.authService.authEvent.subscribe((user) =&gt; {
      if (user) {
        this.setLoggedIn(user)
      } else {
        this.setLoggedOut()
      }
    });
  }

  setLoggedIn(user: any) {
    this.user = user
    this.loggedIn = true

  }

</code></pre>
<p>My AuthService is the following (the authEvent <code>BehaviourSubject</code> is the one I would like to mock):</p>
<pre><code>@Injectable()
export class AuthService {

  authEvent = new BehaviorSubject&lt;any&gt;(null);
  user: any = {}
  
  constructor(

  ) {}


  setUser(user: any) {
    console.log('setUser');
    this.user = { ...user }
    sessionStorage.setItem('app-user', JSON.stringify(this.user))
    this.authEvent.next(this.user)
  }
</code></pre>
<p>And my Unit test, I know this is not the right way to mock the <code>BehaviourSubject</code> but I haven't found any good example how to do it:</p>
<pre><code>
import { BehaviourSubject } from 'rxjs';

export class MockAuthService {

    authEvent = new BehaviourSubject&lt;any&gt;();

    setUser() {
    //mock implementation
    }
}


describe('AppComponent', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;
  let mockAuthService;
  
  beforeEach(async(() =&gt; {

    mockAuthService = jasmine.createSpyObj(['setUser']);

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        { provide: AuthService, useClass: MockAuthService }
      ],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ]
    }).compileComponents();

    
  }));

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

  it('should create the app', () =&gt; {
   
    const app = fixture.componentInstance;
    
    expect(app).toBeTruthy();
  });

 
  describe('ngOnInit', () =&gt; {
    it('should call setLoggedIn user if user received from authEvent', () =&gt; {
      const mockAuthService = TestBed.get(AuthService);
      const userValue = {userName: 'myUser'};
      const spy = spyOn(mockAuthService, 'authEvent').and.returnValue(of(userValue));
      const spyLoggedOut = spyOn(component, 'setLoggedIn').and.callThrough();

      fixture.detectChanges();

      expect(setLoggedIn).toHaveBeenCalled();
      
    });

  });
  
});


</code></pre>
<p>I would really appreciate your help!</p>
",https://stackoverflow.com/questions/65125343/how-to-mock-angular-behavioursubject-when-unit-testing,"['angular', 'unit-testing', 'mocking']",588,True,0,1
"Unit testing method that creates objects, trouble asserting","<p>I have a method that takes an XML string and parses it, returning an <code>IEnumerable&lt;Invoice&gt;</code>. The following is the definition of the classes being used. Note that an <code>Invoice</code> contains <code>InvoiceItem</code>s:</p>
<pre><code>public class Invoice
{
    public const string XmlName = &quot;invoice&quot;;

    public int id { get; set; }
    public string title { get; set; }
    public DateTime timestamp { get; set; }
    public bool paid { get; set; }
    public IList&lt;InvoiceItem&gt; items { get; set; }

    public Invoice() { this.items = new List&lt;InvoiceItem&gt;(); }

    public decimal getTotal()
    {
        if (items == null)
            return 0;

        decimal total = 0;

        foreach (InvoiceItem item in this.items)
            total += item.amount;

        return total;
    }
}

public class InvoiceItem
{
    public const string XmlName = &quot;item&quot;;

    public string description { get; set; }
    public decimal amount { get; set; }
}
</code></pre>
<p>When unit testing the method with NUnit, something strange is going on with the boolean values for <code>paid</code>. Note that I have tested the method in .NET Fiddle, and it returns all the objects it should. So it appears as though something is wrong with the following test (partial code):</p>
<pre><code>[Test]
public void readXml_Test()
{
    // arrange

    // xml stuff...

    // expected objects
    InvoiceItem item1 = new InvoiceItem { description = &quot;item 1 in invoice 1&quot;, amount = 50 };
    InvoiceItem item2 = new InvoiceItem { description = &quot;item 2 in invoice 1&quot;, amount = 50 };
    Invoice invoice1 = new Invoice
    {
        id = 1,
        title = &quot;Aug 2020&quot;,
        timestamp = DateTime.ParseExact(&quot;16/08/2020 09:01:29 AM&quot;, &quot;dd/MM/yyyy hh:mm:ss tt&quot;, System.Globalization.CultureInfo.InvariantCulture),
        paid = true,
        items = new List&lt;InvoiceItem&gt;() { item1, item2 }
     };
     InvoiceItem item3 = new InvoiceItem { description = &quot;item in invoice 2&quot;, amount = 100 };
     Invoice invoice2 = new Invoice
     {
         id = 2,
         title = &quot;Sep 2020&quot;,
         timestamp = DateTime.ParseExact(&quot;16/08/2020 09:01:29 AM&quot;, &quot;dd/MM/yyyy hh:mm:ss tt&quot;, System.Globalization.CultureInfo.InvariantCulture),
         paid = true,
         items = new List&lt;InvoiceItem&gt; { item3 }
      };

    // act
    List&lt;Invoice&gt; actual = xml.readXml().ToList(); // readXml() is the method under test.

    // assert
    Assert.That(actual.Contains(invoice1));
    Assert.That(actual.Contains(invoice2));
}
</code></pre>
<p>As mentioned before, I have tested this in .NET fiddle, and the resulting objects all have correct property values. However, the above test yields:</p>
<pre><code>Message: Expected: True
 But was: False
</code></pre>
<p>There is no mention of any exception. Since I know the method under test works, it seems to be a problem with this test. How can I fix it to make it pass?</p>
",https://stackoverflow.com/questions/63448204/unit-testing-method-that-creates-objects-trouble-asserting,"['c#', '.net', 'unit-testing', 'nunit', 'assert']",58,False,0,0
How to write unit testing script using unittest,"<p>I want to write a unit test cases using unittest where my input is set of images and output is set of images with boundary box in the text, also it generate co-ordinate of the boundary boxes. How can I write test script for that using unittest pyunit framework.</p>
<p>So I have written unittest script to test api is working or not, response should be json / and list format and response of image file format should be png,jpg format, which is working now. I have below test case scenario need to test but how I will check? I don't know.</p>
<p>If optional keys are not passed to API, it should not throw an error. (opposite for compulsory ones) 8) The implemented route should throw/return error if GET request is passed instead of POST. 9) If valid path but invalid file name is provided, you should see respective error. 10) In case of invalid path, you should see respective error message. 11) There is specified set of keys which are compulsory to be passed to APIs, if not it returns an error 12) verify for session time out.</p>
<p>Here is my code:</p>
<pre><code>import requests
import json
import sshtunnel
import unittest
class TestSequentialExecutions(unittest.TestCase):
   
def setUp(self) -&gt; None:
        a=10
    def test_API(self):
        self.resp_list = []
        # API url
        url = ['dummy url','dummyurl']

        # Additional headers.
        headers = {'Content-Type': 'application/json'}
        # Body
        payload = [{'input': 'dummy path'},
                  {&quot;path&quot;: &quot;dummy&quot;}]

        # Test case-1 checking valid API  is routed or not
        # convert dict to json by json.dumps() for body data.
        for i in range(len(url)):
            resp = requests.post(url[i], headers=headers, data=json.dumps(payload[i], indent=4))
            self.assertEqual(resp.status_code, 200)
            self.resp_list.append(resp.json())
            #Test case-2 to check input file is in JPG ,PNG format or not
    def test_fileformat(self):

        n = len(self.resp_list[1])
        my_list = [1]*n
        empty_list=[]
        extensions = ['png','v']
        for filename in self.resp_list[0]:
            if filename.lower().endswith(('.png', '.jpg')):
              empty_list.append(1)
            else:
              empty_list.append(0)
        self.assertEqual(my,empy_list) 



if __name__ == '__main__':
    unittest.main() 
</code></pre>
<p>Actually I am trying to write test script for below github code: <a href=""https://github.com/eragonruan/text-detection-ctpn"" rel=""nofollow noreferrer"">https://github.com/eragonruan/text-detection-ctpn</a></p>
",https://stackoverflow.com/questions/62777068/how-to-write-unit-testing-script-using-unittest,"['python', 'python-unittest']",80,False,0,0
Unit Testing a Windows MFC (CTreeCtrl in special),"<p>I have to write some unit tests for a class that contains a CTreeCtrl object. Problem is i cannot pass the whole chain of windows and init the application as usual, so when using this object i get an error on calling Create or Adding item. For example, i know i cannot pass null on Create as the pParentWnd, but in my case this would be the case. Is there a way to create a ""mocked"" CWnd object to pass?
I'm using Visual Studio 2017 and Google Test/Mock
How can i initialize a CTreeCtrl outside of a normal WinApi Window?</p>
",https://stackoverflow.com/questions/61653721/unit-testing-a-windows-mfc-ctreectrl-in-special,"['c++', 'unit-testing', 'mfc']",100,False,0,0
Unit Testing a Windows MFC (CTreeCtrl in special),"<p>I have to write some unit tests for a class that contains a CTreeCtrl object. Problem is i cannot pass the whole chain of windows and init the application as usual, so when using this object i get an error on calling Create or Adding item. For example, i know i cannot pass null on Create as the pParentWnd, but in my case this would be the case. Is there a way to create a ""mocked"" CWnd object to pass?
I'm using Visual Studio 2017 and Google Test/Mock
How can i initialize a CTreeCtrl outside of a normal WinApi Window?</p>
",https://stackoverflow.com/questions/61653721/unit-testing-a-windows-mfc-ctreectrl-in-special,"['c++', 'unit-testing', 'mfc']",100,False,0,0
how can i do unit testing for APIs?,"<p>i`am new to unit testing and i have this task to write unit testing for Post API i have only the end point and api body i read a lot in google but i could not figure out how to start , any help ?</p>
",https://stackoverflow.com/questions/60041169/how-can-i-do-unit-testing-for-apis,"['java', 'spring-boot', 'api', 'unit-testing', 'junit']",232,True,0,2
Web API Controller Unit testing multiple test issue,"<p>I have create a web API am have developed some unit tests for it. In one of my controllers I pass in a variable of a Id which runs a stored procedure and returns a list of data with the matching data. Here is one of my unit tests:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http.Results;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebApi.Controllers;
using WebApi.Models;

namespace UnitTestProject1
{
    [TestClass]
    public class ProductContollerTests
    {
        // Unit Test Description: Tests to check the number of returned items with the BrandId = 1 matches the number of Products In testProducts
        [TestMethod]
        public void GetProducts_ShouldRetrunCorrectProducts()
        {
            var testProducts = GetTestProducts();
            var controller = new ProductsController(testProducts);

            var result = controller.GetProducts(1) as List&lt;Product&gt;;
            Assert.AreEqual(testProducts.Count, result.Count);
        }

        private List&lt;Product&gt; GetTestProducts()
        {
            var testProducts = new List&lt;Product&gt;
            {
                new Product { BrandId = 1, ProductId = 1, ProductName = ""Home"" },
                new Product { BrandId = 1, ProductId = 2, ProductName = ""Motor"" },
                new Product { BrandId = 1, ProductId = 3, ProductName = ""Travel"" },
                new Product { BrandId = 1, ProductId = 4, ProductName = ""Van"" },
                new Product { BrandId = 1, ProductId = 5, ProductName = ""Commercial"" }

            };

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

<p>Current this is passing because I am count the data that is returned and compared to see if it is equal to the data in the list testproducts. Currently this is a unit test for when the brand id is equal to 1. But what happens if I wanted to test for when brand id is equal to 2.</p>

<p>I can add a new product to the list testProducts but this then cause the first test to fails as I am counting the elements in list testProducts so when i add another product e.g. </p>

<pre><code>new Product { BrandId = 2, ProductId = 6, ProductName = ""Creditor"" }
</code></pre>

<p>There are more values in testProducts than the data being returned from my API. Is there a way in which i could add it so that i only count the elements which have a brandId of one so that i could add other tests or will i have to always create a new testproducts List when testing something different.</p>
",https://stackoverflow.com/questions/59900865/web-api-controller-unit-testing-multiple-test-issue,"['unit-testing', 'asp.net-web-api', 'controller']",24,False,0,1
Can&#39;t load module in while AngularJS unit testing,"<p>I am writing unit tests for my angularJS 1.4.x app Services and Controllers, the problem is all our controllers and services are declared insides modules like shown below, i.e ""MyApp""</p>

<pre><code>module MyApp {

    'user strict';

     export class MyService {
          public static $inject = [
            '$http',
            '$rootScope',
            'library'
          ];
          constructor(private $rootScope:any,
                    private $http:ng.IHttpService,
                    private library:lib.Library) {}

          // some methods...
     }
}
</code></pre>

<p>but when i try to require this file in my test.js file it gives the following error</p>

<pre><code>SyntaxError: Unexpected token, expected "";"" (1:7)
</code></pre>

<p>here is my test file</p>

<pre><code>require('../../../node_modules/angular/angular.min.js');
require('../../../node_modules/angular-mocks/angular-mocks.js');    
require('../ts/MyService.ts');

describe('myService testing', function(){

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

    var ser;

    beforeEach(inject(function(myService) {
        ser = myService;
    }));

    it('1 + 1 should equal 2', function(){
        var actual = ser.addTwoNumbers(1,1);
        expect(actual).toEqual(2);
    });       
});
</code></pre>
",https://stackoverflow.com/questions/59841931/cant-load-module-in-while-angularjs-unit-testing,"['javascript', 'angularjs', 'jasmine', 'jestjs']",112,True,0,1
How to access real DataBase in unit testing?,"<p>I want to get data from my actual database in unit testing.
I have a table named person and I have data in that table. Now, I want to get data from that table in unit testing.
Below is the code which I am using to fetch data from the DB.</p>
<pre><code>public class PersonAppService_Tests: AppTestBase
{
private readonly IRepository&lt;Person&gt; _PersonRepositroy;
private readonly IUnitOfWorkManager _unitOfWorkManager;

public PersonAppService_Tests()
        {
            
            _PersonRepositroy = Resolve&lt;IRepository&lt;Person&gt;&gt;();
            _unitOfWorkManager = Resolve&lt;IUnitOfWorkManager&gt;();

        }
public async Task&lt;List&lt;PersonListDto&gt;&gt; GetAll()
        {
           List&lt;PersonListDto&gt; a = new List&lt;PersonListDto&gt;();
            using (var uow = _unitOfWorkManager.Begin())
            {
                var test = from Person in _PersonRepositroy.GetAll()
                           select new PersonListDto
                           {
                               Id = Person.Id,
                               Text = Person.Text,
                               Code = Person.Code,                               
                               TenantId = Person.TenantId
                           };
                a = test.ToList();//No Data is apppearing, event though database has the data
                await uow.CompleteAsync();
            }

            
        }

}
</code></pre>
<p>using this code I get null data as I have data in my DB.</p>
<p>I am using asp.net Core (3.0) +Entity Framework 5.0</p>
",https://stackoverflow.com/questions/63987043/how-to-access-real-database-in-unit-testing,"['database', 'entity-framework', 'unit-testing', 'asp.net-core', 'aspnetboilerplate']",448,True,0,1
Unit Testing methods which dispatch actions in Vue.js,"<p>I am having trouble to unit test methods in a component, I want to test <code>validations()</code>, <code>clear()</code>, and <code>registerUser()</code> methods but I can't seem to increase the code coverage. Below is the Component :</p>

<pre><code>&lt;template&gt;

    &lt;v-col class=""pa-lg-10""&gt;
        &lt;v-card class="" mx-auto""&gt;
            &lt;form class=""pa-10""&gt;
                &lt;p class=""reg-text""&gt;Registration&lt;/p&gt;
                &lt;v-text-field v-model=""name"" label=""Name"" required&gt;&lt;/v-text-field&gt;
                &lt;v-text-field v-model=""email"" label=""E-mail"" required&gt;&lt;/v-text-field&gt;
                &lt;v-text-field v-model=""address"" label=""Address"" required&gt;&lt;/v-text-field&gt;
                &lt;v-text-field v-model=""phoneNumber"" label=""Phone Number""&gt;&lt;/v-text-field&gt;
                &lt;v-text-field v-model=""password"" label=""Password"" :type=""'password'"" required&gt;&lt;/v-text-field&gt;
                &lt;v-btn class=""mr-4"" color=""primary"" @click=""registerUser""&gt;Register&lt;/v-btn&gt;
                &lt;v-btn @click=""clear""&gt;clear&lt;/v-btn&gt;
            &lt;/form&gt;
        &lt;/v-card&gt;
        &lt;SnackBar/&gt;
    &lt;/v-col&gt;


&lt;/template&gt;

&lt;script&gt;
    import {mapActions, mapGetters} from ""vuex"";
    import SnackBar from ""./SnackBar"";

    export default {
        name: ""RegisterUsers"",
        components: {
            SnackBar
        },
        data() {
            return {
                name: '',
                email: '',
                address: '',
                phoneNumber: '',
                password: '',
                formHasErrors: false,
            }
        },
        methods: {
            registerUser() {
                const formData = {
                    name: this.name,
                    email: this.email,
                    address: this.address,
                    number: this.phoneNumber,
                    password: this.password,
                };

                if (!this.validations()) {
                    this.register(formData);
                }
            },
            clear() {
                this.name = """";
                this.email = """";
                this.address = """";
                this.phoneNumber = """";
                this.password = """";
            },
            validations() {
                // eslint-disable-next-line no-useless-escape
                const mailFormat = /\S+@\S+\.\S+/;
                const vm = this;
                setTimeout(() =&gt; {
                    vm.reset_snackbar();
                }, 2000);
                if (this.email === '') {
                    this.toast_snackbar_on_error('Email is required');
                    return true;
                }

                if (mailFormat.test(this.email.toString()) !== true) {
                    this.toast_snackbar_on_error('Please enter a valid mail');
                    return true;
                }

                if (this.name === '') {
                    this.toast_snackbar_on_error('Name is required');
                    return true;
                }
                if (this.address === '') {
                    this.toast_snackbar_on_error('Address is required');
                    return true;
                }
                if (this.password === '') {
                    this.toast_snackbar_on_error('Password  is required');
                    return true;
                }
                return this.formHasErrors;
            },
            ...mapActions({
                register: 'register/registerUsers',
                reset_snackbar: 'register/reset_snackbar',
                toast_snackbar_on_error: 'register/toast_snackbar_on_error',

            }),
            computed: {
                ...mapGetters('register', ['snackbar_status']),
            },

        },
    };
&lt;/script&gt;

&lt;style scoped&gt;
    div{
        color: inherit;
    }
    .reg-text {
        color: black;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
&lt;/style&gt;
</code></pre>

<p>I have tried to mock some data during the insertion however, I can't seem to get hit those methods. Secondly, I wanted also to expect the message from a <code>SnackBar</code> but I couldn't seem to target it as well.</p>

<p>How can I test this component methods.</p>

<p>Below are my tests :</p>

<pre><code>it(""should expect to have input fields"", () =&gt; {

        const wrapper = shallowMount(RegisterUsers);

        wrapper.setData({ name: '',
          email: 'ab@gmail.com',
          address: 'Buziga, Kampala',
          phoneNumber: '0704594180',
          password: '9393939',
          formHasErrors: false,});

        const button = wrapper.find({name: 'v-btn'})
        button.trigger('click');

        expect(wrapper.classes('s-text')).toBe(false);
    })
</code></pre>

<p>The <strong>css</strong> class <code>s-text</code> you see in the test it's the one wrapping the message of a <code>SnackBar</code>. </p>

<p>I kindly need guidance here.</p>
",https://stackoverflow.com/questions/61540942/unit-testing-methods-which-dispatch-actions-in-vue-js,"['unit-testing', 'vue.js', 'jestjs', 'vuetify.js']",343,True,0,1
Unit Testing POST request body while using WebClient,"<p>Below is a snippet of my code which POST multipart request to server.
Based on some condition, it decides to post only one file or both.</p>

<pre><code>// Based on some condition add 1 or 2 files to the multipart body
MultiValueMap&lt;String, Object&gt; parts = new LinkedMultiValueMap&lt;&gt;();
if (postBothFiles) {
    parts.add(""File_ONE"", new FileSystemResource(file1));
}
parts.add(""File_TWO"", new FileSystemResource(file2));


// Perform the post request adding `parts` to the body
webClient.post().uri(""/postUrl"")
                .contentType(MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData(parts))
                .retrieve()
                .bodyToMono(String.class)
                .block();
</code></pre>

<p>During Unit Test, I want to test if the condition works correctly. To do that, by some means, I want to verify if the request body has two files or only one. </p>

<p>I tried using <code>ExchangeFilterFunction</code>, however it doesn't let me read the body content. </p>

<p>What is the best way to Unit Test such POST requests?</p>
",https://stackoverflow.com/questions/60719352/unit-testing-post-request-body-while-using-webclient,"['java', 'spring', 'unit-testing', 'webclient', 'spring-webflux']",1742,True,0,1
Flink SQL Unit Testing: How to Assign Watermark?,"<p>I'm writing a unit test for a Flink SQL statement that uses match_recognize. I'm setting up the test data like this</p>
<pre><code>Table data = tEnv.fromValues(DataTypes.ROW(
  DataTypes.FIELD(&quot;event_time&quot;, DataTypes.TIMESTAMP(3)),
  DataTypes.FIELD(&quot;foobar&quot;, DataTypes.STRING()),
  ....
  ),
  row(...),
  row(...)
);
</code></pre>
<p>I have two questions,</p>
<ul>
<li>How do I designate event_time as the field for watermarking? (indicating rowtime)</li>
<li>Less important, give the table created a meaningful name?</li>
</ul>
<p>FLINK VERSION: 1.11</p>
",https://stackoverflow.com/questions/64036629/flink-sql-unit-testing-how-to-assign-watermark,"['apache-flink', 'flink-streaming', 'flink-sql', 'flink-table-api']",844,True,0,1
JUnit 5 Unit Testing Get and Post methods,"<p>I am new to spring boot and Junit testing. I am facing problem in testing Rest Api's Get and Post method. Many tutorials online guide about the use of mockMvc in JUnit testing. But are those still valid for JUnit 5. </p>

<pre><code>@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = RegisterRestController.class)
class RegisterRestControllerTest {
  @Autowired
  private MockMvc mockMvc;

  @Autowired
  private ObjectMapper objectMapper;

  @MockBean
  private RegisterUseCase registerUseCase;

  @Test
  void whenValidInput_thenReturns200() throws Exception {
    mockMvc.perform(...);
  }

}
</code></pre>

<p>However I read a article that you don't need to include @ExtendWith extension from SpringBoot 2.1 onwards.
Since Junit 5 and spring boot both updated with lot of changes from previous version it has become difficult to analyse which code available online is correct regarding testing. 
I am not able to use MockMvc.perform().andExpect(status().isOk()).</p>

<pre><code>mockMvc.perform(post(""/forums/{forumId}/register"", 42L)
    .contentType(""application/json"")
    .param(""sendWelcomeMail"", ""true"")
    .content(objectMapper.writeValueAsString(user)))
    .andExpect(status().isOk());
</code></pre>

<p>What is the correct use of testing Get and post methods. And testing Rest verbs comes under unit testing or integration testing?</p>

<p>Also guide me good source to check updated features of Junit 5 with Spring Boot(JUnit 5 doc is not helpful in my case).</p>
",https://stackoverflow.com/questions/61935864/junit-5-unit-testing-get-and-post-methods,"['spring-boot', 'unit-testing', 'spring-mvc', 'junit5', 'spring-restcontroller']",4625,True,0,1
Unit testing an external HTTP request in .NET,"<p>I have the following method:</p>
<pre><code>  private async Task&lt;Result&gt; TryGetResult (string request)
        {
            var httpClient = new HttpClient(); 
            var result = await httpClient.GetAsync(request);
            if (result.IsSuccess)
            {
                var body = await result.Content.ReadAsStringAsync();
                var deserializedResult = JsonConvert.DeserializeObject&lt;Result&gt;(body);
                return deserializedResult ;
            }

            if ( result.StatusCode == (HttpStatusCode)429 )
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
                return await TryGetResult(request);
            }
        }
</code></pre>
<p>This takes in this string request:
<code>var request =  $&quot;https://atlas.microsoft.com/search/address/json ... //(private keys omitted)</code></p>
<p>I want to unit test the method and stub out the request so that I don't make a real call. I have limited experience unit testing C# and am struggling to work out how to stub this? Please can anyone point me in the right direction?</p>
<p>I have tried looking at similar articles and googling but cannot find the stubbing of a string request like this and wonder if I'm going in the wrong direction with trying to test?</p>
",https://stackoverflow.com/questions/62880263/unit-testing-an-external-http-request-in-net,"['c#', '.net', 'nunit']",180,True,0,1
Unit testing a Vuetify Data Table with Jest,"<p>I have created a Vue.js application with Vuetify and am now trying to unit test a component containing a Vuetify Data Table. The Data Table is populated from a backend REST API using Axios which works fine when I run the application, however in my unit test (where I mock out Axios with Jest) the Data Table is never populated</p>

<p>Here is the source for my Component </p>

<pre><code>&lt;template&gt;
  &lt;v-container fluid&gt;
    &lt;v-card&gt;
      &lt;v-card-title&gt;
        Results
        &lt;v-spacer&gt;&lt;/v-spacer&gt;
        &lt;v-text-field
          v-model=""search""
          append-icon=""mdi-magnify""
          label=""Search""
          single-line
          hide-details
        &gt;&lt;/v-text-field&gt;
      &lt;/v-card-title&gt;
      &lt;v-data-table
        :headers=""headers""
        :items=""results""
        :search=""search""
        :loading=""loading""
        loading-text=""Loading results...""
        :custom-sort=""customSort""
      &gt;
        &lt;template v-slot:item.startTime=""{item}""&gt;{{formatDate(item.startTime)}}&lt;/template&gt;
        &lt;template v-slot:item.endTime=""{item}""&gt;{{formatDate(item.endTime)}}&lt;/template&gt;
      &lt;/v-data-table&gt;
    &lt;/v-card&gt;
  &lt;/v-container&gt;
&lt;/template&gt;

&lt;script&gt;
import axios from 'axios';
import moment from 'moment';

function dateArrayToMoment(date) {
  return moment()
    .year(date[0])
    .month(date[1])
    .date(date[2])
    .hour(date[3])
    .minute(date[4]);
}

export default {
  name: 'ResultsList',
  data() {
    return {
      loading: true,
      search: '',
      headers: [
        { text: 'Task', align: 'start', sortable: false, value: 'title' },
        { text: 'State', value: 'state' },
        { text: 'Start Time', value: 'startTime' },
        { text: 'End Time', value: 'endTime' },
        { text: 'Result', value: 'resultMessage' }
      ],
      results: []
    };
  },
  mounted() {
    this.loadResults();
  },
  methods: {
    async loadResults() {
      try {
        let response = await axios.get('BACKEND_SERVER/results', {});
        this.results = response.data;
        this.loading = false;
        // eslint-disable-next-line no-debugger
      } catch (error) {
        // eslint-disable-next-line no-console
        console.error(error);
        // you can handle different errors differently
        // or just display an error message instead of your table using a &lt;v-if&gt; tag
        // or navigate to an error page
      }
    },
    formatDate(date) {
      return dateArrayToMoment(date).format('YYYY-MM-DD hh:mm');
    },
    customSort(items, index, isDesc) {
      items.sort((a, b) =&gt; {
        if (index[0] == 'startTime' || index[0] == 'endTime') {
          if (!isDesc[0]) {
            return (
              dateArrayToMoment(b[index]).toDate() -
              dateArrayToMoment(a[index]).toDate()
            );
          } else {
            return (
              dateArrayToMoment(a[index]).toDate() -
              dateArrayToMoment(b[index]).toDate()
            );
          }
        }
      });
      return items;
    }
  }
};
&lt;/script&gt;
</code></pre>

<p>And here is the test spec that tests the component</p>

<pre class=""lang-js prettyprint-override""><code>import Vue from 'vue'
import Vuetify from 'vuetify'
import ResultsList from '@/components/ResultsList'
import { mount, createLocalVue } from '@vue/test-utils'
import axios from 'axios'
import flushPromises from 'flush-promises';

Vue.use(Vuetify)

const localVue = createLocalVue()

var results = [
  {
    'id': 1,
    'state': 'COMPLETED',
    'startTime': [2020, 4, 21, 19, 42],
    'endTime': [2020, 4, 21, 19, 42],
    'type': 'Example Scheduled Task',
    'title': 'Example Scheduled Task at 2020-04-21 19:42:00',
    'resultMessage': 'Task finished successfully'
  },
  {
    'id': 2,
    'state': 'COMPLETED',
    'startTime': [2020, 4, 22, 13, 36],
    'endTime': [2020, 4, 22, 13, 36],
    'type': 'Example Scheduled Task',
    'title': 'Example Scheduled Task at 2020-04-22 13:36:00',
    'resultMessage': 'Task finished successfully'
  },
  {
    'id': 3,
    'state': 'COMPLETED',
    'startTime': [2020, 4, 22, 13, 37],
    'endTime': [2020, 4, 22, 13, 37],
    'type': 'Example Scheduled Task',
    'title': 'Example Scheduled Task at 2020-04-22 13:37:00',
    'resultMessage': 'Task finished successfully'
  }
];

// Use Jest to mock the Axios
jest.mock('axios');

describe('ResultsList.vue', () =&gt; {
  let vuetify

  beforeEach(() =&gt; {
    vuetify = new Vuetify()

    axios.get.mockResolvedValue(results);
  })

  it('should have a custom title and match snapshot', async () =&gt; {
    const wrapper = mount(ResultsList, {
      localVue,
      vuetify,
      propsData: {
        title: 'Foobar',
      },
    })

    await flushPromises()

    // With jest we can create snapshot files of the HTML output
    expect(wrapper.html()).toMatchSnapshot()

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

<p>As you can see I use Jest to mock out Axios so it returns some test data and use Jest to verify a snapshot. </p>

<p>The problem is the snapshot doesn't contain any data (test or otherwise) despite calling flushPromises to ensure all promises are resolved before taking the snapshot.</p>

<p>Here is the snapshot. As you can see no data is displayed in the Data Table, test or otherwise.</p>

<pre><code>// Jest Snapshot v1

exports[`ResultsList.vue should match snapshot 1`] = `
&lt;div class=""container container--fluid"" title=""Foobar""&gt;
  &lt;div class=""v-card v-sheet theme--light""&gt;
    &lt;div class=""v-card__title""&gt;
      Results
      &lt;div class=""spacer""&gt;&lt;/div&gt;
      &lt;div class=""v-input v-input--hide-details theme--light v-text-field v-text-field--single-line""&gt;
        &lt;div class=""v-input__control""&gt;
          &lt;div class=""v-input__slot""&gt;
            &lt;div class=""v-text-field__slot""&gt;&lt;label for=""input-4"" class=""v-label theme--light"" style=""left: 0px; position: absolute;""&gt;Search&lt;/label&gt;&lt;input id=""input-4"" type=""text""&gt;&lt;/div&gt;
            &lt;div class=""v-input__append-inner""&gt;
              &lt;div class=""v-input__icon v-input__icon--append""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-magnify theme--light""&gt;&lt;/i&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=""v-data-table theme--light""&gt;
      &lt;div class=""v-data-table__wrapper""&gt;
        &lt;table&gt;
          &lt;colgroup&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
            &lt;col class=""""&gt;
          &lt;/colgroup&gt;
          &lt;thead class=""v-data-table-header""&gt;
            &lt;tr&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""Task"" class=""text-start""&gt;&lt;span&gt;Task&lt;/span&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""State: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;State&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""Start Time: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;Start Time&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""End Time: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;End Time&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
              &lt;th role=""columnheader"" scope=""col"" aria-label=""Result: Not sorted. Activate to sort ascending."" aria-sort=""none"" class=""text-start sortable""&gt;&lt;span&gt;Result&lt;/span&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate v-data-table-header__icon mdi mdi-arrow-up theme--light"" style=""font-size: 18px;""&gt;&lt;/i&gt;&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/thead&gt;
          &lt;tbody&gt;
            &lt;tr class=""v-data-table__empty-wrapper""&gt;
              &lt;td colspan=""5""&gt;No data available&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      &lt;div class=""v-data-footer""&gt;
        &lt;div class=""v-data-footer__select""&gt;Rows per page:&lt;div class=""v-input v-input--hide-details v-input--is-label-active v-input--is-dirty theme--light v-text-field v-select""&gt;
            &lt;div class=""v-input__control""&gt;
              &lt;div role=""button"" aria-haspopup=""listbox"" aria-expanded=""false"" aria-owns=""list-17"" class=""v-input__slot""&gt;
                &lt;div class=""v-select__slot""&gt;
                  &lt;div class=""v-select__selections""&gt;
                    &lt;div class=""v-select__selection v-select__selection--comma""&gt;10&lt;/div&gt;&lt;input aria-label=""$vuetify.dataTable.itemsPerPageText"" id=""input-17"" readonly=""readonly"" type=""text"" aria-readonly=""false"" autocomplete=""off""&gt;
                  &lt;/div&gt;
                  &lt;div class=""v-input__append-inner""&gt;
                    &lt;div class=""v-input__icon v-input__icon--append""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-menu-down theme--light""&gt;&lt;/i&gt;&lt;/div&gt;
                  &lt;/div&gt;&lt;input type=""hidden"" value=""10""&gt;
                &lt;/div&gt;
                &lt;div class=""v-menu""&gt;
                  &lt;!----&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=""v-data-footer__pagination""&gt;–&lt;/div&gt;
        &lt;div class=""v-data-footer__icons-before""&gt;&lt;button type=""button"" disabled=""disabled"" class=""v-btn v-btn--disabled v-btn--flat v-btn--icon v-btn--round v-btn--text theme--light v-size--default"" aria-label=""Previous page""&gt;&lt;span class=""v-btn__content""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-chevron-left theme--light""&gt;&lt;/i&gt;&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;
        &lt;div class=""v-data-footer__icons-after""&gt;&lt;button type=""button"" disabled=""disabled"" class=""v-btn v-btn--disabled v-btn--flat v-btn--icon v-btn--round v-btn--text theme--light v-size--default"" aria-label=""Next page""&gt;&lt;span class=""v-btn__content""&gt;&lt;i aria-hidden=""true"" class=""v-icon notranslate mdi mdi-chevron-right theme--light""&gt;&lt;/i&gt;&lt;/span&gt;&lt;/button&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
`;
</code></pre>
",https://stackoverflow.com/questions/61484502/unit-testing-a-vuetify-data-table-with-jest,"['vue.js', 'jestjs', 'axios', 'vuetify.js']",4018,True,0,1
Unit testing getting error for importing a png,"<p>I've written a unit test for React. I ran the test and it failed with an error</p>

<pre><code>import myLogo from ""~/../img/myImage.png""
</code></pre>

<p>This code runs fine on the page and successfully renders the image. I am not sure why it fails on the Jest unit test.</p>

<p>Here is the error output</p>

<pre><code>SyntaxError: Invalid or unexpected token

at ScriptTransformer._transformAndBuildScript (../node_module/jest-runtime/build/script_transformer.js:403:17)
</code></pre>
",https://stackoverflow.com/questions/60970443/unit-testing-getting-error-for-importing-a-png,"['reactjs', 'jestjs']",66,False,0,0
Unit testing with a &quot;real&quot; database using efcore,"<p>I've got a fairly complex application to test that uses EFCore, including things like NetTopologySuite. It runs on MS SQL Server locally and Azure SQL in the cloud and has to be tested against these, so in memory databases and SQLite are not enough. Is anybody aware of some helper framework to automate the creation/wiping of test databases? I've found EfCore.TestSupport, but it doesn't seem to support NetTopologySuite, which is a must have for us.</p>
",https://stackoverflow.com/questions/61217578/unit-testing-with-a-real-database-using-efcore,"['asp.net-core', 'asp.net-web-api']",93,False,0,1
Unit testing service Moq setup not returning value,"<p>I am trying to write a unit test for my service layer.
This is the test that i am writing. I am trying to get back a response and i am having an issue with mocking. When i debug the saveCustomerRecordTextFile.WriteToDiskCustomerRecordAsync method return null and i am not sure what i am doing wrong.</p>

<pre><code>  public class InvitationServiceTests
  { 
    private readonly Mock&lt;ITranformToCustomerDistanceRecord&gt; _customerRecordFileReader;
    private readonly Mock&lt;ISaveInviteeRecord&gt; _customerRecordFileOutputWriter;
    private readonly Mock&lt;ICustomerDistanceFromDublinOffice&gt; _distanceFromDublinOffice;
    private readonly Mock&lt;ISaveCustomerRecord&gt; _saveCustomerRecordTextFile;
    public InvitationServiceTests()
    {
        _customerRecordFileReader = new Mock&lt;ITranformToCustomerDistanceRecord&gt;();
        _customerRecordFileOutputWriter = new Mock&lt;ISaveInviteeRecord&gt;();
        _distanceFromDublinOffice = new Mock&lt;ICustomerDistanceFromDublinOffice&gt;();
        _saveCustomerRecordTextFile = new Mock&lt;ISaveCustomerRecord&gt;();
   }

[Fact]
public void InvitationService_return_statusOk()
{

    _saveCustomerRecordTextFile.Setup(c =&gt; c.WriteToDiskCustomerRecordAsync(It.IsAny&lt;IFormFile&gt;())).Returns(Task.FromResult(It.IsAny&lt;string&gt;()));

    var invitationService = new InvitationService(_customerRecordFileReader.Object,
        _customerRecordFileOutputWriter.Object,
        _distanceFromDublinOffice.Object,
        _saveCustomerRecordTextFile.Object);

    var s = invitationService.InviteToDublinOfficeAsync(It.IsAny&lt;IFormFile&gt;());

}
</code></pre>

<p>Code Implementation:</p>

<pre><code>    public class InvitationService : IInvitationService
    {
        private readonly ITranformToCustomerDistanceRecord _customerRecordFileReader;
        private readonly ISaveInviteeRecord _customerRecordFileOutputWriter;
        private readonly ICustomerDistanceFromDublinOffice _distanceFromDublinOffice;
        private readonly ISaveCustomerRecord _saveCustomerRecordTextFile;

        public InvitationService(
            ITranformToCustomerDistanceRecord customerRecordFileReader, 
            ISaveInviteeRecord customerRecordFileOutputWriter,
            ICustomerDistanceFromDublinOffice distanceFromDublinOffice,
            ISaveCustomerRecord saveCustomerRecordTextFile)
        {   
            _customerRecordFileReader = customerRecordFileReader ?? throw new ArgumentNullException(nameof(customerRecordFileReader)); 
            _customerRecordFileOutputWriter = customerRecordFileOutputWriter ?? throw new ArgumentNullException(nameof(customerRecordFileOutputWriter));
            _distanceFromDublinOffice = distanceFromDublinOffice ?? throw new ArgumentNullException(nameof(distanceFromDublinOffice));
            _saveCustomerRecordTextFile = saveCustomerRecordTextFile ?? throw new ArgumentNullException(nameof(saveCustomerRecordTextFile));

        }
        public async Task&lt;InviteeResponse&gt; InviteToDublinOfficeAsync(IFormFile file)
        {
           var filepath =  await _saveCustomerRecordTextFile.WriteToDiskCustomerRecordAsync(file);
           var customerRecords = _customerRecordFileReader.MappingFromTextFileToCustomerRecord(filepath);
           var customerRecordsWithDistance = _distanceFromDublinOffice.TransformCustomerRecordToInviteeDistanceRecord(customerRecords);
           return  _customerRecordFileOutputWriter.WriteToDiskInviteeToOffice(customerRecordsWithDistance);
        }
    } 
</code></pre>
",https://stackoverflow.com/questions/62429911/unit-testing-service-moq-setup-not-returning-value,"['c#', 'moq', 'xunit']",471,True,0,1
Unit Testing JDBC methods with MySQL specific queries,"<p>I have a bunch of methods which run mysql specific SQLs using JDBC calls. I need to write unit or integration test for these methods that should run as part of the CI build.</p>
<p>Currently I'm using an in-memory hsql DB to do unit testing on the database, which obviously isn't compatible with these MySQL specific queries. I end up running my tests against a local mysql instance.</p>
<p>As expected this is leading to drop in code coverage and  code being dropped to production without automated testing.</p>
<p>What are my options here apart from using a central MySQL instance to run these tests?</p>
<p>Sample method for reference -</p>
<pre><code>public void bulkLoad(Connection connection) {
      String bulkLoadQuery = &quot;LOAD DATA CONCURRENT LOCAL INFILE ? REPLACE INTO TABLE my_table (id, name)&quot;
      try (PreparedStatement statement = connection.prepareStatement( bulkLoadQuery ) {
          statement.setString( 1, fileToUpload );
          statement.execute();
       }
}
</code></pre>
",https://stackoverflow.com/questions/64078422/unit-testing-jdbc-methods-with-mysql-specific-queries,"['mysql', 'unit-testing', 'continuous-integration']",46,False,0,1
AskTimeoutException during Embedded Kafka Unit testing Akka Java,"<p>I am working on <strong>akka</strong> with <strong>Kafka</strong> and writing test cases for my Kafka Consumer.
I used Embedded Kafka for unit testing.</p>

<p>When i try to run my test case everything goes fine, but in last following Exception occurred:</p>

<pre><code>akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://testActor/system/StreamSupervisor-0/flow-0-1-mapAsyncUnordered#-2130769]] after [1000 ms]. Message of type [akka.stream.impl.fusing.ActorGraphInterpreter$Snapshot$] was sent by [Actor[akka://testActor/system/StreamSupervisor-0#-867168141]]. A typical reason for `AskTimeoutException` is that the recipient actor didn't send a reply.

at akka.pattern.PromiseActorRef$.$anonfun$defaultOnTimeout$1(AskSupport.scala:675)
at akka.pattern.PromiseActorRef$.$anonfun$apply$1(AskSupport.scala:696)
at akka.actor.Scheduler$$anon$4.run(Scheduler.scala:202)
at scala.concurrent.Future$InternalCallbackExecutor$.unbatchedExecute(Future.scala:875)
at scala.concurrent.BatchingExecutor.execute(BatchingExecutor.scala:113)
at scala.concurrent.BatchingExecutor.execute$(BatchingExecutor.scala:107)
at scala.concurrent.Future$InternalCallbackExecutor$.execute(Future.scala:873)
at akka.actor.LightArrayRevolverScheduler$TaskHolder.executeTask(LightArrayRevolverScheduler.scala:334)
at akka.actor.LightArrayRevolverScheduler$$anon$3.executeBucket$1(LightArrayRevolverScheduler.scala:285)
at akka.actor.LightArrayRevolverScheduler$$anon$3.nextTick(LightArrayRevolverScheduler.scala:289)
at akka.actor.LightArrayRevolverScheduler$$anon$3.run(LightArrayRevolverScheduler.scala:241)
at java.lang.Thread.run(Thread.java:748)
</code></pre>

<p>Here is my code.</p>

<p>My Test method is:</p>

<pre><code>@Test
public void publishMessage() {

    final TestKit probe = new TestKit(system);
    final Config config = system.settings().config().getConfig(""akka.kafka.producer"");
    ActorRef childMaker = probe.getTestActor();

    final ProducerSettings&lt;String, String&gt; producerSettings =
            ProducerSettings.create(config, new StringSerializer(), new StringSerializer())
                    .withBootstrapServers(bootstrapServers);

    Source.range(1, 10)
            .map(Object::toString)
            .map(value -&gt; new ProducerRecord&lt;&gt;(topic, 0, ""key1"", value))
            .runWith(Producer.plainSink(producerSettings), materializer);

    new EventFilter(Logging.Info.class, system)
            .occurrences(1)
            .matches(""Starting up Consumer:"")
            .matches(""Consumer Started:"")
            .intercept(() -&gt; TestActorRef
                    .create(system, KafkaConsumerPlainExternalSource.props(new RequestRegisterConsumer(system,
                            config, bootstrapServers, groupId, topic, (byte) 0, childMaker))));

}
</code></pre>

<p>My KafkaConsumer Class looks like: </p>

<pre><code>public class KafkaConsumerPlainExternalSource extends AbstractLoggingActor {

private static RequestRegisterConsumer consumerConf;

static Props props(RequestRegisterConsumer consumerConf) {
    return Props.create(KafkaConsumerPlainExternalSource.class, consumerConf);
}

public KafkaConsumerPlainExternalSource(RequestRegisterConsumer consumerConf) {
    KafkaConsumerPlainExternalSource.consumerConf = consumerConf;
}

@Override
public Receive createReceive() {
    return receiveBuilder().build();
}

@Override
public void preStart() {

    log().info(""Starting up Consumer: "" + self().path().toString());

    //Update
akka.kafka.javadsl.Consumer.plainExternalSource(consumer, Subscriptions
                .assignment(new TopicPartition(consumerConf.getTopic(), consumerConf.getTopicPartition())))
                .mapAsync(10, Consumer :: consume)
                .to(Sink.ignore())
                .run(ActorMaterializer.create(consumerConf.getActorSystem()));
    log().info(""Consumer Started: "" + self().path().toString());
}
</code></pre>

<p>}</p>

<p>My application.conf file is:</p>

<pre><code>&gt;    akka { 
&gt;   loggers = [akka.testkit.TestEventListener] 
&gt;     test {
&gt;     timefactor = 1.0
&gt;     filter-leeway = 10s
&gt;     calling-thread-dispatcher {
&gt;       type = akka.testkit.CallingThreadDispatcherConfigurator
&gt;     }   }   kafka.producer {//producer conf} }
</code></pre>

<p>When i add a sleep of 10 sec in last of my test case than my test runs fine. I could not find the root cause of this Exception.</p>
",https://stackoverflow.com/questions/60112945/asktimeoutexception-during-embedded-kafka-unit-testing-akka-java,"['java', 'apache-kafka', 'akka', 'akka-stream']",549,False,0,0
Unit testing by CTest of Cross-compiled Project,"<p>I am developing hobby OS which is cross-compiled to other architecture than my development PC and is run in QEMU emulator.</p>
<p>I am trying to introduce unit testing of the source files I develop for my kernel but to let them run on my development machine rather than in QEMU on my target.</p>
<p>In order to cross-compile my sources, I use the toolchain file which uses my custom GCC toolchain. As coming from CMake principle of toolchain file usage, the toolchain file is set up prior to <code>project(...)</code> definition in my root <code>CMakeLists.txt</code> file.</p>
<p>My question is how to build my test executables for my dev machine (x86_64) using the built-in GCC while cross-compiling my kernel binary for target platform... I do not know how to set <code>CMAKE_CXX_COMPILER</code> / <code>CMAKE_C_COMPILER</code> cmake variables specifically for each use case (testing, target build)</p>
<p>To have a look at my particular project, please feel free to navigate here:<a href=""https://gitlab.com/revolta/revolta"" rel=""nofollow noreferrer"">https://gitlab.com/revolta/revolta</a></p>
<p>I would like to add <code>test/</code> to my project root including selected sources from <code>source/...</code> and manage it somehow from my root <code>CMakeLists.txt</code></p>
<p>Thanks in advance for any concept ideas and help! Cheers Martin</p>
",https://stackoverflow.com/questions/64927375/unit-testing-by-ctest-of-cross-compiled-project,"['unit-testing', 'cmake', 'cross-compiling']",1051,True,0,1
Following Android docs on unit testing and failing,"<p>I am trying to run the simple unit test by following the example here:</p>
<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></p>
<pre><code>import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import org.junit.Test;

import static com.google.common.truth.Truth.assertThat;

public class UnitTestSampleJava {
    private static final String FAKE_STRING = &quot;HELLO_WORLD&quot;;
    private Context context = ApplicationProvider.getApplicationContext();

    @Test
    public void readStringFromContext_LocalizedString() {
        // Given a Context object retrieved from Robolectric...
        ClassUnderTest myObjectUnderTest = new ClassUnderTest(context);

        // ...when the string is returned from the object under test...
        String result = myObjectUnderTest.getHelloWorldString();

        // ...then the result should be the expected one.
        assertThat(result).isEqualTo(FAKE_STRING);
    }
}
</code></pre>
<p>I have a brand new project and I set the gradle files as specified, then I created a test with this line:</p>
<pre><code>private Context context = ApplicationProvider.getApplicationContext();
</code></pre>
<p>and I get an exception on that line number stating:</p>
<pre><code>java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
</code></pre>
<p>However, this was listed in the docs as a local unit test and not an instrumented test.</p>
",https://stackoverflow.com/questions/63440421/following-android-docs-on-unit-testing-and-failing,"['android', 'junit4', 'android-unit-testing']",467,True,0,1
Cmocka unit testing with C: mocking nested function calls,"<p>So, toy program that duplicates the issues I am having using cmocka for developing unit tests for existing code. The issue is a nested function call does not mock, which makes the unit test dependent on the nested function call performing properly. Please note, that ""mockable_static"" define was used as the original code has static functions that exist as ""internal function calls"", but for purposes of unit tests, these are open to external calls. (<a href=""https://stackoverflow.com/questions/49898454/mock-wrap-static-functions-called-by-a-non-static-function-under-test"">See stackoverflow post where this idea came from</a>)</p>

<p>Without further ado, here is the code:</p>

<p>func.h:</p>

<pre><code>#ifndef FUNC_H_
#define FUNC_H_

#ifdef UNIT_TESTING
#define mockable_static
mockable_static char* bar();
#endif

char* foo();

#endif // FUNC_H_
</code></pre>

<p>func.c:</p>

<pre><code>#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#ifndef UNIT_TESTING
#define mockable_static static
#else
#define mockable_static
#endif

mockable_static char* bar (){
    printf(""This is bar!\n"");
    char *str = ""This is the result of bar!"";
    return str;
}

char* foo(){
    printf(""This is foo, and it should return the results of bar()\n"");
    char * res;
    res = bar();
    return res;
}
</code></pre>

<p>test.c:</p>

<pre><code>#include &lt;setjmp.h&gt; /* needs to be before cmocka.h */
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;cmocka.h&gt;

#include ""func.h""

static void test_bar(void **state);
static void test_wrap_bar(void **state);
static void test_foo(void **state);

char* __real_bar();

char* __wrap_bar(){
    printf(""This is a wrap and doesn't return bar!\n"");
    return (char*)mock();
}

int main(void){
    //bar test
    const struct CMUnitTest bar_tests[] = {
        cmocka_unit_test(test_bar),
        cmocka_unit_test(test_wrap_bar)
    };
    const struct CMUnitTest foo_tests[] = {
        cmocka_unit_test(test_foo)
    };
    //foo test w/ mocking bar

    int status;
    status = cmocka_run_group_tests(bar_tests,NULL,NULL);
    status = cmocka_run_group_tests(foo_tests,NULL,NULL);

    printf(""Status = %d\n"",status);
    return status;
}

static void test_bar(void **state){
    char expected_res[] = ""This is the result of bar!"";
    char * actual_res;

    actual_res = __real_bar();
    assert_string_equal(actual_res,expected_res);
}

static void test_wrap_bar(void **state){
    char * this =  ""I don't want bar!"";
    will_return(__wrap_bar,this);

    char * res = bar();
    assert_string_equal(res,this);
}

static void test_foo(void **state){
    char * this =  ""I don't want bar!"";
    will_return(__wrap_bar,this);

    char * res = foo();
    assert_string_equal(res,this);
}
</code></pre>

<p>gcc compile line:</p>

<pre><code>gcc ./test.c ./func.c -DUNIT_TESTING -g -Wl,--wrap=bar -o test -lcmocka-static
</code></pre>

<p>results on test execution:</p>

<pre><code>[==========] Running 2 test(s).
[ RUN      ] test_bar
This is bar!
[       OK ] test_bar
[ RUN      ] test_wrap_bar
This is a wrap and doesn't return bar!
[       OK ] test_wrap_bar
[==========] 2 test(s) run.
[  PASSED  ] 2 test(s).
[==========] Running 1 test(s).
[ RUN      ] test_foo
This is foo, and it should return the results of bar()
This is bar!
[  ERROR   ] --- ""This is the result of bar!"" != ""I don't want bar!""
[   LINE   ] --- ./test.c:59: error: Failure!
[  FAILED  ] test_foo
[==========] 1 test(s) run.
[  PASSED  ] 0 test(s).
[  FAILED  ] 1 test(s), listed below:
[  FAILED  ] test_foo

 1 FAILED TEST(S)
Status = 1
</code></pre>

<p>As you can see, bar() does not get wrapped in foo(), but in the wrap test, bar gets wrapped exactly as foo() calls bar. Bar is tested using __real_bar() which is a part of the cmocka test library (while __real_bar() has a prototype, the function is never defined and returns expected results as per cmocka documentation. Anyone have any experience using unit tests on nested function calls? I haven't found any results of mocking nested function calls with cmocka, but my google-foo might be lacking. If the assert is removed at the end of test_foo(), the test fails due to unused values in the will_return queue.</p>

<pre><code>[==========] Running 2 test(s).
[ RUN      ] test_bar
This is bar!
[       OK ] test_bar
[ RUN      ] test_wrap_bar
This is a wrap and doesn't return bar!
[       OK ] test_wrap_bar
[==========] 2 test(s) run.
[  PASSED  ] 2 test(s).
[==========] Running 1 test(s).
[ RUN      ] test_foo
This is foo, and it should return the results of bar()
This is bar!
[  ERROR   ] --- %s() has remaining non-returned values.
./test.c:56: note: remaining item was declared here

[  FAILED  ] test_foo
[==========] 1 test(s) run.
[  PASSED  ] 0 test(s).
[  FAILED  ] 1 test(s), listed below:
[  FAILED  ] test_foo

 1 FAILED TEST(S)
Status = 1
</code></pre>
",https://stackoverflow.com/questions/60400794/cmocka-unit-testing-with-c-mocking-nested-function-calls,"['c', 'unit-testing', 'cmocka']",2393,True,6,1
"How to pass { history, location, match } when unit testing","<p>I am running tests against the following component:</p>

<pre><code>const App: React.FC&lt;RouteComponentProps&gt; = ({ history, location, match }) =&gt; { ... }
</code></pre>

<p>All the tests are passing however I get this warning:</p>

<pre><code>const { getByText, debug } = render(&lt;MemoryRouter&gt;&lt;Route&gt;&lt;App/&gt;&lt;/Route&gt;&lt;/MemoryRouter&gt;);

Type '{}' is missing the following properties from type 'RouteComponentProps&lt;{}, StaticContext, {}&gt;': history, location, match(2739)
</code></pre>

<p>I was under the impression that <code>&lt;MemoryRouter&gt;</code> &amp; <code>&lt;Route&gt;</code> would provide <code>&lt;App/&gt;</code> with the missing properties...</p>
",https://stackoverflow.com/questions/62034182/how-to-pass-history-location-match-when-unit-testing,"['reactjs', 'typescript', 'react-router-dom', 'react-testing-library']",493,False,5,0
NestJS/TypeORM unit testing: Can&#39;t resolve dependencies of JwtService,"<p>I'm trying to unit test this controller and mock away the services/repositories that it needs.</p>
<pre><code>@Controller('auth')
export class AuthController {
    constructor(
        private readonly authService: AuthService,
        private readonly usersService: UsersService,
    ) {}

    @Post('register')
    public async registerAsync(@Body() createUserModel: CreateUserModel) {
        const result = await this.authenticationService.registerUserAsync(createUserModel);

        // more code here
    }

    @Post('login')
    public async loginAsync(@Body() login: LoginModel): Promise&lt;{ accessToken: string }&gt; {
        const user = await this.usersService.getUserByUsernameAsync(login.username);

        // more code here
    }
}
</code></pre>
<p>Here is my unit test file:</p>
<pre><code>describe('AuthController', () =&gt; {
    let authController: AuthController;
    let authService: AuthService;

    beforeEach(async () =&gt; {
        const moduleRef: TestingModule = await Test.createTestingModule({
            imports: [JwtModule],
            controllers: [AuthController],
            providers: [
                AuthService,
                UsersService,
                {
                    provide: getRepositoryToken(User),
                    useClass: Repository,
                },
            ],
        }).compile();

        authController = moduleRef.get&lt;AuthenticationController&gt;(AuthenticationController);
        authService = moduleRef.get&lt;AuthenticationService&gt;(AuthenticationService);
    });

    describe('registerAsync', () =&gt; {
        it('Returns registration status when user registration succeeds', async () =&gt; {
            let createUserModel: CreateUserModel = {...}

            let registrationStatus: RegistrationStatus = {
                success: true,
                message: 'User registered successfully',
            };

            jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =&gt;
                Promise.resolve(registrationStatus),
            );

            expect(await authController.registerAsync(createUserModel)).toEqual(registrationStatus);
        });
    });
});
</code></pre>
<p>But when running this, I get the following error(s):</p>
<pre><code>  ● AuthController › registerAsync › Returns registration status when user registration succeeds

    Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.

    Potential solutions:
    - If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?
    - If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtModule?
      @Module({
        imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
      })

      at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:191:19)
      at Injector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:147:33)
      at resolveParam (../node_modules/@nestjs/core/injector/injector.js:101:38)
          at async Promise.all (index 0)
      at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:116:27)
      at Injector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:80:9)
      at Injector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:37:9)
      at Injector.lookupComponentInImports (../node_modules/@nestjs/core/injector/injector.js:223:17)
      at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:189:33)

  ● AuthController › registerAsync › Returns registration status when user registration succeeds

    Cannot spyOn on a primitive value; undefined given

      48 |             };
      49 |
    &gt; 50 |             jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =&gt;
         |                  ^
      51 |                 Promise.resolve(registrationStatus),
      52 |             );
      53 |

      at ModuleMockerClass.spyOn (../node_modules/jest-mock/build/index.js:780:13)
      at Object.&lt;anonymous&gt; (Authentication/authentication.controller.spec.ts:50:18)
</code></pre>
<p>I'm not quite sure how to proceed so I'd like some help.</p>
",https://stackoverflow.com/questions/62822943/nestjs-typeorm-unit-testing-cant-resolve-dependencies-of-jwtservice,"['jestjs', 'nestjs', 'typeorm', 'nestjs-jwt']",3503,True,5,3
How to set global environment variables when Unit Testing,"<p>I am trying to create a unit test, however, whenever I run it I encounter <code>null</code> values on my variables. Debugging the issue points to my environment variables not being used globally on my unit test. As a <code>class</code> I'm testing calls another class that then references its values from an environment variable. How do I make use of global environment variables in IntelliJ?.</p>

<p>I've already added Environment Variables in the Test Configuration like this,
<img src=""https://i.stack.imgur.com/dCGjo.png"" alt=""""></p>

<p>However, this doesn't seem to be used on the entire project. Hence classes calling this environment variables are returning null. How do I make my Unit Test and the classes it calls to use the globally declared environment variables?. TIA. Below is a snippet of my code of how my environment variables are being used in a class</p>

<pre><code>@Value(""${fintech.clientid}"")
private String clientId;
@Value(""${fintech.secret}"")
private String clientSecret;
@Value(""${digifi-host}"")
private String fintechHost;
@Value(""${fintech-digifi-login-endpoint}"")
private String loginUrl;
@Value(""${fintech-single-session-endpoint}"")
private String singleSessionUrl;
</code></pre>

<p>What this does is from the Class, it calls the values stored in my application.properties file. And from the application.properties file, it tries to look for the proper values in the environment variables declared on run time.</p>

<pre><code>So from Java Class &gt; application.properties file/config &gt; Runtime Environment Variables 
</code></pre>

<p>Below is the screenshot of variables with null values when debugging the test. As you can see, all of the values are null which means it didn't load the environment variables I have put in the Unit Test. On the other test case where I had a temporary fix (as I put in the answer here), they are populated and hence loading the environment variables properly, but in my many other test cases like this one, it doesn't.</p>

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

<p>PS:
I've already found related articles in stackoverflow, but they are all test-class specific and that uses surefire plugins or setting the environment variables or via pom, but I don't need it to be there as it is a requirement for us to use environment variables on runtime as the values of the variables should be hidden and not visible on the code. I just simply need the entire project to use a global environment variable when it is doing its Unit Test. Much like how my project would use the environment variables I set in the IDE in normal runtime.</p>

<p>Just for Reference. I already did the ff.:</p>

<hr>

<p>A. </p>

<pre class=""lang-java prettyprint-override""><code>@ClassRule
public final static EnvironmentVariables environmentVariables = new EnvironmentVariables().set(""property1"", ""value1"");
</code></pre>

<p>B. </p>

<pre class=""lang-java prettyprint-override""><code>@ContextConfiguration(locations = ""classpath:application.properties"")
public class LoginServiceTest {
...
}
</code></pre>

<p>C.</p>

<pre class=""lang-xml prettyprint-override""><code>&lt;plugin&gt;
    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
    &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
    &lt;configuration&gt;  
      &lt;environmentVariables&gt;
        &lt;SERVER_PORT&gt;8082&lt;/SERVER_PORT&gt;
      &lt;/environmentVariables&gt;
    &lt;/configuration&gt;
&lt;/plugin&gt;
</code></pre>

<p>D.</p>

<pre class=""lang-java prettyprint-override""><code>@TestPropertySource(properties = {""property1=value1"",""property2=value2"",})
public class LoginServiceTest {
...
}
</code></pre>

<p>E.</p>

<pre class=""lang-java prettyprint-override""><code>public class LoginServiceTest {    
static{
      System.setProperty(""property1"", ""value1"");
      System.setProperty(""property2"", ""value2"");            
...
}
</code></pre>
",https://stackoverflow.com/questions/60961768/how-to-set-global-environment-variables-when-unit-testing,"['java', 'spring', 'unit-testing', 'junit']",2449,True,5,1
How to stub Vue component methods for unit testing,"<p>How can I stub certain methods (getters, in particular) from Vue single file components for unit testing with mocha/expect?</p>

<p>The problem I was facing was the following: 
I have a component with a get method <em>someData</em></p>

<pre><code>&lt;script lang=""ts""&gt;
import { Vue, Component } from 'vue-property-decorator'
import SomeService from '@/services/some.service'

@Component()
export default class MyApp extends Vue {
    ...

    mounted () {
      ...
    }

    get someData () {
      return this.$route.path.split('/')[1] || 'main'
    }

    get getLocation () {
      return this.someService.getBaseURL()
    }

    initSomeStringProperty (): string {
      return 'some string'
    }
}
&lt;/script&gt;
</code></pre>

<p>My tests always fail with: </p>

<blockquote>
  <p>[Vue warn]: Error in render: ""TypeError: Cannot read property 'path' of undefined""</p>
</blockquote>

<p>When I try to stub the method using sinon, like following:</p>

<pre><code>describe('MyApp.vue', () =&gt; {
  if('returns main', () =&gt; {
    const dataStub = sinon.stub(MyApp, 'someData')
    listStub.yields(undefined, 'main')
    const wrapper = shallowMount(AppNavBar)
    expect(wrapper.text()).to.include('Some Content')
  })
})
</code></pre>

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

<blockquote>
  <p>TypeError: Cannot stub non-existent own property someData</p>
</blockquote>

<p>In addition, I get the same error for every other method, I want to stub analogously, e.g., initSomeStringProperty().</p>
",https://stackoverflow.com/questions/60150559/how-to-stub-vue-component-methods-for-unit-testing,"['unit-testing', 'vue.js', 'mocha.js', 'sinon']",3515,True,4,2
Svelte 3: Could not import modules when unit testing,"<p>I'm trying to test a Svelte component with Jest. This component works fine in the browser, but unit test fails with importing modules.</p>

<p>For example, when running Jest, <code>import uuid from 'uuid'</code> compiled as <code>const { default: uuid } = require(""uuid"");</code>, and calling <code>uuid.v4()</code> causes <code>TypeError: Cannot read property 'v4' of undefined</code>. When I use <code>import * as uuid from 'uuid'</code> or <code>const uuid = require('uuid')</code>, Jest unit test passes, but it doesn't work in the browser.</p>

<p>How can I deal with this issue? Any information would greatly help. Thank you.</p>

<p>package.json:</p>

<pre><code>{
  ""name"": ""svelte-app"",
  ""version"": ""1.0.0"",
  ""scripts"": {
    ""build"": ""rollup -c"",
    ""dev"": ""rollup -c -w"",
    ""start"": ""firebase serve --only hosting""
  },
  ""devDependencies"": {
    ""@rollup/plugin-json"": ""^4.0.0"",
    ""@testing-library/jest-dom"": ""^5.1.1"",
    ""@testing-library/svelte"": ""^1.11.0"",
    ""bulma"": ""^0.8.0"",
    ""eslint"": ""^6.7.0"",
    ""eslint-config-standard"": ""^14.1.0"",
    ""eslint-plugin-import"": ""^2.18.2"",
    ""eslint-plugin-jest"": ""^23.0.4"",
    ""eslint-plugin-node"": ""^10.0.0"",
    ""eslint-plugin-promise"": ""^4.2.1"",
    ""eslint-plugin-standard"": ""^4.0.1"",
    ""eslint-plugin-svelte3"": ""^2.7.3"",
    ""jest-transform-svelte"": ""^2.1.1"",
    ""node-sass"": ""^4.13.1"",
    ""rollup"": ""^1.12.0"",
    ""rollup-jest"": ""0.0.2"",
    ""rollup-plugin-commonjs"": ""^10.0.0"",
    ""rollup-plugin-livereload"": ""^1.0.0"",
    ""rollup-plugin-node-builtins"": ""^2.1.2"",
    ""rollup-plugin-node-globals"": ""^1.4.0"",
    ""rollup-plugin-node-resolve"": ""^5.2.0"",
    ""rollup-plugin-svelte"": ""^5.0.3"",
    ""rollup-plugin-terser"": ""^5.1.2"",
    ""sirv-cli"": ""^0.4.5"",
    ""svelma"": ""^0.3.2"",
    ""svelte"": ""^3.18.2"",
    ""svelte-preprocess"": ""^3.4.0""
  },
  ""dependencies"": {
    ""firebase"": ""^7.8.2""
  },
  ""private"": true
}
</code></pre>

<p>rollup.config.js</p>

<pre><code>import json from '@rollup/plugin-json'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'rollup-plugin-node-builtins'
import globals from 'rollup-plugin-node-globals'
import livereload from 'rollup-plugin-livereload'
import resolve from 'rollup-plugin-node-resolve'
import svelte from 'rollup-plugin-svelte'
import { terser } from 'rollup-plugin-terser'
import preprocess from 'svelte-preprocess'

const production = !process.env.ROLLUP_WATCH

export default {
  input: 'src/main.js',
  output: {
    sourcemap: true,
    format: 'iife',
    name: 'app',
    file: 'public/build/bundle.js',
  },
  plugins: [
    // https://github.com/rollup/plugins/tree/master/packages/json
    json(),

    svelte({
      // enable run-time checks when not in production
      dev: !production,
      // we'll extract any component CSS out into
      // a separate file — better for performance
      css: css =&gt; {
        css.write('public/build/bundle.css')
      },
      preprocess: preprocess(),
    }),

    // If you have external dependencies installed from
    // npm, you'll most likely need these plugins. In
    // some cases you'll need additional configuration —
    // consult the documentation for details:
    // https://github.com/rollup/rollup-plugin-commonjs
    resolve({
      browser: true,
      dedupe: importee =&gt; importee === 'svelte' || importee.startsWith('svelte/'),
    }),
    commonjs(),
    globals(),
    builtins(),

    // In dev mode, call `npm run start` once
    // the bundle has been generated
    !production &amp;&amp; serve(),

    // Watch the `public` directory and refresh the
    // browser on changes when not in production
    !production &amp;&amp; livereload('public'),

    // If we're building for production (npm run build
    // instead of npm run dev), minify
    production &amp;&amp; terser(),
  ],
  watch: {
    clearScreen: false,
  },
}

function serve () {
  let started = false

  return {
    writeBundle () {
      if (!started) {
        started = true

        require('child_process').spawn('npm', ['run', 'start'], {
          stdio: ['ignore', 'inherit', 'inherit'],
          shell: true,
        })
      }
    },
  }
}
</code></pre>

<p>jest.config.js</p>

<pre><code>const sveltePreprocess = require('svelte-preprocess')

module.exports = {
  displayName: { name: 'web', color: 'magentaBright' },
  moduleFileExtensions: [
    'js',
    'json',
    'svelte',
  ],
  preset: 'rollup-jest',
  transform: {
    '\\.js$': 'rollup-jest',
    '\\.svelte$': ['jest-transform-svelte', { preprocess: sveltePreprocess(), debug: true }],
  },
  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
}
</code></pre>
",https://stackoverflow.com/questions/60323002/svelte-3-could-not-import-modules-when-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'svelte', 'svelte-3']",3837,True,4,3
&#39;FIRESTORE INTERNAL ASSERTION FAILED: Unexpected state&#39; when unit testing with Jest,"<p>I'ḿ setting up a jest test suite for a Node.js and Express REST API i'm building, i'm using @firebase/testing module to initialize a testing app, however when i try to perform any sort of operation to the database this error comes out:</p>
<pre><code>FIRESTORE (7.17.2) INTERNAL ASSERTION FAILED: Unexpected state
      at fail (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/util/assert.ts:39:9)
      at hardAssert (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/util/assert.ts:53:5)
      at fromBytes (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/remote/serializer.ts:270:5)
      at fromWatchChange (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/remote/serializer.ts:486:25)
      at PersistentListenStream.onMessage (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/remote/persistent_stream.ts:576:25)
      at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/remote/persistent_stream.ts:456:21
      at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/remote/persistent_stream.ts:509:18
      at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/@firebase/testing/node_modules/@firebase/firestore/src/util/async_queue.ts:369:14
</code></pre>
<p>I also tried connecting to my regular firestore database with the credentials i have been using to develop the endpoints and same error pops out even tho it's the app i use daily</p>
<p>Weird thing is, data is being written to the database, but error still stops testing</p>
<p>Here is firebase setup:</p>
<pre><code>(src/db/functions.js)

let app  = initializeTestApp({ 
    projectId: &quot;illicit&quot;
})
db = app.firestore()
module.exports = { db }
</code></pre>
<p>Function throwing the error</p>
<pre><code>(tests/fixtures/db.js)

const { db } = require('../../src/db/functions')
const bcrypt = require('bcrypt');

const createAdmin = async function() {

    // Encrypt password
    let encPass = await bcrypt.hash(&quot;admin&quot;, 8)

    let admin = {
        name: &quot;Admin Test User&quot;,
        email: &quot;admin@test.com&quot;,
        password: encPass,
        tokens: []
    }

    // Add to db
    let docRef = await db.collection('admins').add(admin) // &lt;- This line throws the error
    return;
}

module.exports = {
    createAdmin
}
</code></pre>
<p>And finally testing file</p>
<pre><code>(tests/glasses.test.js)
const supertest = require('supertest');
const app = require('../src/app')
const functions = require('./fixtures/db')

let adminToken;
let glassesId;

//Executes before any test, here is where error occurs, before any tests
beforeAll( async () =&gt; {
    await functions.createAdmin()
    return
})

test('Should log in an admin', async () =&gt; {
    let response = await supertest(app)
    .post('/admins/login')
    .send({
        email: 'admin@test.com',
        password: 'admin'
    })
    .expect(200);
    expect(response.body.token).toEqual(expect.any(String))
    adminToken = response.token;
});
</code></pre>
<p>This only happens only when i try to test, regular app works just fine</p>
<p>Things i've tried:</p>
<ul>
<li>Firestore rules are read and write true, so it's not a rules error</li>
<li>Mocked Firestore with firebase-mock and Jest seems to work fine, however this is not a
solution, since i need to test data inside the database</li>
</ul>
<p>Hope you can help me :)</p>
",https://stackoverflow.com/questions/63319638/firestore-internal-assertion-failed-unexpected-state-when-unit-testing-with-j,"['node.js', 'firebase', 'unit-testing', 'jestjs', 'firebase-test-lab']",9094,True,16,4
&quot;Cannot read property &#39;length&#39; of undefined&quot; when unit testing,"<p>I am unit-testing a component which renders a list of codes from server. </p>

<p>Response coming is of this format:</p>

<pre><code>{
  ContactActivityView :[
        {
           Code:""AB"",
           IsActive:false,
        },
        {
           Code:""BC"",
           IsActive:true,
        }
        ..
        ...
  ]
}
</code></pre>

<p>In my component.ts file I consume it in the following way:</p>

<pre><code>codesArray: ICodeModel[];

ngOnInit() {
  this.getCodes();
}

getCodes() {
    this.service.getCodes()
      .subscribe((response: ICodeModel[] | []) =&gt; {
        this.codesArray = response['ContactActivityView'];
      },
      error =&gt; console.log(error)
    );
}
</code></pre>

<p>It works fine and I am able to show my data using component.html file:</p>

<pre><code>  ..
  ...
    &lt;div  class=""message"" *ngIf=""codesArray.length === 0""&gt;
      No Data Found.
    &lt;/div&gt;
    &lt;div class=""tbl-row"" *ngFor=""let code of codesArray""&gt;
      &lt;div class=""item""&gt;
        {{ code.Code }}
      &lt;/div&gt;
      &lt;div class=""item""&gt;
        {{ code.IsActive }}
      &lt;/div&gt;
  ..
  ...
</code></pre>

<p>component.service file:</p>

<pre><code>..
...
getCodes(): Observable&lt;ICodeModel[]&gt; {
  return this._service.get(this.codeURL);
}
..
...
</code></pre>

<p>Now when I run my component.spec file it gives me an error: </p>

<pre><code>TypeError: Cannot read property 'length' of undefined
</code></pre>

<p>I realized that in .html my <code>codesArray</code> is <code>undefined</code> due to which length is <code>undefined</code>.</p>

<p>I <code>console</code> my <code>codesArray</code>. It is showing data in comp.ts file but comes <code>undefined</code> in comp.spec file</p>

<p>Not sure what am I doing wrong as I am able to render the data properly, but somehow my test is failing.
Here's my component.spec file</p>

<pre><code>..
...
class MockCodesService {
  getCodes(): Observable&lt;ICodeModel[]&gt; {
    return of([]);
  }

  addCode(param: ICodeModel){
    return of({});
  }

  updateCode(param: ICodeModel) {
    return of({});
  }
}

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        CodesComponent
      ],
      providers: [
        { provide: CommonCrudService, useClass: CommonCrudMockService },
        { provide: MessageService, useClass: MessageMockService },
        { provide: AppService, useClass: AppMockService },
        { provide: CodesService, useClass: MockCodesService }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>Thanks.</p>
",https://stackoverflow.com/questions/61315827/cannot-read-property-length-of-undefined-when-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-test']",7941,False,3,1
How to implement unit testing within the strapi framework,"<p>I'm experimenting with Strapi and would like to create a controller verified by unit tests.</p>

<p><strong>How do I setup Unit tests within Strapi?</strong></p>

<p>I have written the following test</p>

<pre><code>test('checks entity inside boundary',async ()=&gt; {
    ctx={};
    var result = await controller.findnearby(ctx);
    result = {};
    expect(result).anyting();
});
</code></pre>

<p>however, inside my Controller I have code that accesses a global strapi object, which causes this error <code>ReferenceError: strapi is not defined</code></p>

<pre><code>   strapi.log.info('findNearby');
   strapi.log.info(ctx.request.query.lat);
   strapi.log.info(ctx.request.query.long);
</code></pre>

<p>What is the best practice with Strapi and testing?</p>
",https://stackoverflow.com/questions/60699428/how-to-implement-unit-testing-within-the-strapi-framework,"['node.js', 'unit-testing', 'jestjs', 'strapi']",2259,True,3,2
Unit testing ASP.NET MVC ViewBag properties set in view,"<p>I have various ViewBags which I need to test are set correctly. I am starting with testing a simple ViewBag.Title then I will move onto my other ViewBags which actually pass dynamic data.</p>

<p>I am trying to test this ViewBag.Title in the Create.cshtml</p>

<pre><code>@{
    ViewBag.Title = ""Create"";
}
</code></pre>

<p>The Booking controller for this View:</p>

<pre><code>    // GET: Booking/Create
    public ActionResult Create()
    {
        return View();
    }
</code></pre>

<p>I have tried the following:</p>

<pre><code>    [TestMethod]
    public void BookingTest()
    {
        var controller = new BookingController();
        var ar = controller.Create() as ViewResult;
        Assert.AreEqual(""Create"", ar.ViewData[""Title""]);
    }
</code></pre>

<p>Also tried:</p>

<pre><code>    [TestMethod]
    public void BookingTest()
    {
        var controller = new BookingController();
        //var ar = controller.Create() as ViewResult;
        Assert.AreEqual(""Create"", controller.ViewBag.Title);
    }
</code></pre>

<p>Both unit test fail and return the following: <code>Message: Assert.AreEqual failed. Expected:&lt;Create&gt;. Actual:&lt;(null)&gt;.</code></p>

<p>Can anyone see what I am doing wrong?</p>
",https://stackoverflow.com/questions/61187150/unit-testing-asp-net-mvc-viewbag-properties-set-in-view,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing']",591,True,3,1
Vue unit testing: &quot;You are running Vue in development mode.&quot;?,"<p>I understand that in your jest.setup.js code, you are supposed to set </p>

<pre><code>Vue.config.productionTip = false;
Vue.config.devtools = false;
</code></pre>

<p>and I do. In fact, here is my jest.setup.js code. Notice the console.log('yo ho');</p>

<pre><code>// test/setup.js

import Vue from 'vue';
import Vuetify from 'vuetify';
import { config } from '@vue/test-utils';
import VueCompositionApi from '@vue/composition-api'; // &lt;-- Make the import

Vue.use(Vuetify);
Vue.use(VueCompositionApi);
Vue.config.productionTip = false;
Vue.config.devtools = false;
console.log('yo ho');
// https://vue-test-utils.vuejs.org/
// and this came from: https://github.com/kazupon/vue-i18n/issues/323
// it mocks out the $t function to return the key so you can test that the right key is being used
config.mocks = {
  $t: (key) =&gt; 'i18n:' + key
};

</code></pre>

<p>So given that, I don't expect to get these warnings - ever. But I do on about 1/3 of my unit test files. Not all my unit test files, just some of them. I am really confused. </p>

<p>So I then added that console log statement to ensure that on the unit tests that I am getting this warning, the jest.setup.js is actually getting called.  This is the output from one of my unit tests:</p>

<pre><code>PASS src/components/announcement-banner.test.ts (8.255s)

  ● Console

    console.log tests/unit/jest.setup.js:12
      yo ho
    console.info node_modules/Vue/dist/vue.runtime.common.dev.js:8403
      Download the Vue Devtools extension for a better development experience:
      https://github.com/vuejs/vue-devtools
    console.info node_modules/Vue/dist/vue.runtime.common.dev.js:8412
      You are running Vue in development mode.
      Make sure to turn on production mode when deploying for production.
      See more tips at https://vuejs.org/guide/deployment.html

</code></pre>

<p>How in the world I am I getting the Vue warning, when I am definitely executing the jest.setup?</p>

<p>to make these warnings go away, I have to go to the specific test file and add the config lines directly before the createLocalVue() call.</p>

<pre><code>Vue.config.productionTip = false;
Vue.config.devtools = false;
const localVue = createLocalVue();
</code></pre>
",https://stackoverflow.com/questions/61469650/vue-unit-testing-you-are-running-vue-in-development-mode,"['vue.js', 'vue-test-utils']",2843,True,9,3
How to mock the view model with Hilt for unit testing fragments?,"<p>I've got an android app setup for dependency injection using Hilt, and would like to unit test my fragments.</p>
<p>I'm currently creating my view model using:</p>
<pre><code>private val viewModel: ExampleViewModel by viewModels()
</code></pre>
<p>And I am creating the fragment for testing using the code from <a href=""https://github.com/android/architecture-samples/blob/dev-hilt/app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/HiltExt.kt#L38"" rel=""noreferrer"">here</a></p>
<p>I need to replace this ExampleViewModel with a mock, how would I go about doing this?</p>
",https://stackoverflow.com/questions/62823817/how-to-mock-the-view-model-with-hilt-for-unit-testing-fragments,"['android', 'kotlin', 'android-viewmodel', 'dagger-hilt']",5571,True,22,1
How to perform Unit testing on PySpark Structured Streaming?,"<p>I'm using PySpark Structured Streaming with Kafka as a reader stream. For the sake of unit testing, I would like to replace Kafka reader stream with a mock. How can I do this?</p>
<p>The following question is equivalent to mine but I use Python (PySpark) instead of Scala. And I couldn't find MemoryStream in PySpark.</p>
<p><a href=""https://stackoverflow.com/questions/56894068/how-to-perform-unit-testing-on-spark-structured-streaming"">How to perform Unit testing on Spark Structured Streaming?</a></p>
",https://stackoverflow.com/questions/62981805/how-to-perform-unit-testing-on-pyspark-structured-streaming,"['pyspark', 'spark-streaming']",1358,False,3,0
Unit Testing a Retrieve TableOperation for Azure Table Storage,"<p>I have some code that I'd like to unit test.<br>
I am retrieving some data from an Azure Storage Table database as part of my method that I'd like to test, so I need to mock out the return from the database.</p>

<p><strong>Code to test:</strong></p>

<pre><code>public class GetCustomer : IGetCustomer
{
   //constructor
   public GetCustomer(IClientTableFactory clientTableFactory)
   {
      _partitionKey = ""test"";
      _customersTable = clientTableFactory.GetStorageTable(""customers"");
   }

   //method to test
   public async Task&lt;string&gt; GetCustomerNameAsync(string email)
   {
      //match on full email
      var match = await SearchAsync(email.ToLower());
      if (match == null)
      {
         //just match on email domain
         var domain = email.ToLower().Substring(email.IndexOf(""@""));
         match = await SearchAsync(domain);
      }
      return match;
   }

   //internal method that queries Azure Table Storage
   private async Task&lt;string&gt; SearchAsync(string searchString)
   {
      var query = TableOperation.Retrieve&lt;Customer&gt;(_partitionKey, rowkey: searchString);
      var result = await _customersTable.ExecuteAsync(query);
      var match = result.Result as Customer;
      return match?.Name;
   }
}
</code></pre>

<p><strong>Unit Test so far:</strong></p>

<pre><code>//Arrange
var email = ""Testy.McTest@Test.com.au"";
var tableFactory = new Mock&lt;IClientTableFactory&gt;();
var customersTable = new Mock&lt;CloudTable&gt;(new Uri(""http://unittests.localhost.com/FakeTable""));
customersTable.Setup(x =&gt; x.ExecuteAsync(It.IsAny&lt;TableOperation&gt;()))
   .ReturnsAsync(new TableResult{ HttpStatusCode = 200, Result = new Customer{ Name = ""jiminy crickets"" }});
tableFactory.Setup(x =&gt; x.GetStorageTable(""customers"")).Returns(customersTable.Object);
var getCustomers = new GetCustomer(tableFactory.Object);
// Act
var result = await getCustomers.GetCustomerNameAsync(email);
// Assert
Assert.AreEqual(""jiminy crickets"", result);
</code></pre>

<p>Of course, the test passes every time. The missing piece of the puzzle that I would like to mock out is this line:  </p>

<pre><code>customersTable
    .Setup(x =&gt; x.ExecuteAsync(It.IsAny&lt;TableOperation&gt;()))
    .ReturnsAsync...
</code></pre>

<p>I should be able to replace <code>It.IsAny&lt;TableOperation&gt;()</code> with my search query eg <code>It.Is&lt;TableOperation&gt;(y =&gt; y.RowKey == ""testy.mctest@test.com.au""</code> but unfortunately RowKey is inaccessible. </p>

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

<pre><code>customersTable
    .Setup(x =&gt; x.ExecuteAsync(TableOperation.Retrieve&lt;Customer&gt;(_partitionKey, rowkey: searchString))
</code></pre>

<p>but it never passes this code at runtime - maybe because of the <code>ETag</code> property?</p>

<p>Any ideas? I've seen plenty of answers about mocking Table Storage, but none about mocking Query results.</p>
",https://stackoverflow.com/questions/62212232/unit-testing-a-retrieve-tableoperation-for-azure-table-storage,"['c#', 'azure', 'unit-testing', 'moq', 'azure-table-storage']",1594,True,3,1
Apache Beam Python Unit Testing a ParDo class with_outputs,"<p>I have a ParDo class that checks if a pubsub message contains certain attributes and returns a valid and invalid TaggedOutput (that works fine in the normal flow, using yield for returning the values), and I am not able to do unit testing for this class, I am trying to provide a dummy message (dictionary replicating pubsub message info) and I want to check if the output of the class contains other attributes.</p>

<p>this is what I have so far:</p>

<pre><code>class TestValidateMessage(unittest.TestCase):

def test_not_valid(self):
    with TestPipeline() as p:
        pcoll = (
                p
                | beam.Create([{'attributes':{""imageUrl"":000}}])
                | beam.ParDo(ValidateMessage()).with_outputs(
        'invalid', main='valid'))
    valid, _ = pcoll
    invalid = pcoll['invalid']
    print(invalid)
    assert_that(invalid, {'failure_step':'Message validation'})
</code></pre>

<p>With this I get an error message:</p>

<pre><code>TypeError: Map can be used only with callable objects. Received {'failure_step'} instead.
</code></pre>

<p>When I try to print(invalid), I get <code>PCollection[ParDo(ValidateMessage)/ParDo(ValidateMessage).invalid]</code>
How do I access (for asserting purposes) the content of the PCollection?</p>
",https://stackoverflow.com/questions/60999791/apache-beam-python-unit-testing-a-pardo-class-with-outputs,"['python', 'unit-testing', 'apache-beam', 'google-cloud-pubsub']",1345,True,2,1
Should I mock every single dependencies in unit testing?,"<p>After a lot reading, I found that people advice to mock every dependencies in a method under unit test.</p>

<p><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><a href=""https://stackoverflow.com/questions/38181/when-should-i-mock"">When should I mock?</a></p>

<p>However, I have a method that creates a list of objects (the dependencies) and uses the method these objects to alter the list. In the real-life scenario, the method is transforming data payload sent by the client into these objects.
Below is the code implementation in Typescript but it just gives you an idea.</p>

<pre><code>import {expect} from 'chai';

import 'mocha';

class Bar {
    private val: number;

    constructor(val: number) {
        this.val = val;
    }

    isValid(): boolean {
        return this.val !== 2;
    }

    canMergeWith(bar: Bar): boolean {
        return this.val === bar.val;
    }
}

class BarBuilder {
    constructor() {
    }

    createBars(payload: number[]): Bar[] {
        const bars: Bar[] = [];
        payload.forEach(p =&gt; {
            bars.push(new Bar(p));
        });

        const filtered = this.filterBars(bars);
        const merged = this.mergeBars(filtered);
        return merged;
    }

    private filterBars(bars: Bar[]): Bar[] {
        return bars.filter(b =&gt; b.isValid());
    }

    private mergeBars(bars: Bar[]): Bar[] {
        const merged: Bar[] = [];
        bars.forEach((bar, i) =&gt; {
            if (i &gt; 0) {
                const before = bars[i - 1];
                if (!bar.canMergeWith(before)) {
                    merged.push(bar);
                }
            } else {
                merged.push(bar);
            }
        });
        return merged;
    }
}

describe('BarBuilder', () =&gt; {
    it('Should convert payload into valid bars', () =&gt; {
        const payload = [1, 2, 3, 4, 4, 5, 5];
        const barBuilder = new BarBuilder();
        const bars = barBuilder.createBars(payload);
        expect(bars).to.deep.equal([{val: 1}, {val: 3}, {val: 4}, {val: 5}]);
    });
});
</code></pre>

<p>Currently, the test is passing. But it is violating the rule that <strong>I should mock every dependency in the class</strong>.</p>

<p>My question which one of the following should I do: </p>

<ol>
<li>Should I really mock the class Bar in order to comply to that rule?</li>
</ol>

<p>If so, I find another difficulty doing that. If I mock the class Bar, how do I make the mock methods <code>canMergeWith</code> and <code>isValid</code>  return true or false based on their input? Isn't the equivalent as re-writting the class itself?</p>

<ol start=""2"">
<li>Should I refactor my code instead?</li>
</ol>

<p>I was also thinking probably the problem is with my code being not testable. Before, the methods <code>canMergeWith</code> and <code>isValid</code> belonged to <code>BarBuilder</code>. For the sake of readability, I moved them inside Bar. But now, the unit testing <code>BarBuilder</code> is not trival anymore .</p>

<ol start=""3"">
<li>Leave the test as it is despite the fact that it is violating unit testing rule.</li>
</ol>
",https://stackoverflow.com/questions/61793083/should-i-mock-every-single-dependencies-in-unit-testing,"['unit-testing', 'oop', 'language-agnostic']",1409,True,2,1
How to unit testing with jest in vue composition api component?,"<p>I'm writing a unit test with jest, for my composition API component in vue.js.</p>

<p>But I can't access to functions in composition API's setup().</p>

<p><strong>Indicator.vue</strong></p>

<pre><code>&lt;template&gt;
  &lt;div class=""d-flex flex-column justify-content-center align-content-center""&gt;
    &lt;ul class=""indicator-menu d-flex justify-content-center""&gt;
      &lt;li v-for=""step in steps"" :key=""step""&gt;
        &lt;a href=""#"" @click=""updateValue(step)"" :class=""activeClass(step, current)""&gt; &lt;/a&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
    &lt;div class=""indicator-caption d-flex justify-content-center""&gt;
      step
      &lt;span&gt; {{ current }}&lt;/span&gt;
      from
      &lt;span&gt; {{ steps }}&lt;/span&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import {createComponent} from '@vue/composition-api';

export default createComponent({
  name: 'Indicator',
  props: {
    steps: {
      type: Number,
      required: true
    },
    current: {
      type: Number,
      required: true
    }
  },
  setup(props, context) {
    const updateValue = (step: number) =&gt; {
      context.emit('clicked', step);
    };
    const activeClass = (step: number, current: number) =&gt;
      step &lt; current ? 'passed' : step === current ? 'current' : '';
    return {
      updateValue,
      activeClass
    };
  }
});
&lt;/script&gt;

&lt;style&gt;&lt;/style&gt;
</code></pre>

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

<pre><code>import Indicator from '@/views/components/Indicator.vue';
import { shallowMount } from '@vue/test-utils';

describe('@/views/components/Indicator.vue', () =&gt; {  
  let wrapper: any;
  beforeEach(() =&gt; {
    wrapper = shallowMount(Indicator, {
      propsData: {
        steps: 4,
        current: 2
      }
    });
  });
  it('should return ""current"" for values (2,2)', () =&gt; {
    expect(wrapper.vm.activeClass(2, 2)).toBe('current');
  });
});
</code></pre>

<p>And I got this Error, in running test command:</p>

<blockquote>
  <p>TypeError: Cannot read property 'vm' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/60377091/how-to-unit-testing-with-jest-in-vue-composition-api-component,"['typescript', 'unit-testing', 'vue.js', 'jestjs', 'vue-composition-api']",9059,True,15,3
Unit testing a component that uses other components (wrapping),"<p>I have not been able to find answers to my question and I'm not sure if its because nobody else struggled with it before? Or my wording is incorrect. So here I am.</p>

<p>Let's say we have a Dialog component that looks like this (some parts were left off for simplicity sake):</p>

<pre><code>import React from 'react';
import Modal from './Modal';

export default class Dialog extends React.Component {
  render() {
    const { children, dialogCss, ...modalProps } = this.props;

    return (
      &lt;Modal role=""dialog"" {...modalProps}&gt;
        &lt;div&gt;
          &lt;div dialogCss={dialogCss}&gt;{children}&lt;/div&gt;
        &lt;/div&gt;
      &lt;/Modal&gt;
    );
  }
}
</code></pre>

<p>As you can see from the code, <code>Dialog</code> component uses <code>Modal</code> component under the hood.</p>

<p>How should I approach unit testing?</p>

<ul>
<li>Do I unit test Dialog specific functionalities only (which is only css)?</li>
<li>Do I unit test Dialog specific functionality AND Modal functionality through Dialog?</li>
</ul>

<p>For example, Modal has a boolean prop called <code>open</code> that renders or doesn't render the component. I already tested Modal, and in that Modal test, I test that <code>open</code> prop set to false or true is respected.</p>

<p>Dialog also uses <code>open</code>, do I need to test that ""Dialog"" also respects the <code>open</code> prop set to false or true? </p>

<p>This is how it is currently being tested and it is testing Dialog specific functionality ONLY because my reasoning is: even though Dialog is using Modal under the hood, since Modal itself has been tested, it will be redundant to test it through Dialog again. Please correct me if I am wrong.</p>

<pre><code>import React from 'react';
import Dialog from './Dialog';

const testCss = {
  'background-color': '#fff',
  color: '#000',
};

test('respects dialogCss prop', () =&gt; {
  const { getByTestId } = render(
    &lt;Dialog open={true} dialogCss={() =&gt; testCss}&gt;
      &lt;div&gt;hello&lt;/div&gt;
    &lt;/Dialog&gt;
  );

  expect(getByTestId('dialogbox')).toHaveStyle({ ...testCss });
});

test('renders children', () =&gt; {
  const { getByTestId } = render(
    &lt;Dialog open={true}&gt;
      &lt;div data-testid=""test""&gt;hello&lt;/div&gt;
    &lt;/Dialog&gt;
  );

  expect(getByTestId('test')).not.toBeNull();
});
</code></pre>

<p>And here is the dispute: someone said <code>your dialog is still a dialog and you'd expect anything that depends on it to not break</code>, meaning we SHOULD be testing that Modal is working through Dialog. Meaning that Dialog should test that <code>open</code> is being respected, even though Modal itself is testing for it.</p>

<p>Two opposing thoughts, and we are all new to front end unit testing. Any help is appreciated!</p>

<p>Thank you for your time and help!</p>
",https://stackoverflow.com/questions/60213494/unit-testing-a-component-that-uses-other-components-wrapping,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",260,False,2,0
Python how to check internal functionalities with unit testing,"<p>I have the following test</p>

<pre><code>from unittest.mock import ANY

try:
    from unittest import mock  # python 3.3+
except ImportError:
    import mock  # python 2.6-3.2

import pytest

from data_cleaning import __main__ as data_cleaning


@mock.patch('Repositories.repository.Repository.delete')
@pytest.mark.parametrize(""argv"", [
    (['-t', 'signals']),
    (['-t', 'signals', 'visualizations']),
    (['-t', 'signals', 'visualizations']),
    (['-d', '40', '--processes', 'historicals'])])
def test_get_from_user(mock_delete, argv):
    with mock.patch('data_cleaning.__main__.sys.argv', [''] + argv):
        data_cleaning.main()

    mock_delete.assert_has_calls([ANY])


pytest.main('-x ../data_cleaning'.split())
</code></pre>

<p>which tries to cover the following code</p>

<pre><code>import argparse
import logging
import sys

from Repositories import repository
from common import config

_JSONCONFIG = config.config_json()
config.initial_configuration_for_logging()


def parse_args(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--days', help='Dias de datos que se quiere mantener.',
                        required=False, type=int, default=30)
    parser.add_argument('-p', '--processes', help='Tablas a procesar.',
                        required=True, nargs='+', choices=['signals', 'not_historicals', 'historicals'])
    return parser.parse_args(args)


def main():
    args = parse_args(sys.argv[1:])
    try:
        repo = repository.Repository()
        for process in args.processes:
            if process == 'signals':
                tables_with_column = get_tables_with_column(_JSONCONFIG['SIGNAL_TABLES'])
                for table, column in tables_with_column:
                    repo.delete(column, table, args.days)
            elif process == 'not_historicals':
                tables_with_column = get_tables_with_column(_JSONCONFIG['NOT_HISTORICALS_TABLES'])
                for table, column in tables_with_column:
                    repo.delete(column, table, args.days)
            elif process == 'historicals':
                tables_with_column = get_tables_with_column(_JSONCONFIG['HISTORICAL_TABLES'])
                for table, column in tables_with_column:
                    repo.delete(column, table, args.days)
                    repo.execute_copy_table_data_from(table, 'historica')

    except AttributeError as error:
        logging.exception(f'AttributeError: {repr(error)}')
    except KeyError as error:
        logging.exception(f'KeyError: {repr(error)}')
    except TypeError as error:
        logging.exception(f'TypeError: {repr(error)}')
    except Exception as error:
        logging.exception(f'Exception: {repr(error)}')


def get_tables_with_column(json_object):
    tables_with_column = convert_values_to_pairs_from(json_object, 'table_name', 'column_name')
    return tables_with_column


def convert_values_to_pairs_from(obj: [dict], ket_to_key: str, key_to_value: str) -&gt; [tuple]:
    return [(item[ket_to_key], item[key_to_value]) for item in obj]
</code></pre>

<p>How can I cover 100% of my code through tests? the test case that specified how well implemented is it? What do I have to cover in my tests so that this module is fully covered?</p>

<p>How should I cover testing for this code? I am starting in unit tests, but I have been more than 2 months and I have a hard time understanding what I should test.</p>
",https://stackoverflow.com/questions/62035145/python-how-to-check-internal-functionalities-with-unit-testing,"['python', 'unit-testing', 'pytest']",102,True,2,1
Nodejs unit testing with redis-mock results in ECONNREFUSED,"<p>I'm currently having a class in NodeJS which will create a redis client when being instantiated. I am trying to write a unit test to test this class. However, I am unsure to to get the main code work with the redis-mock use in the unit test.</p>
<p>During the unit test, this line of code returned <code>redis.createClient(config.get('redis.port'), config.get('redis.ip'));</code> -&gt; <code>connect ECONNREFUSED</code></p>
<pre><code>class Socket {

    constructor(socketClient) {

        /** For socket io */
        this.socketClient = socketClient;
        log.info(&quot;new socketio client connected... &quot; + socketClient.id);        
        
        /** For redis */
        // a redis client is created and connects
        this.redisClient = redis.createClient(config.get('redis.port'), config.get('redis.ip'));

        this.redisClient.on('connect', function() {
            log.info('Redis client connected ' + socketClient.id);
        });
        this.redisClient.on('error', function (err) {
            log.error('Redis client something went wrong ' + err);
        });
        this.redisClient.on('message', function (channel, message) {
            log.info('Redis message received...' + socketClient.id + &quot; socketio emitting to &quot; + channel + &quot;: &quot; + message);
            socketClient.emit('updatemessage', message)
        });
    }

}
</code></pre>
<p>This is the unit test code:</p>
<pre><code>'use strict'

var expect = require('chai').expect
  , server = require('../index')
  , redis = require('redis-mock')
  , redisClient
  , io = require('socket.io-client')
  , ioOptions = { 
      transports: ['websocket']
    , forceNew: true
    , reconnection: false
  }
  , testMsg = JSON.stringify({message: 'HelloWorld'})
  , sender
  , receiver
  



describe('Chat Events', function(){
  beforeEach(function(done){
    
    redisClient = redis.createClient();
    // start the io server
    //server.start()
    // connect two io clients
    sender = io('http://localhost:3000/', ioOptions)
    receiver = io('http://localhost:3000/', ioOptions)
    
    // finish beforeEach setup
    done()
  })
  afterEach(function(done){
    
    redisClient.disconnect
    // disconnect io clients after each test
    sender.disconnect()
    receiver.disconnect()
    done()
  })

  describe('Message Events', function(){
    it('Clients should receive a message when the `message` event is emited.', function(done){
      sender.emit('message', testMsg)
      receiver.on('ackmessage', function(msg){
        expect(msg).to.contains(testMsg)
        done()
      })
    })
  })
})

</code></pre>
",https://stackoverflow.com/questions/62907441/nodejs-unit-testing-with-redis-mock-results-in-econnrefused,"['node.js', 'unit-testing', 'redis']",5441,True,2,1
Unit testing using Jest and Enzym in React Native,"<p>How can I find element inside component with jest and enzyme?</p>

<p>Let say, I have 1 component parent (Login) and 2 child component (Title and Form), so in component Login, I want to find is there TextInput element inside Form component or something else maybe another element inside Form Component, with jest and enzyme, then how can I get that just with 1 unit testing (Login.test.js)?</p>

<p>This is my login component for the ilustration</p>

<pre><code>&lt;Login&gt;
  &lt;Title title='Login Page' /&gt;
  &lt;Form 
     email={this.state.email}
     password={this.state.password}
  /&gt;
&lt;/Login&gt;
</code></pre>

<p>Title Component</p>

<pre><code>&lt;Text&gt;{this.props.title}&lt;/Text&gt;
</code></pre>

<p>Form Component</p>

<pre><code>&lt;View&gt;
  &lt;TextInput value={this.props.email} placeHolder=""Your Email"" /&gt;
  &lt;TextInput value={this.props.password} placeHolder=""Your Password"" /&gt;
&lt;/View&gt;
</code></pre>

<p>This is my current Login.test.js</p>

<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import Login from './Login';
import renderer from 'react-test-renderer';

describe('Login', () =&gt; {
  const wrapper = shallow(&lt;Login /&gt;);
  const instaceOf = wrapper.instance();

  it('renders correctly', () =&gt; {
    const rendered = renderer.create(&lt;Login /&gt;).toJSON();
    expect(rendered).toBeTruthy();
  });

  it('should render the Text Input Element', () =&gt; {
    let form = wrapper.find('Form');
    expect(form.find('TextInput""]')).toHaveLength(2);
  });
});
</code></pre>
",https://stackoverflow.com/questions/59798888/unit-testing-using-jest-and-enzym-in-react-native,"['react-native', 'jestjs', 'enzyme']",759,False,2,1
Python unit testing sys.exit call with assertRaises or mock.patch,"<p>I've read a lot of answers suggesting that the way to unit test sys.exit is to do the following:</p>

<pre><code>with self.assertRaises(SystemExit) as system_exit:
    function()
self.assertEqual(system_exit.exception_code, 1)
</code></pre>

<p>Does the above not actually raise a SystemExit in my test? Is it better or worse to do the following?</p>

<pre><code>@mock.patch(""&lt;path to class file&gt;.sys.exit"")
def testFunction(self, mock_sys_exit):
    function()
    mock_sys_exit.assert_called_once_with(1)
</code></pre>

<p>Are both the approaches equivalent, or is one better than the other? And why?</p>
",https://stackoverflow.com/questions/60862835/python-unit-testing-sys-exit-call-with-assertraises-or-mock-patch,"['python', 'mocking', 'python-unittest', 'sys', 'systemexit']",478,False,1,0
Flutter unit testing - unable to pump full widget tree,"<p>I am just getting started with unit testing in Flutter, and I have hit a bit of a wall. I have a fairly simple app located here:
<a href=""https://github.com/chuckntaylor/kwjs_flutter_demo"" rel=""nofollow noreferrer"">https://github.com/chuckntaylor/kwjs_flutter_demo</a></p>

<p>The app is essentially a list view of events where you can tap on one to read more details about the event.</p>

<p><img src=""https://res.cloudinary.com/chucktaylor/image/upload/v1590504833/kwjsApp-optimized.gif"" alt=""KWJS Flutter App in action""></p>

<p>I have two screens for this: <code>events_screen.dart</code> for the list view, and <code>event_screen.dart</code> for the details. I have been trying to write my tests in <code>events_screen_test.dart</code></p>

<p>My testing difficulties are with the events screen (the list view). After running <code>await tester.pumpWidget(MaterialApp(home: EventsScreen())</code> I can use <code>find.text('Events')</code> for example to find the title in the AppBar, but I cannot find any of the elements that make up the list.</p>

<p>To clarify further. I am using <code>get_it</code> as a serviceLocator to get the viewModel for the EventsScreen when it loads. The viewModel is the <code>ChangeNotifierProvider</code>, and EventsScreen contains a <code>Consumer</code> to update the list. in EventsScreen <code>initState()</code>, it calls loadEvents() on the viewModel. After loadEvents() is done, the viewModel calls notifyListeners(), so that EventsScreen can update.</p>

<p>How do I ensure that all these steps occur so that I can properly test if the EventsScreen is rendering properly?</p>

<p>I could be approaching this all wrong, so any advice is appreciated.</p>
",https://stackoverflow.com/questions/62029967/flutter-unit-testing-unable-to-pump-full-widget-tree,"['unit-testing', 'flutter', 'testing', 'dart']",1596,True,1,2
Instantiate a class with decorator ( mobx ) - React : Unit Testing,"<p>Looking for insights with this one.</p>
<p>Say we have</p>
<pre><code>class Thing {

  doSomething() { ... }
}
</code></pre>
<p>and we can</p>
<pre><code>const testThing = new Thing()
testThing.doSomething()
</code></pre>
<p>How, in React, say when we inject with MobX and it wraps everthing can we instantiate ?</p>
<pre><code>@inject('storeThing')
class Thing {

  doSomething() { ... }
}
</code></pre>
<p>now ...</p>
<pre><code>const testThing = new Thing()
testThing.doSomething() /* doSomething undefined because we have the decorator instead */
</code></pre>
<p>Without using enzyme etc <em>( I know how with shallow/mount(Component.wrapper... )</em>  .. in pure JS; how would we call this class to do some basic unit testing ?</p>
<p>Thanks. Hope I made sense.</p>
",https://stackoverflow.com/questions/63040807/instantiate-a-class-with-decorator-mobx-react-unit-testing,"['javascript', 'reactjs', 'mobx']",42,False,1,0
MS Test unit testing framework Won&#39;t Hit its Constructor,"<p>My MSTest test class does contain constructor to initialize logging functionality specific variables.
When running unit test methods in debug mode, found that my debugger is not hitting my constructor. Since we can use <code>[TestInitialize]</code> method in MSTest to force this method to execute before executing any of the methods, I've created <code>Startup()</code> method for this purpose. Even now, debugger is not hitting this method. Hence, all my test methods are failing.</p>
<p>Can anyone please point me where I'm doing wrong! Any suggestions to resolve this issue please...</p>
<pre><code>[TestClass]
public class AutomaticInformationUpdateTest
{
    private readonly ILogger&lt;AutomaticInformationUpdate&gt; _logger;
    private static ILoggerFactory _loggerFactory;
    private readonly IServiceProvider _serviceProvider;

    //ISSUE: When executing individual methods, or complete test class, this constructor is not calling
    public AutomaticInformationUpdateTest(ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
    {
        _loggerFactory = loggerFactory;
        _serviceProvider = serviceProvider;
        _logger = _loggerFactory.CreateLogger&lt;AutomaticInformationUpdate&gt;();
    }

    // ISSUE: I should not use this method as I cannot initialize most of the private variables.
    // Even then, I tried this method with the hope that the debugger can can this method.
    // Debugger is not hitting even for this method.
    [TestInitialize]
    public void Startup()
    {
        _logger = _loggerFactory.CreateLogger&lt;AutomaticInformationUpdate&gt;();
    }

    [TestMethod]
    public void ProcessFullEngineInformation_Test()
    {
        IAutomaticInformationUpdate updater = new AutomaticInformationUpdate(_loggerFactory, _serviceProvider);
        Assert.IsTrue(updater.ProcessFullInformation().GetAwaiter().GetResult()); 
    }

    [TestMethod]
    public void ProcessIncrimentalEngineInformation_Test()
    {
        IAutomaticInformationUpdate updater = new AutomaticInformationUpdate(_loggerFactory, _serviceProvider);
        Assert.IsTrue(updater.ProcessIncrimentalInformation().GetAwaiter().GetResult());
    }

    [TestMethod]
    public void ProcessLvlFullInformation_Test()
    {
        IAutomaticInformationUpdate updater = new AutomaticInformationUpdate(_loggerFactory, _serviceProvider);
        Assert.IsTrue(updater.ProcessLvlFull().GetAwaiter().GetResult());
    }

    [TestMethod]
    public void ProcessLvlIncrimentalInformation_Test()
    {
        IAutomaticInformationUpdate updater = new AutomaticInformationUpdate(_loggerFactory, _serviceProvider);
        Assert.IsTrue(updater.ProcessLvlIncrimental().GetAwaiter().GetResult());
    }
}
</code></pre>
",https://stackoverflow.com/questions/64764226/ms-test-unit-testing-framework-wont-hit-its-constructor,"['c#', 'mstest']",174,False,1,1
Unit Testing Hybrid Angular Js and Angular 8 Application,"<p>I'm working on a angular js and angular 8 hybrid application. The new components created in angular are downgraded to be used in angular js. Code snippet of module is shown below:</p>
<pre><code>@NgModule({
    // Declaration and Imports
    providers:[
        ServiceName,
        // Other Services
    ],
    entryComponents: [
        ComponentName,
        // Other components to be used in angular js
    ]
})
export class FeatureModule{
}

declare var angular: angular.IAngularStatic
angular.module('app')
   .directive('cmpName', downgradeComponent({component: ComponentName }) as angular.IDirectiveFactory)
   .factory('serviceName', downgradeInjectable(ServiceName));
</code></pre>
<p>In <code>app.module.ts</code> file, there is following code.</p>
<pre><code>// Usual Stuff
export class AppModule {
  constructor(
    private upgrade: UpgradeModule,
  ) {
  }

  ngDoBootstrap() {
    this.upgrade.bootstrap(document.body, ['app'], { strictDi: true });
  }
}
</code></pre>
<p>Nothing has been updated in component spec file generated by angular cli.</p>
<p>In <code>tsconfig.spec.json</code>,</p>
<pre><code>{
  &quot;extends&quot;: &quot;../tsconfig.json&quot;,
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;./&quot;,
    &quot;outDir&quot;: &quot;../out-tsc/spec&quot;,
    &quot;types&quot;: [&quot;jasmine&quot;, &quot;node&quot;, &quot;angular&quot;]
  },
  &quot;files&quot;: [&quot;test.ts&quot;, &quot;polyfills.ts&quot;],
  &quot;include&quot;: [&quot;**/*.spec.ts&quot;, &quot;**/*.d.ts&quot;]
}
</code></pre>
<p><code>karma.conf.js</code> looks like below.</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/ProjectFolder'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true
  });
};
</code></pre>
<p>Now, if I run <code>npm run test</code> or <code>ng test</code> command to run test suite, I'm getting following error.<br />
<code>An error was thrown in afterAll Uncaught ReferenceError: angular is not defined ReferenceError: angular is not defined at Module../..path-to-module-file/feature.module.ts.</code></p>
<p>How can I resolve this issue? Do I have to mock <code>angular</code> variable declared in the module file. Any help is appreciated?</p>
",https://stackoverflow.com/questions/64244140/unit-testing-hybrid-angular-js-and-angular-8-application,"['angularjs', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",625,False,1,1
How to negative assert_response in unit testing with Rails,"<p>How can one test if the HTTP response is <strong>not</strong> something in the standard unit-testing framework with Rails (Ver 6.0, more specifically)? Basically it is negation of <a href=""https://apidock.com/rails/v6.0.0/ActionDispatch/Assertions/ResponseAssertions/assert_response"" rel=""nofollow noreferrer"">assert_response</a> like this:</p>
<pre class=""lang-rb prettyprint-override""><code>test &quot;should get index&quot; do
  get restricted_articles_url
  assert_response_NOT :success  # &lt;= this method does not exist.
end
</code></pre>
<p>The background is, the user tested should not be granted access to the URL (or Controller method), but what response would be returned may change later in the development and the exact response is of secondary importance.</p>
",https://stackoverflow.com/questions/64554065/how-to-negative-assert-response-in-unit-testing-with-rails,"['ruby-on-rails', 'unit-testing', 'httpresponse']",207,True,1,2
Unit testing properties for Page Models in Razor Pages,"<p>I have a simple Page Model, <code>PizzaModel</code>:</p>

<pre class=""lang-cs prettyprint-override""><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace starting_app.Pages
{
    public class PizzaModel : PageModel
    {
        public string Customer {get; set;}
        public int Total {get; set;}
        public string SomeProperty {get; set;}   

        public void OnGet()
        {
        }
    }
}
</code></pre>

<p>I'm using the <code>NUnit</code> framework to test for certain properties:</p>

<pre class=""lang-cs prettyprint-override""><code>using System;
using NUnit.Framework;
using blank_workspace.Pages;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;


namespace starting_app.UnitTests
{
  [TestFixture]
  public class Tests
  {
      [Test]
    public void PizzaModel_Asserts_Customer_Property()
    {
      PizzaModel pm = new PizzaModel();


      Assert.That(pm, Has.Property(""Customer""));
    }
  }
}
</code></pre>

<p>Is this the right format?</p>

<p>I'm currently getting another type of error:</p>

<blockquote>
  <p>The type or namespace name ‘NUnit’ could not be found (are you missing a using directive or an assembly reference?) </p>
</blockquote>

<p>But I'm trying to get my syntax correct.</p>
",https://stackoverflow.com/questions/60177698/unit-testing-properties-for-page-models-in-razor-pages,"['c#', 'unit-testing', 'testing', 'nunit', 'razor-pages']",228,False,1,0
Unit testing function in a class that injects EntityManager,"<p>I need help adding unit test to the function below in NestJs.
I have a class with a createOrder function as shown below. the constructor of the class injects an Entity Manager. How can I test for the createOrder function in jest.</p>
<pre class=""lang-js prettyprint-override""><code>    import { Injectable } from '@nestjs/common';
    import * as shortId from 'shortid';
    import { EntityManager, Repository } from 'typeorm';
    import { HttpException, HttpStatus } from '@nestjs/common';

    import { Service } from 'models/service.model';
    
    @Injectable()
    export class OrderService {
      private readonly orderRepository: Repository&lt;Service&gt;;
    
      constructor(private readonly entityManager: EntityManager) {
        this.orderRepository = entityManager.getRepository(Service);
      }
    
      async createOrder(data) {
        const orderService = new Service();

        orderService.id = shortId.generate(); // just to generate a string for id
    
        const orderServiceData = Object.assign(orderService, data);
    
        try {
          
          await this.orderRepository.save(orderServiceData);
          
          return { success: true };
        } catch (err) {
          throw new HttpException('Post not found', HttpStatus.NOT_FOUND);
        }
      }
    }
</code></pre>
<p>This is what I have tried so far. Yet it fails to call the save function</p>
<pre class=""lang-js prettyprint-override""><code>    import { Test, TestingModule } from '@nestjs/testing';
    import { OrderService } from './order_service.service';
    import { Service } from '../../models/service.model';
    import { Repository, EntityManager, getRepository } from 'typeorm';
    import { getRepositoryToken } from '@nestjs/typeorm';
    
    describe('Order Service', () =&gt; {
      let orderService: OrderServiceService;
      let orderRepository: Repository&lt;Service&gt;;
    
      const mockOrderRepository = () =&gt; ({
        save: jest.fn(),
      });
    
      const mockEntityManager = () =&gt; ({
        getRepository: jest.fn(),
      });
    
      beforeEach(async () =&gt; {
        const module: TestingModule = await Test.createTestingModule({
          providers: [
            OrderService,
            {
              provide: EntityManager,
              useFactory: mockEntityManager,
            },
            {
              provide: getRepositoryToken(Service),
              useFactory: mockOrderRepository,
            },
          ],
        }).compile();
    
        orderService = await module.get&lt;OrderService&gt;(
          OrderService,
        );
        orderRepository = await module.get(getRepositoryToken(Service));
      });
    
      it('should check that order service is defined', () =&gt; {
        expect(orderService).toBeDefined();
      });
    
      describe('Create order service', () =&gt; {
        it('should create an order service', () =&gt; {
          expect(orderRepository.save).not.toHaveBeenCalled();
          const data = {
            name: 'Gucci Cloths',
            type: 'Cloths',
          };
    
          orderService.createOrder(data);
          expect(orderRepository.save).toHaveBeenCalled();
        });
      });
    });
</code></pre>
",https://stackoverflow.com/questions/63451064/unit-testing-function-in-a-class-that-injects-entitymanager,"['unit-testing', 'jestjs', 'nestjs', 'entitymanager', 'typeorm']",727,True,1,1
Angular Unit Testing HTTP Error Interceptors catchError/ErrorEvent/Error,"<p>My HTTP Interceptors have really weird problem, which I really cannot manage. More precisely, when changing <code>ErrorEvent</code> to <code>Error</code> and vice versa it covers one of the if/else conditions but making the other one not covered in code coverage. I'm using Angular 9, Jest 24 and RxJS 6.</p>

<p><strong>http-error.interceptor.ts</strong></p>

<pre><code>import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest
} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest&lt;any&gt;,
    next: HttpHandler
  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    let errorMessage: string;

    return next.handle(request).pipe(
      catchError((err: HttpErrorResponse) =&gt; {
        if (err.error instanceof ErrorEvent) {
          // Client-side error.
          errorMessage = `An error occurred: ${err.error.message}`;
          alert('Network error.');
        } else {
          // Server-side error.
          alert('Server unavailable.');
          errorMessage = `Backend returned code ${err.status}, body was: ${err.error}`;
        }

        return throwError(errorMessage);
      })
    );
  }
}
</code></pre>

<p>With this setup, the test below is passing without covering the <code>else</code> part.</p>

<p><strong>http-error.interceptor.spec.ts</strong></p>

<pre><code>import { TestBed } from '@angular/core/testing';
import { HttpErrorInterceptor } from './http-error.interceptor';
import {
  HttpClientTestingModule,
  HttpTestingController
} from '@angular/common/http/testing';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { RegisterService } from './register.service';

describe('HttpErrorInterceptor', () =&gt; {
  let httpErrorInterceptor: HttpErrorInterceptor;
  let httpTestingController: HttpTestingController;
  let registerService: RegisterService;

  beforeEach(async () =&gt;
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        RegisterService,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpErrorInterceptor,
          multi: true
        }
      ]
    })
  );

  beforeEach(() =&gt; {
    httpErrorInterceptor = new HttpErrorInterceptor();
    httpTestingController = TestBed.inject(HttpTestingController);
    registerService = TestBed.inject(RegisterService);
  });

  it('should catch errors when calling fake URL', async () =&gt; {
    const fakeURL = 'https://fakeapi.com';
    const fakeDataToBeSend = {
      firstName: 'Daniel',
      lastName: 'Danielecki',
      email: 'daniel.danielecki@foo.com'
    };

    jest.spyOn(window, 'alert').mockImplementation(() =&gt; {}); // Note: window.alert = jest.fn() works too, but it contaminates other tests, therefore try to avoid it.

    // Make an HTTP POST request
    await registerService.registerUser(fakeDataToBeSend, fakeURL).subscribe(); // https://github.com/angular/angular/issues/18345 ????

    httpTestingController
      .expectOne(fakeURL)
      .error(new ErrorEvent('Network error.')); //Error type instance can't be passed.

    expect(window.alert).toHaveBeenCalledWith('Network error.');

    // httpTestingController
    //   .expectOne(fakeURL)
    //   .error(new ErrorEvent('Server unavailable.')); //Error type instance can't be passed.

    // expect(window.alert).toHaveBeenCalledWith('Server unavailable.');
  });
</code></pre>

<p>Now, in the <strong>http-error.interceptor.ts</strong> I'm changing <code>ErrorEvent</code> to <code>Error</code> and the test will fail. However, if in the <strong>http-error.interceptor.spec.ts</strong> I'll do the changes like below the test is passing. But, the <code>if</code> is not covered, however <code>else</code> is.</p>

<pre><code>// httpTestingController
//   .expectOne(fakeURL)
//   .error(new ErrorEvent('Network error.')); //Error type instance can't be passed.

// expect(window.alert).toHaveBeenCalledWith('Network error.');

httpTestingController
  .expectOne(fakeURL)
  .error(new ErrorEvent('Server unavailable.')); //Error type instance can't be passed.

expect(window.alert).toHaveBeenCalledWith('Server unavailable.')
</code></pre>
",https://stackoverflow.com/questions/60578944/angular-unit-testing-http-error-interceptors-catcherror-errorevent-error,"['angular', 'unit-testing', 'rxjs', 'jestjs', 'angular-http-interceptors']",2122,False,1,0
Unit Testing Dynamic Query JPA Specification on Spring Boot,"<p>I've some class to handle dynamic query like this below</p>

<pre class=""lang-java prettyprint-override""><code>public class QueryFilter&lt;T&gt; implements Specification&lt;T&gt; {

    transient List&lt;SearchCriteria&gt; list;

    public QueryFilter() {
        this.list = new ArrayList&lt;&gt;();
    }

    public void add(SearchCriteria criteria) {
        list.add(criteria);
    }

    @Override
    public Predicate toPredicate(Root&lt;T&gt; root, CriteriaQuery&lt;?&gt; criteriaQuery, CriteriaBuilder builder) {
        //create a new predicate list
        List&lt;Predicate&gt; predicates = new ArrayList&lt;&gt;();

        //add add criteria to predicates
        for (SearchCriteria criteria : list) {
            if (criteria.getOperation().equals(SearchOperation.EQUAL)) {
                predicates.add(builder.equal(root.get(criteria.getKey()), criteria.getValue1()));
            }  else if (criteria.getOperation().equals(SearchOperation.NOT_EQUAL)) {
                predicates.add(builder.notEqual(root.get(criteria.getKey()), criteria.getValue1()));
            } else if (criteria.getOperation().equals(SearchOperation.GREATER_THAN)) {
                predicates.add(builder.greaterThan(root.get(criteria.getKey()), criteria.getValue1().toString()));
            } else if (criteria.getOperation().equals(SearchOperation.LESS_THAN)) {
                predicates.add(builder.lessThan(root.get(criteria.getKey()), criteria.getValue1().toString()));
            } else if (criteria.getOperation().equals(SearchOperation.GREATER_THAN_EQUAL)) {
                predicates.add(builder.greaterThanOrEqualTo(root.get(criteria.getKey()), criteria.getValue1().toString()));
            } else if (criteria.getOperation().equals(SearchOperation.LESS_THAN_EQUAL)) {
                predicates.add(builder.lessThanOrEqualTo(root.get(criteria.getKey()), criteria.getValue1().toString()));
            } else if (criteria.getOperation().equals(SearchOperation.IN)) {
                predicates.add(builder.in(root.get(criteria.getKey())).value(criteria.getValue1()));
            } else if (criteria.getOperation().equals(SearchOperation.NOT_IN)) {
                predicates.add(builder.not(root.get(criteria.getKey())).in(criteria.getValue1()));
            }
        }
        return builder.and(predicates.toArray(new Predicate[0]));
    }
}
</code></pre>

<p><strong>Question :</strong>
- how to create unit test for this class with junit 5?
- Note : my project using spring-boot</p>
",https://stackoverflow.com/questions/62038568/unit-testing-dynamic-query-jpa-specification-on-spring-boot,"['java', 'spring-boot', 'spring-data-jpa']",447,False,1,0
Unit testing an @ObservableObject in Swift Test Driven Development,"<p>I'm trying to learn how to use MVVM architecture with TDD to solve some of the problems with not being able to unit test Views in SwiftUI.</p>

<p>I have an Alarm struct which takes a date:</p>

<pre><code>import Foundation

struct Alarm {
    var time: Date
}
</code></pre>

<p>And I have a basic </p>

<pre><code>class AlarmPickerViewModel: ObservableObject {
    @Published var alarm: Alarm

    init(alarm: Alarm) {
        self.alarm = alarm
    }

}
</code></pre>

<p>I'm struggling to work out how to write a unit test that fails if the <code>AlarmPickerViewModel</code> isn't a subclass of <code>ObservableObject</code> and the alarm property isn't <code>@Published</code>.</p>

<p>I've looked at <a href=""https://stackoverflow.com/questions/60467247/write-unit-tests-for-observableobject-viewmodels-with-published-results"">this question on the site</a> but it doesn't seem to help me.</p>

<p>Any pointers on where I'm going wrong please?</p>
",https://stackoverflow.com/questions/62154604/unit-testing-an-observableobject-in-swift-test-driven-development,"['swift', 'mvvm', 'tdd', 'observableobject']",1572,True,1,1
Unit testing MVC controller - need path to the application,"<p>I've inherited a legacy ASP.net MVC application and I'm trying to backfit unit test and running into an error.  Here's my unit test:</p>

<pre><code>public void DashboardController_Index_ReturnsIndex()
     {
         var dashboardController = _mocker.Resolve&lt;DashboardController&gt;();
         var controllerContextMock = new Mock&lt;ControllerContext&gt;();
         var userMock = new Mock&lt;IUserContext&gt;();

         userMock
             .SetupGet(u =&gt; u.Identity.IsAuthenticated)
             .Returns(true);
         userMock
             .Setup(u =&gt; u.Type)
             .Returns(EUserType.Normal);
         controllerContextMock
             .SetupGet(c =&gt; c.HttpContext.User)
             .Returns(userMock.Object);
         controllerContextMock
             .SetupGet(p =&gt; p.HttpContext.Request.Url)
             .Returns(new Uri(""http://localhost/Dashboard/Index""));

         dashboardController.ControllerContext = controllerContextMock.Object;

         var result = dashboardController.Index() as ViewResult;

         Assert.Equal(""Index"", result.ViewName);
     }
</code></pre>

<p>When the Index action is called, it calls a static method in another class that returns a string expression used for configuration purposes.  After that config string gets returned, another static method in another (referenced) static class (different namespace) gets called which attempts to parse that string expression but throws an exception.  Here's that method:</p>

<pre><code>private static string GetResourceString(HttpContextBase httpContext, string sxExpression, string sxVirtualPath)
        {
            var context = new ExpressionBuilderContext(sxVirtualPath);
            var builder = new ResourceExpressionBuilder();
            var fields = (ResourceExpressionFields)builder.ParseExpression(sxExpression, 
                typeof(string), context);

            if (string.IsNullOrEmpty(fields.ClassKey) == false)
                return (string)httpContext.GetGlobalResourceObject(fields.ClassKey, fields.ResourceKey, 
                    Thread.CurrentThread.CurrentCulture);
            return (string)httpContext.GetLocalResourceObject(sxVirtualPath, fields.ResourceKey, 
                Thread.CurrentThread.CurrentCulture);
        }
</code></pre>

<p>The exception occurs in the third line of this method where the code attempts to break the string into fields.  Specifically, here's the exception:</p>

<blockquote>
  <p>System.Web.HttpException (0x80004005): The application relative virtual path '~/' cannot be made absolute, because the path to the application is not known.</p>
</blockquote>

<p>I've seen <a href=""https://stackoverflow.com/questions/6428372/how-to-mock-application-path-when-unit-testing-web-app/6528979"">this post</a> that describes how to inject a fake into this call but since the Controller itself isn't trying to parse the string, but rather handing it off to a helper method in another class, it seems that DI won't work.  Any idea how I can fake the application path while unit testing?  In production, this code works just fine.  I'm thinking I can refactor the controller to use this helper class as a dependency instead of just calling static methods but I'm hoping for a solution that doesn't require code changes to production code.</p>
",https://stackoverflow.com/questions/60292193/unit-testing-mvc-controller-need-path-to-the-application,"['c#', 'asp.net-mvc', 'unit-testing']",134,True,1,1
Unit testing of custom Assert function using Google Test,"<p>I am using Boost.Assert library, and have this custom assert code, which needs to be unit tested using Google Test framework:</p>
<pre class=""lang-cpp prettyprint-override""><code>    #include &lt;boost/assert.hpp&gt;
    #define ASSERT(expr)                BOOST_ASSERT(expr)
    #define ASSERT_MSG(expr, msg)       BOOST_ASSERT_MSG(expr, msg)

    namespace boost {
        inline void assertion_failed_msg(char const* expr, char const* msg, char const* function, char const* /*file*/, long /*line*/) {
            std::cerr &lt;&lt; &quot;Expression '&quot; &lt;&lt; expr &lt;&lt; &quot;' is false in function '&quot; &lt;&lt; function &lt;&lt; &quot;': &quot; &lt;&lt; (msg ? msg : &quot;&lt;...&gt;&quot;) &lt;&lt; &quot;.\n&quot;
                &lt;&lt; &quot;Backtrace:\n&quot; &lt;&lt; boost::stacktrace::stacktrace() &lt;&lt; std::endl;

            std::abort();
        }

        inline void assertion_failed(char const* expr, char const* function, char const* file, long line) {
            ::boost::assertion_failed_msg(expr, 0 /*nullptr*/, function, file, line);
        }
    } // namespace boost
</code></pre>
<p>The idea is to check that <code>ASSERT( 1!=1 )</code> terminates the program with the appropriate error code and error log message.</p>
<p>I am aware of Google Test, Death Tests. I have the following structure, which kind of works for me:</p>
<pre class=""lang-cpp prettyprint-override""><code>void assert_death_test() 
{
    ASSERT( 1!=1 );
}

TEST(unit_test_DeathTest, test_of_assert_function) {
    EXPECT_EXIT(assert_death_test(), ::testing::KilledBySignal(SIGABRT), &quot;Stuff hit the fan.&quot;);
}
</code></pre>
<p>Since I'm using a death test, <code>ASSERT(...)</code> does not terminate unit testing, and death test notices that the program exits with some log message. The problem is this:</p>
<pre><code>Death test: assert_death_test()
    Result: died but not with expected error.
  Expected: contains regular expression &quot;Stuff hit the fan.&quot;
Actual msg:
[  DEATH   ] Expression '1!=1' is false in function 'void assert_death_test()': &lt;...&gt;.
[  DEATH   ] Backtrace:
[  DEATH   ]  0# boost::assertion_failed_msg(char const*, char const*, char const*, char const*, long) in ./executable
[  DEATH   ]  1# boost::assertion_failed(char const*, char const*, char const*, long) in ./executable
[  DEATH   ]  2# assert_death_test() in ./executable
[  DEATH   ]  3# unit_test_DeathTest_test_of_assert_function_Test::TestBody() in ./executable
.
. // Continues with more log messages
.
</code></pre>
<p>Because of this problem, the test is counted as a fail, whereas it normally is a success. (The assert kills program, and sends a log message to stdout)</p>
<p>How can I solve this problem? (Alternative methods are also applicable)</p>
<p>Is there a way to force the output of a test to be successful?</p>
",https://stackoverflow.com/questions/62533438/unit-testing-of-custom-assert-function-using-google-test,"['c++', 'unit-testing', 'boost', 'googletest']",609,True,1,2
How to do the unit testing on stm32 programming,"<p>I have STM 32 nucleo board .I have done a program for an embedded functionality. Currently I want to do the unit testing for the functionalities including the peripherals like ADC,SPI,UART..Can anyone suggest the Unit testing framework to test the functionality for the same.</p>
",https://stackoverflow.com/questions/61136966/how-to-do-the-unit-testing-on-stm32-programming,['stm32'],6715,True,1,2
Unit testing with Laravel assertDatabaseHas and a float column,"<p>Doing some tests on my Laravel app and am running into intermittent failures due to one of my database columns being defined as a <code>FLOAT</code>. When running a test with <a href=""https://laravel.com/docs/5.8/database-testing#available-assertions"" rel=""nofollow noreferrer""><code>assertDatabaseHas()</code></a> it sometimes fails due to floating point uncertainty.</p>

<pre><code>&lt;?php

namespace Test\Unit;

use App\Foo;

class MyModelTest extends TestCase
{
    public function testFooCanBar(): void
    {
        $stringvalue = ""baz"";
        $floatvalue = 234.281;
        $data = [
            ""name"" =&gt; $stringvalue,
            ""data"" =&gt; $floatvalue,
        ];
        Foo::bar($stringvalue, $floatvalue);
        $this-&gt;assertDatabaseHas(""foos"", $data);
    }
}
</code></pre>

<p>Sometimes result:</p>

<pre class=""lang-none prettyprint-override""><code>Failed asserting that a row in the table [foos] matches the attributes {
    ""name"": ""baz"",
    ""data"": 234.281
}.

Found similar results: [
    {
        ""name"": ""baz"",
        ""data"": 234.280999999999999995
    }
]
</code></pre>

<p>I can think of a few ways to work around this (change the column to an <code>INT</code> and multiply by 10^x, or just remove the column from the comparison) but I'm wondering if there are any methods I missed to properly check this. When comparing values directly we can use PHPUnit's <a href=""https://phpunit.readthedocs.io/en/8.5/assertions.html#assertequalswithdelta"" rel=""nofollow noreferrer""><code>assertEqualsWithDelta()</code></a>; is there anything similar for a database check?</p>
",https://stackoverflow.com/questions/60066437/unit-testing-with-laravel-assertdatabasehas-and-a-float-column,"['php', 'laravel', 'unit-testing', 'floating-point', 'phpunit']",1693,True,1,1
Component Unit Testing in Ionic 3 using Jasmine-Karma,"<p>I am trying to test a page in Ionic 3. So, I created .spec.ts of that page manually within src/pages/page folder. But when I create component using TestBed.createComponent, then it shows following error :</p>

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

<blockquote>
  <p>about.spec.ts file</p>
</blockquote>

<pre><code>    import { CUSTOM_ELEMENTS_SCHEMA } from ""@angular/core"";
import { TestBed, ComponentFixture, async } from ""@angular/core/testing"";
import { AboutPage } from './about';
import { IonicPageModule, NavController, NavParams, Platform } from 'ionic-angular';
import { BrowserDynamicTestingModule,platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';

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

    let fixture;
    let component;
    beforeEach(async(() =&gt; {
        TestBed.resetTestEnvironment();
        TestBed.initTestEnvironment(BrowserDynamicTestingModule,platformBrowserDynamicTesting());
      TestBed.configureTestingModule({
        declarations: [ AboutPage ],
        imports: [IonicPageModule.forChild(AboutPage)],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [NavController, NavParams, Platform]
      }).compileComponents().then((response) =&gt; {
          fixture = TestBed.createComponent(AboutPage);
          component = fixture.componentInstance;
          fixture.detectChanges();
      });
    }));

    afterEach(() =&gt; {
      fixture.destroy();
      component = null;
    });

     describe('First test',() =&gt; {
        it('should print',() =&gt; {
            let a = true;
            expect(a).toBeTruthy();
        })
    })
});
</code></pre>

<p>I am unable to find out where my code is lacking due to which this error is coming. I need to fetch component in my spec file so as to perform testing on its functions and its part.
     Please suggest where I may be doing wrong. </p>

<blockquote>
  <p><strong>AS SUGGESTED (Edition-1) :</strong></p>
</blockquote>

<p>I changed my about.spec.ts by removing afterEach and refactoring beforeEach code into 2 parts :</p>

<pre><code>import { CUSTOM_ELEMENTS_SCHEMA ,NO_ERRORS_SCHEMA} from ""@angular/core"";
import { TestBed, ComponentFixture, async } from ""@angular/core/testing"";
import { AboutPage } from './about';
import { IonicPageModule, NavController, NavParams, Platform } from 'ionic-angular';
import { BrowserDynamicTestingModule,platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';

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

    let fixture;
    let component;

    beforeEach(async(() =&gt; {
        TestBed.initTestEnvironment(BrowserDynamicTestingModule,platformBrowserDynamicTesting());
        TestBed.configureTestingModule({
            declarations: [ AboutPage ],
            imports: [IonicPageModule.forChild(AboutPage)],
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
            providers: [NavController, NavParams, Platform]
        }).compileComponents();
    }));

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

    it('should print',() =&gt; {
        let a = true;
        expect(a).toBeTruthy();
    });
});
</code></pre>

<p>But again I am getting same type of error, not that of destroy one.</p>

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

<p>Please suggest.</p>
",https://stackoverflow.com/questions/60168397/component-unit-testing-in-ionic-3-using-jasmine-karma,"['angular', 'unit-testing', 'testing', 'ionic3', 'karma-jasmine']",281,False,1,1
"how to handle catch in sinon, unit testing nodejs","<p>in my UserService:</p>

<pre><code>createUser: async (data) =&gt; {
    const user = new UserDBEntryMapper(data);
    const createdUser = await UserModel.create(user).catch(error =&gt; {
      this.handleError(error);
    });
    return createdUser ? new UserBOMapper(createdUser) : null;
  }
</code></pre>

<p>in my user.test.js</p>

<pre><code>it.only('Create New User', async () =&gt; {
    const stub = sinon.stub(UserModel, ""create"").returns(user);
    const created = await UserService.createUser(user);
    expect(stub.calledOnce).to.be.true;
});
</code></pre>

<p>throwing the error as:</p>

<pre><code>Create New User:
TypeError: UserModel.create(...).catch is not a function
</code></pre>

<p>If I remove <code>catch</code> block in <code>UserService</code> the test passes, but we need a catch block there. How do I handle this?</p>

<p><strong>Note:</strong> <code>UserModel.create()</code> is <code>sequelize</code> default function</p>
",https://stackoverflow.com/questions/60597739/how-to-handle-catch-in-sinon-unit-testing-nodejs,"['node.js', 'unit-testing', 'sequelize.js', 'sinon-chai']",570,True,1,1
Angular unit testing - change component variable inside the test,"<p>I want to test the functionality of a button, but that element is not visible on the page because it's under an <code>*ngIf</code>. I would like to set the variable from <code>*ngIf</code> to be truthy in order to be able to display the data. I tried doing it with:</p>

<pre><code>beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HeaderComponent);
    component = fixture.componentInstance;
    component.currentUser = {firstName: 'xxx'} as User; // Changing currentUser so it won't be undefined anymore 
    fixture.detectChanges();
  });
</code></pre>

<p>but still doesn't work. Here is my component:</p>

<pre><code>&lt;div class=""menu-button-container""&gt;
    &lt;div class=""menu-button"" [ngClass]=""{'menu-open': isMenuOpen}"" (click)=""toggleMenu()"" *ngIf=""currentUser""&gt;
        &lt;div class=""line-menu-button line-menu-button__top""&gt;&lt;/div&gt;
        &lt;div class=""line-menu-button line-menu-button__middle""&gt;&lt;/div&gt;
        &lt;div class=""line-menu-button line-menu-button__bottom""&gt;&lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>and the test I try to run:</p>

<pre><code>it('should open the menu when the button menu is clicked', () =&gt; {
    const fixture = TestBed.createComponent(HeaderComponent);
    fixture.detectChanges();
    const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
    expect(menuDebugElement).toBeTruthy();
  });
</code></pre>

<p>this always fails. If I define the <code>*ngIf</code> rule as <code>*ngIf=""currentUser""</code>, the test is working. How can I do this variable change from the test? Please advise! Thanks!</p>
",https://stackoverflow.com/questions/61104838/angular-unit-testing-change-component-variable-inside-the-test,"['angular', 'unit-testing', 'karma-jasmine']",9841,True,1,2
How to trigger ngModelChange event in Jasmine unit testing?,"<p>I am using below code to perform unit testing by using Jasmine in Angular application.</p>
<p><strong>test.component.html:</strong></p>
<pre><code>&lt;p-treeTable [value]=&quot;employees&quot; [columns]=&quot;cols&quot; class=&quot;employeestreetable&quot;&gt;
    &lt;ng-template pTemplate=&quot;header&quot; let-columns&gt;
        &lt;tr&gt;
            &lt;th *ngFor=&quot;let col of cols&quot; style=&quot;width:30px&quot;&gt;
                {{col.header}}
            &lt;/th&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
    &lt;ng-template pTemplate=&quot;body&quot; let-rowNode let-rowData=&quot;rowData&quot;  let-columns=&quot;columns&quot;&gt;
        &lt;tr [ttRow]=&quot;rowNode&quot;&gt;
            &lt;td width=&quot;30&quot; class=&quot;text-right&quot; ttEditableColumn&gt; 
              &lt;p-treeTableToggler [rowNode]=&quot;rowNode&quot;&gt;
                    &lt;/p-treeTableToggler&gt;
                &lt;p-treeTableCellEditor&gt;
                    &lt;ng-template pTemplate=&quot;input&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['name']&quot; /&gt;
                    &lt;/ng-template&gt;
                    &lt;ng-template pTemplate=&quot;output&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['name']&quot;&gt;
                     &lt;/ng-template&gt;
                &lt;/p-treeTableCellEditor&gt;
             &lt;/td&gt; 
             &lt;td width=&quot;30&quot; class=&quot;text-right&quot;&gt;
                &lt;p-treeTableCellEditor&gt;
                    &lt;ng-template pTemplate=&quot;input&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['salary']&quot; (ngModelChange)=&quot;calculateTotalSalary(rowNode)&quot; /&gt;
                    &lt;/ng-template&gt;
                    &lt;ng-template pTemplate=&quot;output&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['salary']&quot;&gt;
                     &lt;/ng-template&gt;
                &lt;/p-treeTableCellEditor&gt;
             &lt;/td&gt;
             &lt;td width=&quot;30&quot; class=&quot;text-right&quot; ttEditableColumn&gt;
                &lt;p-treeTableCellEditor&gt;
                    &lt;ng-template pTemplate=&quot;input&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['incentive']&quot;  (ngModelChange)=&quot;calculateTotalSalary(rowNode)&quot; /&gt;
                    &lt;/ng-template&gt;
                    &lt;ng-template pTemplate=&quot;output&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['incentive']&quot;&gt;
                     &lt;/ng-template&gt;
                &lt;/p-treeTableCellEditor&gt;
             &lt;/td&gt;
             &lt;td width=&quot;30&quot; class=&quot;text-right&quot;&gt;
               &lt;span&gt;{{rowData['totalsalary']}}&lt;/span&gt;
              &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
&lt;/p-treeTable&gt; 
</code></pre>
<p><strong>test.component.ts:</strong></p>
<pre><code>import { Component, OnInit, ViewChild } from '@angular/core';
import { TreeNode } from 'primeng/primeng'
import { ChangeDetectorRef } from '@angular/core';
@Component({
  selector: 'test-app',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {
  cols = [
    { field: 'name', header: 'Name' },
    { field: 'salary', header: 'Salary' },
    { field: 'incentive', header: 'Incentive' },
    { field: 'totalsalary', header: 'Total Salary' }
  ];
  employees: TreeNode[] = [
    {
      &quot;data&quot;: {
        &quot;name&quot;: &quot;Alex&quot;,
        &quot;salary&quot;: 10000,
        &quot;incentive&quot;: 5000,
        &quot;totalsalary&quot;: 15000
      },
      &quot;children&quot;: [
        {
          &quot;data&quot;: {
            &quot;name&quot;: &quot;George&quot;,
            &quot;salary&quot;: 8000,
            &quot;incentive&quot;: 2000,
            &quot;totalsalary&quot;: 10000
          },
        }
      ]
    },
    {
      &quot;data&quot;: {
        &quot;name&quot;: &quot;Robert&quot;,
        &quot;salary&quot;: 18000,
        &quot;incentive&quot;: 10000,
        &quot;totalsalary&quot;: 280000
      },
      &quot;children&quot;: [
        {
          &quot;data&quot;: {
            &quot;name&quot;: &quot;John&quot;,
            &quot;salary&quot;: 7000,
            &quot;incentive&quot;: 5000,
            &quot;totalsalary&quot;: 12000
          }
        }
      ]
    }
  ];
  calculateTotalSalary(rownode) {
    rownode.node.data.totalsalary = +rownode.node.data.salary + +rownode.node.data.incentive;
  }
}
</code></pre>
<p><strong>test.component.spec.ts:</strong></p>
<pre><code>import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {
    TestComponent
} from &quot;./test.component&quot;;
import { FormsModule, NgModel } from '@angular/forms';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MessageService } from 'primeng/api';
import { TreeNode } from 'primeng/api';
import { TreeTableModule } from 'primeng/treetable';
import { By } from '@angular/platform-browser';
import { InputTextModule } from 'primeng/inputtext';
describe('TestComponent', () =&gt; {
  let component: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;;
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule,
      FormsModule, TreeTableModule, InputTextModule
      ],
      declarations: [ TestComponent ],
      providers: [ ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  beforeEach(fakeAsync(() =&gt; {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    tick();
  }));
  it('should update total salary amount', fakeAsync(() =&gt; {
    spyOn(component, 'calculateTotalSalary');
    const editableTreeTableEl = fixture.debugElement.query(By.css(&quot;.employeestreetable&quot;));
    let editableColumns = editableTreeTableEl.queryAll(By.css(&quot;.ui-editable-column input&quot;));
    const el = editableColumns[0].nativeElement;
    const ngModel = editableColumns[0].injector.get(NgModel);
    tick();
    ngModel.valueAccessor.writeValue(25000);
    el.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    expect(component.calculateTotalSalary).toHaveBeenCalled(); //failing here
    expect(+el.value).toEqual(25000);
  }));
});
</code></pre>
<p><strong>Demo:</strong>
<a href=""https://stackblitz.com/edit/test-jasmine-karma-t7khzp?file=app%2Ftest.component.html"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/test-jasmine-karma-t7khzp?file=app%2Ftest.component.html</a></p>
<p>I am updating salary amount in above unit test case. How to trigger related ngModelChange event when I update ngModel value from above unit test case?</p>
",https://stackoverflow.com/questions/63908650/how-to-trigger-ngmodelchange-event-in-jasmine-unit-testing,"['angular', 'jasmine', 'karma-jasmine', 'karma-runner']",4540,True,1,1
Angular: How to use router in angular unit testing,"<p>I'm writing a test case in angular. I have written a condition if <code>res.length === 1</code> redirect to the details page. (<code>this.router.navigate(['details', id])</code>). I'm getting the <code>id</code> from the first array of the object in body response as <code>const id = res[0].id</code>. These both line are not covered in my code coverage. Can anyone let me know where I made mistake?</p>

<p>I'm getting <code>Expected spy navigate to have been called with [ [ '/product-details', 'SAAASD0001' ] ] but it was never called.</code></p>

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

<pre><code>let router = {navigate: jasmine.createSpy('navigate')};
</code></pre>

<pre><code>TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  providers: [
    { provide: Router, useValue: router }
  ]
})
</code></pre>

<pre><code>it('should take data from store', () =&gt; {
  const mockData = [
      {
        id: '123',
        name: 'Stackoverlow',
      }
  ]
  expect(component.getList).toEqual(mockData);

  const productId = mockData[0].id;
  expect(router.navigate).toHaveBeenCalledWith(['/details', id]);
});
</code></pre>

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

<pre><code>  getList() {
    this.store
      .select('content', 'catalogue')
      .pipe(takeUntil(this.onDestroy$))
      .subscribe((res) =&gt; {
        Iif (res.length === 1) {
          // this line doesn't cover
          const id = res[0].id;
          // this line doesn't cover
          this.router.navigate(['details', id]);
        } else {
          this.list = category(res);
        }
      });
  }
</code></pre>
",https://stackoverflow.com/questions/61392210/angular-how-to-use-router-in-angular-unit-testing,"['javascript', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",353,True,1,2
Async callback timeout when unit testing nested async function,"<p>I want to implement a function which hits some apis asynchronously and does some calculations. However I would like to use promises (also because I thought its easy to write unit test for them)</p>

<p>This is the function I want to write.</p>

<pre><code>const CalcFactory = (someApi1, someApi2, someApi3) =&gt; 
 async function calculation(params){
  return new Promise((res, rej) =&gt;{
    const data1 = someApi1.getData() // getData is async
    someApi2.getData((err, data) =&gt;{
       if(err)
         rej(err);
       else
         res();
      });
    });
 }
</code></pre>

<p>The question now is how to test and mock this? My first test is if all the api methods are beeing called but I already struggle with that.</p>

<pre><code>const Calculator = CalcFactory(api1Mock, api2Mock, api3Mock);

if('should hit all external apis', () =&gt; {
return Calculator(somedada).then(()=&gt;{
   expect(api1Mock.getData).toHaveBeenCalledWith(someData);
   expect(api2Mock.getData).toHaveBeenCalledWith(somedata);
   });

});
</code></pre>

<p>the mocks look like this:</p>

<pre><code>const api1Mock = {
   someData: jest.fn(),
}

const api2Mock = {
someData: jest.fn().mockResolvedValue({
      data:{},
   })
}
</code></pre>

<p>However I always get a timeout when I run the test. I am also not really sure if this is a good approach to write the function but I really would like to use a promise.</p>
",https://stackoverflow.com/questions/62330615/async-callback-timeout-when-unit-testing-nested-async-function,"['javascript', 'unit-testing', 'jestjs']",415,True,1,1
Unit testing that component renders correctly - invalid hook call,"<p>I am working on a learning project to get familiar with React and Typescript. I have created a stopwatch component and I want to simply test that it renders without crashing, as I know it works fine in the browser.</p>
<p>The following code fails with an invalid hook call error message. &quot;Invalid hook call. Hooks can only be called inside of the body of a function component.&quot; I am unsure what the cause of this issue might be, I was thinking I am setting my test in a wrong way.</p>
<pre><code>import { shallow } from &quot;enzyme&quot;;
import { Stopwatch } from &quot;../../Components/Stopwatch&quot;;
import * as React from &quot;react&quot;;
import {
  onAddClick,
  isEnabled,
  setAddButtonEnabled,
} from &quot;../Fixtures/stopwatch&quot;;

test(&quot;renders without crashing&quot;, () =&gt; {
  const wrapper = shallow(&lt;Stopwatch /&gt;);
  expect(wrapper.html()).toMatchSnapshot();
});
</code></pre>
<p>The imports for <code>onAddClick</code>, <code>isEnabled</code> and <code>setAddButtonEnabled</code> are mock props I used to pass to the Stopwatch component, as I thought initially that this might fix the issue.</p>
",https://stackoverflow.com/questions/62484987/unit-testing-that-component-renders-correctly-invalid-hook-call,"['reactjs', 'typescript', 'unit-testing']",188,False,0,1
Error while angular unit testing with Jasmine and Karma,"<p>I have already imported the angular material in my spec.ts but I am getting the below error when trying to run the test that is ng test of this particular component:</p>

<p>Error: Template parse errors:</p>

<p>'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""</p>

<p>[ERROR ->]
                          
                      ][dataSource]=""parts"" matSort  class=""mat-elevation-z8"">
                    
                ""): ng:///DynamicTestModule/PartViewComponent.html@6:23
                The pipe 'uuidAbbrev' could not be found (""eader-cell *matHeaderCellDef mat-sort-header>Uuid
                       {{[ERROR ->]row.uuid|uuidAbbrev}}
                    
                ""): ng:///DynamicTestModule/PartViewComponent.html@10:44
                Can't bind to 'matHeaderRowDef' since it isn't a known property of 'tr'. (""
                    
                    ]<em>matHeaderRowDef=""displayedProps"">
                    
                    [ERROR ->]
                    
                    ]*matRowDef=""let row; columns: displayedProps;"">
                  
                
                ""): ng:///DynamicTestModule/PartViewComponent.html@24:35
                Property binding matRowDefColumns 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 ->]
                  
                http://localhost:9876/_karma_webpack_/vendor.js:36418:17)
                    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (<a href=""http://localhost:9876/_karma_webpack_/vendor.js:54593:19"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:54593:19</a>)
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (<a href=""http://localhost:9876/_karma_webpack_/vendor.js:60159:37"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:60159:37</a>)
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (<a href=""http://localhost:9876/_karma_webpack_/vendor.js:60146:23"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:60146:23</a>)
                    at <a href=""http://localhost:9876/_karma_webpack_/vendor.js:60089:62"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:60089:62</a>
                    at Set.forEach ()
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (<a href=""http://localhost:9876/_karma_webpack_/vendor.js:60089:19"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:60089:19</a>)
                    at <a href=""http://localhost:9876/_karma_webpack_/vendor.js:60007:19"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:60007:19</a>
                    at Object.then (<a href=""http://localhost:9876/_karma_webpack_/vendor.js:36409:77"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:36409:77</a>)
                    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndAllComponents (<a href=""http://localhost:9876/_karma_webpack_/vendor.js:60005:26"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js:60005:26</a>)</em>
            ```</p>
",https://stackoverflow.com/questions/60228377/error-while-angular-unit-testing-with-jasmine-and-karma,"['angular', 'unit-testing', 'karma-jasmine']",3846,False,0,1
Error while performing angular Unit testing with SpyOn document,"<p>I am trying to do the unit testing for component, I mocked the data and expecting some result but getting an error, below is my unit test.</p>

<pre><code>it('should call getData method ', () =&gt; {
    const usageService = TestBed.get(UsageService);
    component.slug = 'slugName';
    spyOn(document, 'getElementById').and.returnValue(""slugName"");
    component.ngOnInit();
    expect(usageService.getData).toHaveBeenCalled();
    });
</code></pre>

<p>In above I am getting an error at line <code>spyOn(document, 'getElementById').and.returnValue(""slugName"");</code></p>

<p>Error is: </p>

<blockquote>
  <p>Argument of type ""slugName"" is not assignable to parameter of type
  'HTMLElement'.</p>
</blockquote>

<p>This issue comes after upgrading jasmine version from <strong>2.8</strong> to <strong>3.5.10</strong></p>

<p>I don't know what's wrong in this code, why previously it was working fine and now after upgrading it won't work.</p>

<p>please help me to resolve the issue.</p>
",https://stackoverflow.com/questions/61954745/error-while-performing-angular-unit-testing-with-spyon-document,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-mocha']",645,True,0,2
For unit testing how to make a namespace derived?,"<p>I have two namespaces:</p>
<pre><code>namespace MyNamespace
</code></pre>
<p>and</p>
<pre><code>namespace MyNamespace.Test
</code></pre>
<p>the second one is for Unit Testing. I don't want to make the classes within &quot;MyNamespace&quot; public but I want the unit tests to be able to access them. I tried internal because from the <a href=""https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers"" rel=""nofollow noreferrer"">Access Modifier documentation</a> I had assumed that &quot;MyNamespace.test&quot; would be derived but it's not working. Do I use a different access modifier or is my namespace wrong?</p>
",https://stackoverflow.com/questions/63075668/for-unit-testing-how-to-make-a-namespace-derived,"['c#', 'namespaces', 'access-modifiers']",572,True,0,1
Unit testing Spring REST API Service (Update (PUT Method)),"<p>I'm trying to unit test a service for my controller in my API but i'm getting the following 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-css lang-css prettyprint-override""><code>2020-05-20 15:23:51.493  WARN 25469 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity&lt;com.tropicalia.meu_cardapio.domain.user.User&gt; com.tropicalia.meu_cardapio.api.user.update.UserUpdateRest.update(com.tropicalia.meu_cardapio.domain.user.User,java.lang.Long)]

MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /users/89
       Parameters = {}
          Headers = [Content-Type:""application/json""]
             Body = &lt;no character encoding set&gt;
    Session Attrs = {}

Handler:
             Type = com.tropicalia.meu_cardapio.api.user.update.UserUpdateRest
           Method = com.tropicalia.meu_cardapio.api.user.update.UserUpdateRest#update(User, Long)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:""Origin"", ""Access-Control-Request-Method"", ""Access-Control-Request-Headers""]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :202
Actual   :400</code></pre>
</div>
</div>
</p>

<p>This is my test class :</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-css lang-css prettyprint-override""><code>@RunWith(SpringRunner.class)
@WebMvcTest(UserUpdateRest.class)
public class UpdateUserTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private UserUpdateService service;

    @Test
    public void updateUser_whenPutUser() throws Exception {

        User user = new User();
        user.setName(""Test Name"");
        user.setId(89L);

        given(service.updateUser(user.getId(), user)).willReturn(user);

        mvc.perform(put(""/users/"" + user.getId().toString())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isAccepted())
                .andExpect(jsonPath(""name"", is(user.getName())));
    }
}</code></pre>
</div>
</div>
</p>

<p>And this is my 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-css lang-css prettyprint-override""><code>@Service
public class UserUpdateService {

    @Autowired
    UserRepository repository;

    public User updateUser(Long id, User user) {
        repository
                .findById(id)
                .orElseThrow(() -&gt; new EntityNotFoundException(""User not found.""));
        return repository.save(user);
    }
}</code></pre>
</div>
</div>
</p>

<p>Would really appreciate if someone could help me with this one.</p>

<p>From what i understand, there's something wrong with the request body but i have no idea what to do to fix it.</p>
",https://stackoverflow.com/questions/61922613/unit-testing-spring-rest-api-service-update-put-method,"['java', 'spring', 'api', 'unit-testing', 'http']",2321,True,0,1
Apache Camel: Unit testing for file and http components,"<p>I am fairly new to Camel &amp; just managed to implement a use case as below with 2 routes which is using file &amp; http components. Looking for some leads on writing junits for the same. Have tried some sample test case below based on the inputs that i found on the net. Not sure if that suffices. Appreciate your help!</p>
<ul>
<li><p>Implementation:</p>
<pre><code> @Override
 public void configure() throws Exception {
     // Global Exception Handling block
     onException(FileWatcherException.class).process(new Processor() {
         public void process(Exchange exchange) throws Exception {
             System.out.println(&quot;Exception handled&quot;);
         }
     }).to(&quot;file:C:/error?recursive=true&quot;).handled(true);

     // Actively listen to the input folder for an incoming file
     from(&quot;file:C:/input?noop=true&amp;recursive=true&amp;delete=true&quot;)
         .process(new Processor() {
             public void process(Exchange exchange) throws Exception {
                 String fileName = exchange.getIn().getHeader(&quot;CamelFileName&quot;).toString();
                 exchange.getIn().setHeader(&quot;fileName&quot;, fileName);
             }
         })
         // Call the Get endpoint with fileName as input parameter
         .setHeader(Exchange.HTTP_METHOD, simple(&quot;GET&quot;))
         .toD(&quot;http://localhost:8090/fileWatcher?fileName=${header.fileName}&quot;)
         .choice()
             // if the API returns true, move the file to the outbox folder 
             .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(constant(200)))
                 .to(&quot;file:C:/outbox?noop=true&amp;recursive=true&quot;)
                 .endChoice()
             // If the API's response code is other than 200, move the file to error folder
             .otherwise()
                 .log(&quot;Moving the file to error folder&quot;)
                 .to(&quot;file:C:/error?recursive=true&quot;)
                 .end();

     // Listen to the outbox folder for file arrival after it gets moved in the above step
     from(&quot;file:C:/outbox?noop=true&amp;recursive=true&quot;)
         // Request Body for POST call is set in FileDetailsProcessor class
         .process(new FileDetailsProcessor())
         .marshal(jsonDataFormat)
         .setHeader(Exchange.HTTP_METHOD, simple(&quot;POST&quot;))
         .setHeader(Exchange.CONTENT_TYPE, constant(&quot;application/json&quot;))
         // Call the Rest endpoint with fileName &amp; filePath as RequestBody
         .to(&quot;http://localhost:8090/fileWatcher&quot;)
         .process(new MyProcessor())
         .end();
 }
</code></pre>
</li>
<li><p>Junit</p>
<pre><code>  @Test
      public void checkFileWatcherFunctionality() throws Exception {
      context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
          @Override
          public void configure() throws Exception {
              // mocking all endpoints. **QUESTION** - Is this required?
              mockEndpointsAndSkip(&quot;http://localhost:8090:fileWatcher?fileName=loan.csv&quot;);
              mockEndpointsAndSkip(&quot;file:C:/processing&quot;);
              mockEndpointsAndSkip(&quot;file:C:/error&quot;);
              mockEndpointsAndSkip(&quot;http://localhost:8090:fileWatcher&quot;);
          }
      });
      context.start();

      // **QUESTION** - This is a GET call. Expecting only the HTTP status code from it. How to check that?
      getMockEndpoint(&quot;mock:http://localhost:8090:fileWatcher?fileName=abc.txt&quot;).expectedBodyReceived();
      // **QUESTION** - This is a POST call. How to send request body along? Expecting only the HTTP status code from it. How to check that?
      getMockEndpoint(&quot;mock:http://localhost:8090:fileWatcher&quot;).expectedBodyReceived();
      // **QUESTION** - Is this the right way to check?
      getMockEndpoint(&quot;mock:file:C:/processing&quot;).expectedFileExists(&quot;loan.csv&quot;);;

      template.sendBodyAndHeader(&quot;file:C:/inbound&quot;, &quot;&quot;, Exchange.FILE_NAME, &quot;loan.csv&quot;);
      // QUESTION - What can be asserted now?
</code></pre>
<p>}</p>
</li>
</ul>
<p>Also - How to write test cases for negative flow (exception scenario)? Looking for suggestions.</p>
",https://stackoverflow.com/questions/65263226/apache-camel-unit-testing-for-file-and-http-components,"['junit', 'apache-camel', 'dsl', 'camel-http']",572,False,0,1
"Unit testing with PowerMock, precision problem when comparing seconds","<p>I'm trying to unit test a time function using powermock, but I'm sometimes having trouble getting through the assertEquals() when comparing the current time with system clock. The expected time is 2 seconds off. Here is my code for reference:</p>
<pre><code>@RunWith(PowerMock Runner.class)
@PrepareForTest({Calendar.class, time.class})
public class TEST {

    @Test
    public void testTime() {
        PowerMockito.mockStatic(Calendar.class);
        Mockito.when(Calendar.getInstance()).thenReturn(calendarInstance);
        SimpleDateFormat sdf = new SimpleDateFormat(DD_DOT_MM_DOT_YYY);
        assertEquals(sdf.format(calendarInstance.getTime()), time.getDate(DD_DOT_MM_DOT_YYYY)); }
    }
    
//inside the time.getDate function
    
public static String getDate(String format) {
    DateFormat dateFormat = new SimpleDateFormat(format);
    Date date = new Date();
    return dateFormat.format(date);
}
</code></pre>
<p>And here's the Junit output I sometimes get which indicates the failure:</p>
<pre><code>org.junit.ComparisonFailure:
Expected :20:43:18
Actual :20:43:20
</code></pre>
<p>I have tried a few ways to get around this, but I couldn't get it working reliably. Thank you for your help in advance.</p>
",https://stackoverflow.com/questions/64727990/unit-testing-with-powermock-precision-problem-when-comparing-seconds,"['java', 'unit-testing', 'junit', 'powermock', 'powermockito']",64,True,0,1
Unit testing of base class with jasmine and angular,"<p>I have one generic base class that I uses in each grid component. </p>

<p>Now, I have specs for grid component but I want to add specs for base class in separate base spec file. </p>

<p>Motive behind that is to remove repetitive code and make generic spec file for base grid which will be served for each grid that used base class.</p>

<p>I stuck at one point, <strong>I am not able to create a specs inside base spec file. Basically I want all the specs in base file under one function, and when this function called from sub class with that component, it should return all the specs for that class.</strong></p>

<blockquote>
  <p>Here is what I have and what I tried so far. </p>
</blockquote>

<p><strong>Component Layer:</strong></p>

<pre><code>export class MyComponent extends BaseGrid&lt;MyEntity&gt; { 
    ... (and all other code like constructor and methods)... 
}
</code></pre>

<p><strong>Base Layer:</strong></p>

<pre><code>export class BaseGrid&lt;T&gt; { 
    public async getData(): Promise&lt;void&gt; { ... }
}

... and 100 other functions
</code></pre>

<p><strong>Component specs:</strong></p>

<pre><code>describe('MyComponent ', () =&gt; {
    let component: MyComponent;
    let fixture: ComponentFixture&lt;MyComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            imports: [
                ...
        ],
            providers: [
            ],
        }).compileComponents().then(() =&gt; {
            fixture = TestBed.createComponent(MyComponent);
            component = fixture.componentInstance;
        });
    }));

    // here I created a reference function for my base class spec
    // Now, This is working but I don't want this **describe** and **it** to be here, 
    // it should be in the base file. so I can remove this repetitive code from all components.
    // And From here I just want to call one function let's say a **baseGridSpecs(component)**, 
    // that will load all the specs of base class in this component.
    describe('Should initialize Base grid', () =&gt; {
        it('should have proper component.', () =&gt; {
            const baseGridSpecs = new BaseGridSpecs&lt;MyComponent&gt;();
            baseGridSpecs.runBaseGridTests(component);
            baseGridSpecs.checkGetDataDefined(component);
        });
    });
});
</code></pre>

<p><strong>Base specs:</strong></p>

<pre><code>export class BaseGridSpecs&lt;T&gt; {
  runBaseGridTests(component: any): void {
    expect(component).toBeTruthy();
  }

  checkGetDataDefined(component: any): void {
     expect(component.getData).toBeDefined();
  }
}
</code></pre>

<p><strong>This structure works fine for me,</strong> but it has no use since my <code>describe</code> and <code>it</code> is still in main component spec file.</p>

<blockquote>
  <p>What I am trying to achieve is to just call the base spec function like <code>baseGridSpecs.runBaseGridTests(component);</code> and it should render all <code>describe</code> and <code>it</code> specs for given generic component. </p>
</blockquote>

<p><strong>Any help would be really appreciated...</strong></p>
",https://stackoverflow.com/questions/61129906/unit-testing-of-base-class-with-jasmine-and-angular,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-runner']",3789,True,0,2
Can&#39;t pass unit testing for a simple math question,"<p>This is the code I scraped together and when unit testing it, I receive two errors shown below. The code works fine otherwise. How can I edit it to pass the test? I would greatly appreciate your help.</p>
<p>Also, if you know any resources which would help me learn to do it myself next time, please feel free to suggest one. Thank you very much in advance.</p>
<pre><code>import numpy as np


def calculate(arr):
    if len(arr) != 9:
        raise ValueError('List must contain nine numbers.')
    else:
        arr = np.array(arr)
        new_arr = arr.reshape((3, 3))
        mean = {'mean': [np.mean(new_arr, 0).tolist(), np.mean(new_arr, 1).tolist(), np.mean(arr).tolist()]}
        variance = {'variance': [np.var(new_arr, 0).tolist(), np.var(new_arr, 1).tolist(), np.var(arr).tolist()]}
        standard_deviation = {
            'standard deviation': [np.std(new_arr, 0).tolist(), np.std(new_arr, 1).tolist(), np.std(arr).tolist()]}
        maxi = {'max': [np.max(new_arr, 0).tolist(), np.max(new_arr, 1).tolist(), np.max(arr).tolist()]}
        mini = {'min': [np.min(new_arr, 0).tolist(), np.min(new_arr, 1).tolist(), np.min(arr).tolist()]}
        summ = {'sum': [np.sum(new_arr, 0).tolist(), np.sum(new_arr, 1).tolist(), np.sum(arr).tolist()]}
        return print(mean), print(variance), print(standard_deviation), print(maxi), print(mini), print(summ)


calculate([0, 1, 2, 3, 4, 5, 6, 7, 8])

</code></pre>
<h2>ERROR: test_calculate (test_module.UnitTests)</h2>
<p>Traceback (most recent call last):</p>
<p>File &quot;/home/runner/RectangularConsiderateInverse/test_module.py&quot;, line 10, in test_calculate
self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[2,6,2,8,4,0,1,5,7]'&quot;)</p>
<p>File &quot;/usr/lib/python3.8/unittest/case.py&quot;, line 943, in assertAlmostEqual
diff = abs(first - second)
TypeError: unsupported operand type(s) for -: 'tuple' and 'dict'</p>
<h2>ERROR: test_calculate2 (test_module.UnitTests)</h2>
<p>Traceback (most recent call last):</p>
<p>File &quot;/home/runner/RectangularConsiderateInverse/test_module.py&quot;, line 15, in test_calculate2
self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[9,1,5,3,3,3,2,9,0]'&quot;)</p>
<p>File &quot;/usr/lib/python3.8/unittest/case.py&quot;, line 943, in assertAlmostEqual
diff = abs(first - second)
TypeError: unsupported operand type(s) for -: 'tuple' and 'dict'</p>
<p><strong>The unit testing code:</strong></p>
<pre><code>import unittest
import mean_var_std


# the test case
class UnitTests(unittest.TestCase):
    def test_calculate(self):
        actual = mean_var_std.calculate([2,6,2,8,4,0,1,5,7])
        expected = {'mean': [[3.6666666666666665, 5.0, 3.0], [3.3333333333333335, 4.0, 4.333333333333333], 3.888888888888889], 'variance': [[9.555555555555557, 0.6666666666666666, 8.666666666666666], [3.555555555555556, 10.666666666666666, 6.222222222222221], 6.987654320987654], 'standard deviation': [[3.091206165165235, 0.816496580927726, 2.943920288775949], [1.8856180831641267, 3.265986323710904, 2.494438257849294], 2.6434171674156266], 'max': [[8, 6, 7], [6, 8, 7], 8], 'min': [[1, 4, 0], [2, 0, 1], 0], 'sum': [[11, 15, 9], [10, 12, 13], 35]}
        self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[2,6,2,8,4,0,1,5,7]'&quot;)

    def test_calculate2(self):
        actual = mean_var_std.calculate([9,1,5,3,3,3,2,9,0])
        expected = {'mean': [[4.666666666666667, 4.333333333333333, 2.6666666666666665], [5.0, 3.0, 3.6666666666666665], 3.888888888888889], 'variance': [[9.555555555555555, 11.555555555555557, 4.222222222222222], [10.666666666666666, 0.0, 14.888888888888891], 9.209876543209875], 'standard deviation': [[3.0912061651652345, 3.39934634239519, 2.0548046676563256], [3.265986323710904, 0.0, 3.8586123009300755], 3.0347778408328137], 'max': [[9, 9, 5], [9, 3, 9], 9], 'min': [[2, 1, 0], [1, 3, 0], 0], 'sum': [[14, 13, 8], [15, 9, 11], 35]}
        self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[9,1,5,3,3,3,2,9,0]'&quot;)
    
    def test_calculate_with_few_digits(self):
        self.assertRaisesRegex(ValueError, &quot;List must contain nine numbers.&quot;, mean_var_std.calculate, [2,6,2,8,4,0,1,])

if __name__ == &quot;__main__&quot;:
    unittest.main() ```
</code></pre>
",https://stackoverflow.com/questions/64427356/cant-pass-unit-testing-for-a-simple-math-question,"['python', 'numpy', 'unit-testing']",206,True,-1,1
Prevent a method to be executed during Unit testing,"<p>I am trying to test a class called ""PuntuadorJuego""(GameScore) which has a method “PuntuarXAcertar”(PointsIfMatching) that call a private method “Actualiza”(Update) that basically Updates the score on the Unity's interface as you can see in the code bellow, the problem is that every time I run the test it stops there. I have tried commented the line that call the method and it works but I wonder if there is any other way to prevent the method ""Actualiza"" to be called during testing or even better if there is a way to ignore code related to the interface while testing. Thanks.</p>

<pre><code>[Testing class]
 public class PuntuadorTest
    {
        [Test]
        public void TestPuntuacionAcertar()
        {
            //Assign
            PuntuadorJuego puntuador = new PuntuadorJuego(puntuacion: 50);

            //Act
            puntuador.PuntuarXAcertar(esTurnoJ1: true);

            //Assert
            Assert.AreEqual(expected: 60, actual: puntuador.GetPuntuacionJ1());
        }
    }


[Method called by the tested Method]
private void Actualiza(int cantidad, bool esTurnoJ1)
    {
        if (esTurnoJ1)
        {
            if (puntuacionJ1 &lt; 0)
            {
                ValorPuntuacionText.color = Color.red;
            }
            else
            {
                ValorPuntuacionText.color = Color.white; //THIS is the error line
            }
            ValorPuntuacionText.text = puntuacionJ1 + """";
        }
        else
        {
            if (puntuacionJ2 &lt; 0)
            {
                ValorPuntuacionJ2Text.color = Color.red;
            }
            else
            {
                ValorPuntuacionJ2Text.color = Color.white;
            }
            ValorPuntuacionJ2Text.text = puntuacionJ2 + """";
        }

        if (cantidad &lt; 0)
        {
            burbujaPuntuacion.color = Color.red;
        }
        else 
        {
            burbujaPuntuacion.color = Color.green;
        }
        burbujaPuntuacion.text = cantidad + """";
        burbujaAnimacion.Play(""Puntua"");


    }


[Tested Method]
    public void PuntuarXAcertar(bool esTurnoJ1 = true) 
    {
        if (esTurnoJ1)
        {
            puntuacionJ1 += ACERTAR;
        }
        else
        {
            puntuacionJ2 += ACERTAR;
        }
        Actualiza(ACERTAR, esTurnoJ1);
    }
</code></pre>

<p>PS: I am using C#, Visual Studio and Unity.</p>
",https://stackoverflow.com/questions/62270736/prevent-a-method-to-be-executed-during-unit-testing,"['c#', 'unit-testing', 'unity-game-engine', 'testing', 'nunit']",632,False,0,2
Initialize struct directly for my unit testing in Go,"<pre><code>var tests = []struct {
    input    []int
    expected int
}{
    {{2, 2}, 4},
}
</code></pre>
<p>This throws <strong>missing type in composite literal</strong>. Is there anyway I can do this directly instead of defining a struct type and then create a variable of the type and then initialize it. The above is for simple unit test for a sum of 2 integers.</p>
",https://stackoverflow.com/questions/63384964/initialize-struct-directly-for-my-unit-testing-in-go,['go'],269,True,-2,1
Caching values on a module level and unit testing,"<p>Below is a module for querying and caching AWS STS tokens, the intention is to avoid querying STS if there is a valid token.</p>
<pre><code>class Credentials:
    def __init__(self):
        self.sts_credentials = None
        self.token_expiry_time = None

    def is_token_expired(self):
        current_time_with_buffer = datetime.now() + timedelta(minutes=2)
        return not self.token_expiry_time or self.token_expiry_time &lt; current_time_with_buffer


CREDENTIALS_ = Credentials()


def get_credentials():
    if CREDENTIALS_.is_token_expired():
        sts_client = boto3.client('sts')
        LOGGER.info(&quot;The credentials are either empty or expiring, refreshing&quot;)
        try:
            sts_token = sts_client.assume_role(
                RoleArn=os.environ[&quot;KINESIS_ASSUME_ROLE&quot;],
                RoleSessionName=str(uuid.uuid4()))
        except Exception as e:
            LOGGER.error(f&quot;Error occurred while trying to assume role with {os.environ['KINESIS_ASSUME_ROLE']}&quot;, e)
            raise e

        CREDENTIALS_.sts_credentials = {
            &quot;aws_access_key_id&quot;: sts_token['Credentials']['AccessKeyId'],
            &quot;aws_secret_access_key&quot;: sts_token['Credentials']['SecretAccessKey'],
            &quot;aws_session_token&quot;: sts_token['Credentials']['SessionToken']
        }

        CREDENTIALS_.token_expiry_time = sts_token[&quot;Credentials&quot;][&quot;Expiration&quot;]

    return CREDENTIALS_.sts_credentials
</code></pre>
<p>One of the unit tests is as below, this passes in isolation, but fails when run alongside other tests, the reason being <code>CREDENTIALS_</code> variable, which is modified by other tests, I can set this value to <code>None</code>, but I want to know what is the cleaner way of clearing the cached value</p>
<pre><code>def test_get_credentials_refreshes_token_if_about_to_expire(sts_response, credentials):

    with mock.patch(&quot;boto3.client&quot;) as mock_boto_client:
            mock_assume_role = mock_boto_client.return_value.assume_role
            mock_assume_role.return_value = sts_response

            get_credentials()
            actual_credentials = get_credentials()

            calls = [call('sts'),
                     call().assume_role(RoleArn='arn:aws:iam::000000000000:role/dummyarn', RoleSessionName=ANY),
                     call('sts'),
                     call().assume_role(RoleArn='arn:aws:iam::000000000000:role/dummyarn', RoleSessionName=ANY)]

            assert credentials == actual_credentials
            mock_boto_client.assert_has_calls(calls)
</code></pre>
",https://stackoverflow.com/questions/65505743/caching-values-on-a-module-level-and-unit-testing,"['python-3.x', 'pytest']",77,True,0,1
dispatchEvent syntax for selectItem($event) in angular unit testing,"<p>I am using <code>NgbTypeAhead</code> to show search results. According to the <a href=""https://ng-bootstrap.github.io/#/components/typeahead/api"" rel=""nofollow noreferrer"">Angular docs</a> I am using <code>selectedItem($event)</code> to get hold on selected value and calling my handler method to catch the event. </p>

<p>Everything works fine from UI. Now I'm having trouble unit testing the same.</p>

<p>Below is the code snippet for the same, I'm creating a fixture for my input tag and calling the <code>dispatchEvent</code> method with event name and the params it is expecting. But this is not working as expected, as the handler method is not getting the param <code>($event)</code>.</p>

<p><strong>html file</strong></p>

<pre class=""lang-html prettyprint-override""><code>&lt;div class=""input-group""&gt;
  &lt;input #teamInput teamInput.value='' type=""text"" class=""form-control"" name=""teamNameInput"" formControlName=""teamNameInput"" id=""teamNameInput"" placeholder=""Search Team Name"" i18n-placeholder=""@@TeamPlaceholder""
      [ngbTypeahead]=""teamFilter"" #teamTypeahead=""ngbTypeahead"" (selectItem)=""addTeam($event)""&gt;
 &lt;/div&gt;
</code></pre>

<p><strong>typescript file</strong></p>

<pre class=""lang-js prettyprint-override""><code>   /**
   * Adds an available team to the boardTeam class variable
   *
   * @param teamName the name of the team
   */
  addTeam(teamNameEvent: any) {
    teamNameEvent.preventDefault();
    console.log(""in addTeam:: "" + teamNameEvent.item);
    this.boardTeam = this.availableTeams.find(team =&gt; team.name === teamNameEvent.item);
    // hidden business logic
  }
</code></pre>

<p><strong>test file</strong></p>

<pre class=""lang-js prettyprint-override""><code>it(""has 2 rows in the table after calling add Team"", () =&gt; {
  const expectedTableRowLength = 2;
  const expectedHeaderRowLength = 1;
  const expectedLength = expectedHeaderRowLength + expectedTableRowLength;
  teamInput.dispatchEvent(new Event('selectItem'),{   //this particular event is not working.
     ""item"": ""testTeam"" - 
  fixtureUnderTest.detectChanges();
  const tableRows = fixtureUnderTest.nativeElement.querySelectorAll(""tr"");
      expect(tableRows.length).toBe(expectedLength);

});
</code></pre>
",https://stackoverflow.com/questions/60676181/dispatchevent-syntax-for-selectitemevent-in-angular-unit-testing,"['angular', 'jasmine', 'dispatchevent']",827,True,0,1
Unit testing for ClassMethod of a model in Flask,"<p>I have two databases: one is <code>master</code> and for testing, I have another database <code>master_test</code></p>

<p>To retrieve a total price from a table I have created a <code>@classmethod</code> in a model. This method helps me get the sum of the price filtering by month and year. Here is the class method:</p>

<pre><code>@classmethod
def get_total_book_price(cls, id):

    query = Book.query.with_entities(
        func.sum(Book.price).label(""price"")
    ).filter(
        extract('year', Book.created_at) &gt;= datetime.date.today().year,
        extract('month', Book.created_at) &gt;= datetime.date.today().month
    ).filter(
        Book.id == id
    ).all()

    return query[0].price
</code></pre>

<p>This query works nicely. But when I run this for test case its showing <code>master</code> database does not exist. It should find the <code>master_test</code> database instead of the <code>master</code> database.
Here is the test code:</p>

<pre><code>def test_get_total_book_price(self):
    id = 1
    response = Book.get_total_book_price(id)
    if not response:
        self.assertEqual(response, False)
    self.assertEqual(response, True)
</code></pre>

<p>It's showing the ERROR:</p>

<pre><code> sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL:  database ""master"" 
 does not exist
 (Background on this error at: http://sqlalche.me/e/e3q8)
 ----------------------------------------------------------------------
 Ran 34 tests in 2.011s
 FAILED (errors=1)
 ERROR: Job failed: exit code 1
</code></pre>

<p>Some other test cases are working nicely with <code>master_test</code>. But for this test why it is looking for <code>master</code> database ?</p>
",https://stackoverflow.com/questions/60707793/unit-testing-for-classmethod-of-a-model-in-flask,"['python', 'python-3.x', 'flask', 'flask-sqlalchemy']",324,True,0,1
Changing Private Method Sign with Public for Unit Testing,"<p>I know that changing private method's sign with public ignore encapsulation principle. In addition, private method is an implementation detail. But I wonder that if the method does not effect or break other part of system, can i make the method's signature public?</p>
<p>For instance;</p>
<p>I have a method which contains switch-case block;</p>
<pre><code>private Object foo(Object object, MyTypeEnum type) {
    ....
    switch(type) {
      case type.x:
         return &quot;a&quot;;
     case type.y:
         return &quot;b&quot;;
     case type.z:
         return &quot;c&quot;;
     .
     .
     .
  }
  ..
 }
</code></pre>
<p>In addition;</p>
<ul>
<li>Moving the method in utils class to be able to make its sign public is bad practise since the method is not generic and reusable</li>
<li>Testing a public method which calls the private method(foo) is one of solutions. However, my codebase has a lot of legacy and untested code so i have to change other classes and methods. Furthermore, I have no enough time refactor other part of my codebase.</li>
</ul>
<p>What do you advice to me for this case ?</p>
",https://stackoverflow.com/questions/63468474/changing-private-method-sign-with-public-for-unit-testing,"['java', 'unit-testing', 'testing', 'junit']",126,True,0,1
How to perform unit testing on highcharts in angular9?,"<p>I am having a component defined in angular9 which uses a highcharts API.
Now i want to perform a unit testing on the highcharts.
For eg:
If the data fetched is correct or not.
The highchart is created or not.
Any idea of how it can be done using Jasmin and  karma.
THanks in advance.</p>
",https://stackoverflow.com/questions/61811977/how-to-perform-unit-testing-on-highcharts-in-angular9,"['angular', 'highcharts', 'karma-jasmine']",1046,False,-1,1
Updating multiple attributes of a python object - unit testing,"<pre><code>import requests


class RadioInfo:
    def __init__(self, url, station_num=0):
        self.url = url
        self.station_num = station_num

    def update(self):
        radio_info = self.get_json()
        self.update_info(radio_info)

    def get_json(self):
        r = requests.get(self.url)
        return r.json()[self.station_num]

    def update_info(self, radio_info):
        self.radio_station_name = radio_info[&quot;station&quot;][&quot;name&quot;]
        self.radio_station_description = radio_info[&quot;station&quot;][&quot;description&quot;]
        self.current_listeners = radio_info[&quot;listeners&quot;][&quot;current&quot;]
        self.unique_listeners = radio_info[&quot;listeners&quot;][&quot;unique&quot;]
        self.total_listeners = radio_info[&quot;listeners&quot;][&quot;total&quot;]
        self.now_playing_playlist = radio_info[&quot;now_playing&quot;][&quot;playlist&quot;]
        self.now_playing_song_title = radio_info[&quot;now_playing&quot;][&quot;song&quot;][&quot;title&quot;]
        self.now_playing_song_artist = radio_info[&quot;now_playing&quot;][&quot;song&quot;][&quot;artist&quot;]
        self.now_playing_song_album = radio_info[&quot;now_playing&quot;][&quot;song&quot;][&quot;album&quot;]
        ###
        # What if radio[&quot;playing_next&quot;] is None ??
        ###
        self.next_playing_playlist = radio_info[&quot;playing_next&quot;][&quot;playlist&quot;]
        self.next_playing_song_title = radio_info[&quot;playing_next&quot;][&quot;song&quot;][&quot;title&quot;]
        self.next_playing_song_artist = radio_info[&quot;playing_next&quot;][&quot;song&quot;][&quot;artist&quot;]
        self.next_playing_song_album = radio_info[&quot;playing_next&quot;][&quot;song&quot;][&quot;album&quot;]
</code></pre>
<p>Having the above, trying to figure out how to refactor this, so that I can check if some of the nodes are <code>None</code> and handle this accordingly.
Additionally starting out with unit testing, and besides error handling was thinking about best practices of unit testing this object.
Should I create a method for each property and unit test with <code>pytest.mark.parametrize</code> for example, or is this considered redundant and not necessary ?</p>
",https://stackoverflow.com/questions/65455552/updating-multiple-attributes-of-a-python-object-unit-testing,"['python', 'unit-testing', 'pytest']",90,False,0,0
Unit testing error: Cannot read property &#39;controls&#39; of null,"<p>I'm trying to run simple test and  I'm stuck with the following issue:</p>

<pre><code>TypeError: Cannot read property 'controls' of null
    at OvertimeComponent_ng_container_6_Template (ng:///OvertimeComponent.js:250:62)
    at executeTemplate 
</code></pre>

<p>My code of the template:</p>

<pre><code>&lt;ng-container [formGroup]='shift'&gt;
  &lt;mat-card&gt;
      &lt;h6 class=""text-left""&gt;Overtimes&lt;/h6&gt;
    &lt;div class=""mt-2 mb-1""&gt;
      &lt;mat-accordion multi=""true""&gt;
        &lt;ng-container *ngIf='shift.value'&gt;
          &lt;ng-container formArrayName=""overtimes""
                        *ngFor=""let overtime of shift.get('overtimes')['controls'];let i = index""&gt;
            &lt;ng-container [formGroupName]='i'&gt;
                &lt;mat-expansion-panel&gt;
... 
</code></pre>

<p>My simple spec file for testing, there is just one test that component should be created:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { OvertimeComponent } from './overtime.component';
import {FormBuilder, ReactiveFormsModule, Validators} from ""@angular/forms"";
import {MatDialogModule} from ""@angular/material/dialog"";

describe('OvertimeComponent', () =&gt; {
  let component: OvertimeComponent;
  let fixture: ComponentFixture&lt;OvertimeComponent&gt;;
  const formBuilder: FormBuilder = new FormBuilder();

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ OvertimeComponent ],
      imports: [ReactiveFormsModule, MatDialogModule],
      providers: [ { provide: FormBuilder, useValue: formBuilder } ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(OvertimeComponent);
    component = fixture.componentInstance;
    component.shift = formBuilder.group({
      chain: ['chain', Validators.required],
      ip: [
            '',
            Validators.required
      ],
      action: ['action', Validators.required]
    });

    fixture.detectChanges();
  });

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

</code></pre>

<p>I will be appreciate any help to resolve this issue! Thanks in advance!</p>
",https://stackoverflow.com/questions/62319436/unit-testing-error-cannot-read-property-controls-of-null,"['karma-jasmine', 'angular9']",426,False,0,1
Different unit testing coverage branch with different env variables,"<p>I don't think that unit testing coverage should depend on env variables, and I would like to know how can I deal with it.</p>

<ul>
<li>Using Istanbul</li>
</ul>

<p>The coverage is lower when I run the tests with envs, in this part: </p>

<pre><code>host: process.env.DATABASE_HOST || 'localhost'
</code></pre>

<p>because with this the last branch never is reach.</p>

<p>I think that is related with <a href=""https://github.com/istanbuljs/nyc/issues/969"" rel=""nofollow noreferrer"">https://github.com/istanbuljs/nyc/issues/969</a>
and I was thinking to do <code>del process.env</code> starting the tests</p>

<p>What do you think about that? Do you know another way to solve that?</p>
",https://stackoverflow.com/questions/61734063/different-unit-testing-coverage-branch-with-different-env-variables,"['javascript', 'unit-testing', 'istanbul']",74,False,0,1
Angular 6 Unit testing Error of a particular component,"<p>I am getting the above error while doing unit testing of a particular component. I am a beginner in Angular 6.</p>

<blockquote>
  <p>StaticInjectorError(DynamicTestModule)[UtilsService -> TitleCasePipe]: 
  StaticInjectorError(Platform: core)[UtilsService -> TitleCasePipe]: 
  NullInjectorError: No provider for TitleCasePipe!/</p>
</blockquote>
",https://stackoverflow.com/questions/59717890/angular-6-unit-testing-error-of-a-particular-component,"['angular', 'unit-testing', 'angular6', 'components']",41,False,0,0
"Unit testing with angular cli, http testing not working","<p><strong>albums.spec.ts</strong></p>

<pre><code>describe(""AlbumsComponent"", () =&gt; {
  let component: AlbumsComponent;
  let fixture: ComponentFixture&lt;AlbumsComponent&gt;;
  let albumService: AlbumService;
  let httpMock: HttpTestingController;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
       ......
      ],
      imports: [AppRoutingModule, HttpClientTestingModule],
      providers: [AlbumService, HttpTestingController]
    }).compileComponents();
    albumService = TestBed.get(AlbumService);
    httpMock = TestBed.get(HttpTestingController);
  }));

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

  it(""should retrieve posts from the API via GET"", () =&gt; {
    const dummyAlbums: Album[] = [
      {
        userId: 1,
        userName: ""Arpan"",
        id: 1,
        title: ""quidem molestiae enim""
      },
      {
        userId: 1,
        userName: ""Banerjee"",
        id: 2,
        title: ""sunt qui excepturi placeat culpa""
      }
    ];
    albumService.fetchAlbums().subscribe(albums =&gt; {
      expect(albums.length).toBe(2);
      expect(albums).toEqual(dummyAlbums);
    });
      const request = httpMock.expectOne(
      ""http://jsonplaceholder.typicode.com/albums""
    );
    expect(request.request.method).toBe(""GET"");
    request.flush(dummyAlbums);
  });
});

</code></pre>

<p>i got the following error--</p>

<pre><code>10 specs, 1 failure, randomized with seed 94637
Spec List | Failures
AlbumsComponent &gt; should retrieve posts from the API via GET
**TypeError: httpMock.expectOne is not a function**
    at &lt;Jasmine&gt;
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/src/app/albums/albums.component.spec.ts:67:30)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:308:1)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:358:1)
    at Zone.run (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:124:1)
    at runInTestZone (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:561:1)
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:576:1)
    at &lt;Jasmine&gt;
</code></pre>

<p>there were no compilation errors.
here is my service class</p>

<p><strong>album.service.ts</strong></p>

<pre><code>
@Injectable({ providedIn: ""root"" })
export class AlbumService {
  constructor(private http: HttpClient) {}
  albumUrl = ""http://jsonplaceholder.typicode.com/albums"";


  //get the album title along with the user name
  **fetchAlbums(): Observable&lt;any&gt; {
    return this.http.get&lt;Album[]&gt;(this.albumUrl).pipe(
      tap(albums =&gt; {
        albums.map((album: { userId: String; userName: String }) =&gt; {
          this.fetchUsers(album.userId).subscribe((user: any) =&gt; {
            album.userName = user[0].username;
          });
        });
        // console.log(albums);
      })
    );
  }**


</code></pre>

<p>TypeError: httpMock.expectOne is not a function</p>

<p>I am not able to understand why expectOne is not a function.
I am new to angular and i am learning angular testing.here is the link of the youtube video which i followed <a href=""https://www.youtube.com/watch?v=4JVnSkR04tM&amp;t=376s"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=4JVnSkR04tM&amp;t=376s</a></p>
",https://stackoverflow.com/questions/60798646/unit-testing-with-angular-cli-http-testing-not-working,"['angular', 'testing']",113,False,0,0
"Incomplete, skipped, or risky tests in Cakephp Unit Testing","<p>I am using CakePHP version : 3.7.7</p>
<p>I have written below test case.</p>
<pre><code>public function testDashboard()
    {
    $this-&gt;get( __('user/dashboard') );
    $branches   = $this-&gt;viewVariable('branches');
    $this-&gt;assertEquals(1, !empty($branches));
}
</code></pre>
<p>For this controller code</p>
<pre><code>public function dashboard()
{
    $this-&gt;loadModel('Branches');
    $this-&gt;loadModel('Zones');

    $branches  = $this-&gt;Branches-&gt;find()
        -&gt;where( ['Branches.status' =&gt; 1] )
        -&gt;contain(['Zones'])
        -&gt;order(['Branches.id' =&gt; 'ASC', 'Branches.name' =&gt; 'ASC'])
        -&gt;toArray();// If I put first() then it works

    $this-&gt;set(compact('branches'));
}
</code></pre>
<p>When I run the test case I am getting below Error</p>
<blockquote>
<p>Test code or tested code did not (only) close its own output buffers
OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 2, Risky: 1.</p>
</blockquote>
<p>I works if:</p>
<ol>
<li>If I put <code>first()</code> instead <code>toArray()</code></li>
<li>Or just set <code>$branches = []</code></li>
</ol>
<p>How to solve this issue ?</p>
<p>Thanks for your time.</p>
",https://stackoverflow.com/questions/63922627/incomplete-skipped-or-risky-tests-in-cakephp-unit-testing,"['php', 'unit-testing', 'phpunit', 'cakephp-3.0']",300,True,0,2
How to mock api authetication in laravel unit testing,"<p><code>enter code here</code>I call service which requires authentication, for that, I Have used without middleware trait,</p>

<pre><code>$user = new User([
            'id' =&gt; 1,
            'eos_id' =&gt; '832355',
            'user_name' =&gt; 'yish',
            'email_id' =&gt; 'test@test.com'
        ]);
        $this-&gt;actingAs($user, 'api'); 
</code></pre>

<p>after that when I check as auth('api')->check()  it always returns false.</p>

<p>EDIT</p>

<p>COntroller method that i want to test</p>

<pre><code>public function destroy($id)
    {
        try {
            $deleted = $this-&gt;wareHouseService-&gt;deleteWareHouse($id, auth('api')-&gt;user()-&gt;getAuthIdentifier());
        } catch (\Exception $e) {
            $errors = [$e-&gt;getMessage()];
            if ($e instanceof ValidationException) {
                $errors = Arr::first(array_values($e-&gt;errors()));
            }
            return (new ErrorResource(collect($errors)))
                -&gt;response()
                -&gt;setStatusCode(422);
        }
}
</code></pre>

<p>Test method</p>

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

    $user = new User([
            'id' =&gt; 1,
            'whr_id' =&gt; '832355',
            'user_name' =&gt; 'yish',
            'email_id' =&gt; 'test@test.com'
        ]);

        $this-&gt;actingAs($user, 'api');

    $this-&gt;mockWareHouseService-&gt;shouldReceive('destroy')
            -&gt;with(619, auth('api')-&gt;user()-&gt;getAuthIdentifier())
            -&gt;andReturn(true);
    $actualData = $this-&gt;mockWareHouseController-&gt;destroy(619);

}
</code></pre>

<p>Here auth('api')->user()->getAuthIdentifier()  is aways return null . </p>
",https://stackoverflow.com/questions/61677877/how-to-mock-api-authetication-in-laravel-unit-testing,"['laravel', 'unit-testing', 'authentication']",295,False,0,1
Unit testing a Get request in a spring project,"<p>I developed an application which gets the details from the user via console and the data is stored in a Mongo database. After saving data is passed to angular frontend using spring api. The data is passed to the frontend without any error. Now I need to unit test the method which returns the list of books.</p>
<pre><code>@RestController
@RequestMapping(&quot;/api&quot;)
public class Controller {

@Autowired
    BookRepository bookRepo;

@GetMapping(&quot;/books&quot;)
    public List&lt;Book&gt; getBooks(){
        return bookRepo.findAll();
    }
}
</code></pre>
<p>BookRepository class extends with MongoRepository.</p>
<p>The unit test I've written so far.</p>
<pre><code>    class BookControllerTest {

    private Controller controller;

    private BookRepository repository;

    @Test
    public void getBooksTest(){

        Book b1 = new Book(&quot;12345&quot;,&quot;James&quot;,&quot;male&quot;);
        Book b2 = new Book(&quot;67890&quot;,&quot;Vicky&quot;,&quot;Female&quot;);

        List&lt;Book&gt; bookList = new ArrayList&lt;&gt;();
        bookList.add(b1);
        bookList.add(b2);
        System.out.println(bookList);

        repository.save(b1);
        repository.save(b2);
        List&lt;Book&gt; newList = controller.getBooks();
        System.out.println(newList);

        assertEquals(bookList,newList);
    }

}
</code></pre>
<p>A java.lang.NullPointerException is obtained when trying to save the data to the repository and I think the array list 'newList' also null.<br></p>
<p>Please help me to solve this problem on how to test this method.</p>
",https://stackoverflow.com/questions/63008254/unit-testing-a-get-request-in-a-spring-project,"['java', 'spring', 'unit-testing', 'junit']",750,True,0,2
Unit testing router component with Jest / React -&gt; snapshot failed,"<p>I am currently working on a small application and am busy with the Jest unit tests. Here I am trying to work with shallow rendering. Unfortunately the snapshots don't match and I don't know why (I've only been working with React and Jest for a week).</p>
<p>tests/index.test.tsx</p>
<pre><code>import { shallow, configure } from 'enzyme';
import toJson from 'enzyme-to-json';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import { AppRouter } from '..';

configure({ adapter: new Adapter() })
test('App component', () =&gt; {
  const wrapper = shallow(&lt;AppRouter routes={[]} /&gt;);
  expect(toJson(wrapper)).toMatchSnapshot();
});
</code></pre>
<p>routes/index.tsx</p>
<pre><code>export const AppRouter = ({ history, routes }: Props) =&gt; {
  return (
    &lt;Router basename={BASE_NAME} &gt;
      &lt;AppRoutes routes={routes} /&gt;
    &lt;/Router&gt;
  );
};
</code></pre>
<p>index.tsx.snap (snapshot with toJson -&gt; enzyme-to-json )</p>
<pre><code>exports[`App component 1`] = `ShallowWrapper {}`;

exports[`App component should match snapshot 1`] = `
ShallowWrapper {
  Symbol(enzyme.__root__): [Circular],
  Symbol(enzyme.__unrendered__): &lt;AppRouter
    routes={Array []}
  /&gt;,
  Symbol(enzyme.__renderer__): Object {
    &quot;batchedUpdates&quot;: [Function],
    &quot;getNode&quot;: [Function],
    &quot;render&quot;: [Function],
    &quot;simulateError&quot;: [Function],
    &quot;simulateEvent&quot;: [Function],
    &quot;unmount&quot;: [Function],
  },
  Symbol(enzyme.__node__): Object {
    &quot;instance&quot;: null,
    &quot;key&quot;: undefined,
    &quot;nodeType&quot;: &quot;class&quot;,
    &quot;props&quot;: Object {
      &quot;basename&quot;: &quot;/view/project-setup/&quot;,
      &quot;children&quot;: &lt;AppRoutes
        routes={Array []}
      /&gt;,
    },
    ....
</code></pre>
<p>Jest fail message</p>
<pre><code> FAIL  routes/tests/index.tsx
  ● App component

    expect(received).toMatchSnapshot()

    Snapshot name: `App component 1`

    - Snapshot
    + Received

    - ShallowWrapper {}
    + &lt;BrowserRouter
    +   basename=&quot;&quot;
    + &gt;
    +   &lt;AppRoutes
    +     routes={Array []}
    +   /&gt;
    + &lt;/BrowserRouter&gt;

       8 | test('App component', () =&gt; {
       9 |   const wrapper = shallow(&lt;AppRouter routes={[]} /&gt;);
    &gt; 10 |   expect(toJson(wrapper)).toMatchSnapshot();
         |                           ^
      11 | });
      12 | 

      at Object.&lt;anonymous&gt; (src/routes/__tests__/index.tsx:10:27)

 › 1 snapshot failed.
</code></pre>
",https://stackoverflow.com/questions/63736672/unit-testing-router-component-with-jest-react-snapshot-failed,"['reactjs', 'unit-testing', 'react-redux', 'react-router', 'jestjs']",440,False,0,0
Expect return HTML in ReactJS unit testing using JEST,"<p>I'm trying to unit test this function</p>
<pre><code>export const scoreText = score =&gt; {
  if (score &lt; 1.0) {
    return &lt;span style={{ color: '#fd7878' }}&gt;{score}&lt;/span&gt;;
  }

  if (score &gt;= 1.0 &amp;&amp; score &lt;= 1.5) {
    return &lt;span style={{ color: '#fd7878' }}&gt;{score}&lt;/span&gt;;
  }

  if ((score &gt;= 1.51 &amp;&amp; score &lt;= 2.49) || (score &gt;= 2.5 &amp;&amp; score &lt;= 3.0)) {
    return &lt;span style={{ color: '#2fcc71' }}&gt;{score}&lt;/span&gt;;
  }

  return score;
};
</code></pre>
<p>This is my code now. How can I unit test to expect to return a HTML code?</p>
<pre><code>describe('scoreText', () =&gt; {
  it('score less than 1.0', () =&gt; {
    expect(scoreText(0).toBeLessThan(1.0));
  });
  it('score not less than or equal to 1.0 greater than or equal to 1.5', () =&gt; {
    expect(scoreText(1.2).toBeLessThanOrEqual(1.5));
  });
  it('score not less than or equal to 1.5 greater than or equal to 2.49', () =&gt; {
    expect(scoreText(2.0).toBeLessThanOrEqual(2.49));
  });
});
</code></pre>
",https://stackoverflow.com/questions/65014994/expect-return-html-in-reactjs-unit-testing-using-jest,"['reactjs', 'jestjs']",967,True,0,2
Unit testing a method in Angular with Karma/Jasmin,"<p>I have to test a method in Angular with Jasmine/Karma, but I always get the error message:</p>

<blockquote>
  <p>TypeError: undefined is not iterable (cannot read property Symbol
  (Symbol.iterator))</p>
</blockquote>

<p>I constructed the method like this:</p>

<pre><code>  myMethod(locs: MyCustomType1[], clocs: MyCustomType2[]) {
    clocs = clocs
      .filter(cl =&gt; cl !== null &amp;&amp; cl.l_ids !== null);
    locs = locs
      .filter(l =&gt; l !== null &amp;&amp; l.id !== null);

    clocs.forEach(
      cl =&gt; {
        cl['l_names'] = [];
        locs.forEach(
          l =&gt; {
            if (cl.l_ids.includes(l.id)) {
              clocs['l_names'].push(l.name);
            }
          }
        );
      }
    );
  }
</code></pre>

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

<pre><code>  describe('#MyMethod', () =&gt; {
    beforeEach(() =&gt; {
      component.clocs = mockClocs;
      component.locs = mockLocs;
      component.myMethod(mockLocs, mockClocs);
    });
    describe('#myMethod)', () =&gt; {
      it('The clocs and locs array should by defined', () =&gt; {
        expect(component.clocs).toBeDefined();
        expect(component.locs).toBeDefined();
      });

      it('The clocs array should include ""Location2"" and ""Location3"" with the locationIds 2, 3', () =&gt; {
        expect(component.clocs[1]['l_names'].includes('Location2')).toBeTruthy();
        expect(component.clocs[1]['l_names'].includes('Location3')).toBeTruthy();
      });
    });
  });
</code></pre>

<p>The mentioned error message gets thrown for every expect() method in my it() statement. If I log the array I can see that they are defined with the needed values but the expect() method returns undefined. Hmm</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/60947464/unit-testing-a-method-in-angular-with-karma-jasmin,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",759,False,-1,2
Cannot set property &#39;http&#39; of undefined - Angular Unit testing,"<p>I am fairly new to unit testing. I am building an Angular component and my test suite is Jasmine/Karma.</p>

<p>My first test is complaining about two issues and I'm only trying to test an initialised variable value:</p>

<pre><code>TypeError: Cannot set property 'http' of undefined

TypeError: Cannot read property 'isView' of undefined
</code></pre>

<p>The code is pretty simple so wondering why I'm getting these errors?</p>

<p><strong>myComponent.ts</strong></p>

<pre><code>sView = false;
</code></pre>

<p><strong>myComponent.spec.ts</strong></p>

<pre><code>describe('myComponent', () =&gt; {
    let component: myComponent;
    let fixture: ComponentFixture&lt;myComponent&gt;;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            schemas: [NO_ERRORS_SCHEMA],
            declarations: [myComponent],
            imports: [HttpClientTestingModule],
            providers: [
                {
                    provide: myService,
                    useFactory: myServiceMock
                }
            ]
        });
        fixture = TestBed.createComponent(myComponent);
        component = fixture.componentInstance;
    });


    it('isView defaults to: false', () =&gt; {
        expect(component.isView).toEqual(false);
    });

});
</code></pre>

<p>What is going on here?</p>
",https://stackoverflow.com/questions/60974768/cannot-set-property-http-of-undefined-angular-unit-testing,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",658,True,0,1
this.mobilityService.currentMessage.subscribe is not a function in angular unit testing,"<p>In karma unit testing I'm getting this.mobilityService.currentMessage.subscribe is not a function error</p>

<p>below is the .ts file where I'm trying to get the values from another component through service</p>

<pre><code>  constructor(private projectService: ProjectService, private teamService: TeamserviceService) {this.getData()}

getData(){
this.projectService.currentMessage.subscribe(data =&gt; {
  if(data!=null)
  {
    this.serviceName=data.service_object.serviceName;
    this.serviceId = data.service_object.id})
</code></pre>

<p>this is how my service code looks like -</p>

<pre><code>messageSource = new BehaviorSubject(null);
currentMessage = this.messageSource.asObservable();
getProjectList(messageSource: string[]) {
this.messageSource.next(messageSource);
}
 constructor(private http:HttpClient) {
 getAllProjectService(teamid,serviceid){
 return this.http.get(environment.TEST_AUTOMATION_ENDPOINT+'/api/projects-by-team-and-servicestore? 
teamId='+teamid+'&amp;serviceStoreId='+serviceid+'&amp;access_token='+this.decaccesstoken);
 }
 }
</code></pre>

<p>My .spec file I'm creating a spy object like this - </p>

<pre><code>  const mockProjectService= jasmine.createSpyObj('projectService', ['getAllProjectService','currentMessage']);
</code></pre>

<p>Since 'currentMessage' is not a method inside the service I get this error. Any idea how to subscribe to a variable inside of a service?</p>
",https://stackoverflow.com/questions/60393491/this-mobilityservice-currentmessage-subscribe-is-not-a-function-in-angular-unit,"['angular', 'unit-testing', 'jasmine', 'observable', 'karma-runner']",75,True,-1,1
Unit testing class that inherits from Dictionary base class,"<p>I have the following code:</p>

<pre><code>public class DiagnosticsSettings : Dictionary&lt;string, string&gt;
    {
        public string GetStringValue(string settingName)
        {
            return TryGetValue(settingName, out var result) ? result : throw new UnknownDiagnosticSettingException($""Unable to locate setting with name {settingName}."");
        }


 public T GetEnumValue&lt;T&gt;(string settingName)
        {
            var stringValue = GetStringValue(settingName);

            if (string.IsNullOrWhiteSpace(stringValue))
                throw new UnknownDiagnosticSettingException($""Unable to locate setting with name { settingName }"");

            return (T)Enum.Parse(typeof(T), stringValue);
        }
</code></pre>

<p>I'm trying to unit test and have tried as follows: </p>

<pre><code>     [Test]
        public void Test()
        {
            var settings = new DiagnosticsSettings();
            var value = settings.GetEnumValue&lt;CreatedOn&gt;(CreatedOn.Today.ToString());
            Assert.AreEqual(1, value);
        }
</code></pre>

<p>My Enum class looks like this: </p>

<pre><code> public enum CreatedOn
    {
        Today = 1,
        All = 2
    }
</code></pre>

<p>However I keep getting the error: ""Unable to locate setting with name Today"". </p>

<p>Do I need to pass in settings to the unit test to get this to pass?</p>

<p>Any guidance would be really appreciated, thanks </p>
",https://stackoverflow.com/questions/60455467/unit-testing-class-that-inherits-from-dictionary-base-class,"['c#', 'enums', 'nunit']",162,True,0,1
Unit testing a Vue component with a &quot;HereMap&quot; inside,"<p>I'm trying to unit test a VueJS component containing a Map from HereMaps using Mocha + Chai.
I followed the official tutorial from the VueJS documentation and it went smoothly. </p>

<p>However, when I want to unit test my <code>Map.vue</code> component (containing a HereMap), the component doesn't seem to be mounted properly and there is no way to get past the terminal errors. I think it might be a problem from the scripts the HereMap needs, but I'm not sure.</p>

<p>My unit test  <code>mapTest.spec.ts</code> is the following:</p>

<pre><code>import { shallowMount } from '@vue/test-utils'
import Map from '@/components/Map.vue'
import { expect } from 'chai'

describe('Map', () =&gt; {
    const wrapper = shallowMount(Map);
    it('mounts', () =&gt; {
        wrapper.setProps({latitude: 0, longitude: 0});
        expect(true).equal(true);
  })
})
</code></pre>

<p>When I comment the line <code>const wrapper = shallowMount(Map)</code>, the errors disappear and the test runs smoothly.</p>

<p>Does anyone know how to properly unit test a HereMap?</p>

<p><strong>Thanks a lot for the help.</strong></p>

<hr>

<p>The errors I get from Mocha are as follows:</p>

<pre><code> RUNTIME EXCEPTION  Exception occurred while loading your tests

TypeError: self.eval is not a function
    at Window.&lt;anonymous&gt; (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/src/vendor/here-maps/3.1/mapsjs-core.js:34:1)
    at Object../src/vendor/here-maps/3.1/mapsjs-core.js (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/src/vendor/here-maps/3.1/mapsjs-core.js:404:1)
    at __webpack_require__ (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/webpack/bootstrap:19:1)
    at Object../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js?!./node_modules/vuetify-loader/lib/loader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Map.vue?vue&amp;type=script&amp;lang=ts&amp; (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/src/components/Map.vue:10:1)
    at __webpack_require__ (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/webpack/bootstrap:19:1)
    at Module../src/components/Map.vue?vue&amp;type=script&amp;lang=ts&amp; (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/src/components/Map.vue?0e8b:1:1)
    at __webpack_require__ (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/webpack/bootstrap:19:1)
    at Module../src/components/Map.vue (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/src/components/Map.vue?737c:1:1)
    at __webpack_require__ (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/webpack/bootstrap:19:1)
    at Object../tests/unit/map/mapTest.spec.ts (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/tests/unit/map/mapTest.spec.ts:2:1)
    at __webpack_require__ (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/webpack/bootstrap:19:1)
    at run (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mochapack/lib/entry.js:3:1)
    at Array.forEach (&lt;anonymous&gt;)
    at Object../node_modules/@vue/cli-plugin-unit-mocha/node_modules/mochapack/lib/entry.js (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mochapack/lib/entry.js:10:1)
    at __webpack_require__ (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/webpack/bootstrap:19:1)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/webpack:/webpack/bootstrap:83:1
    at Object.&lt;anonymous&gt; (/home/amaury/Documents/web-projects/projet-restau/frontend/dist/js/main.js:87:10)
    at Module._compile (internal/modules/cjs/loader.js:1123:30)
    at Object._module2.default._extensions.&lt;computed&gt; [as .js] (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mochapack/src/util/registerRequireHook.js:99:12)
    at Module.load (internal/modules/cjs/loader.js:972:32)
    at Function.Module._load (internal/modules/cjs/loader.js:872:14)
    at Module.require (internal/modules/cjs/loader.js:1012:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mocha/lib/mocha.js:334:36
    at Array.forEach (&lt;anonymous&gt;)
    at Mocha.loadFiles (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mocha/lib/mocha.js:331:14)
    at Mocha.run (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mocha/lib/mocha.js:809:10)
    at cb (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mochapack/src/runner/TestRunner.js:96:21)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/@vue/cli-plugin-unit-mocha/node_modules/mochapack/src/webpack/compiler/registerReadyCallback.js:12:7
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:61:1)
    at AsyncSeriesHook.lazyCompileHook (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/tapable/lib/Hook.js:154:20)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/webpack/lib/Compiler.js:304:22
    at Compiler.emitRecords (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/webpack/lib/Compiler.js:499:39)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/webpack/lib/Compiler.js:298:10
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/webpack/lib/Compiler.js:485:14
    at eval (eval at create (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:14:1)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/copy-webpack-plugin/dist/index.js:115:7
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:10:1)
    at AsyncSeriesHook.lazyCompileHook (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/tapable/lib/Hook.js:154:20)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/webpack/lib/Compiler.js:482:27
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/neo-async/async.js:2818:7
    at done (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/neo-async/async.js:3522:9)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/tapable/lib/HookCodeFactory.js:33:10), &lt;anonymous&gt;:4:1)
    at /home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/webpack/lib/Compiler.js:464:33
    at MemoryFileSystem.writeFile (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/memory-fs/lib/MemoryFileSystem.js:328:9)
    at writeOut (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/webpack/lib/Compiler.js:462:30)
    at Immediate._onImmediate (/home/amaury/Documents/web-projects/projet-restau/frontend/node_modules/memory-fs/lib/MemoryFileSystem.js:288:4)
    at processImmediate (internal/timers.js:456:21)
    at process.topLevelDomainCallback (domain.js:137:15)
</code></pre>
",https://stackoverflow.com/questions/61256427/unit-testing-a-vue-component-with-a-heremap-inside,"['javascript', 'unit-testing', 'vue.js', 'mocha.js', 'heremaps']",335,False,0,0
Anuglar 9 unit testing for service for post request?,"<p>How can i write test case for service in my <strong>HomeComponent.spec.ts</strong> file. And for <strong>proceed</strong> button <code>postRequest</code> method called from the home.service.ts file. i have tried out but it's not working. kindly help me out.</p>

<p>home.service.ts</p>

<pre class=""lang-js prettyprint-override""><code>import { Injectable } from '@angular/core';
import { API_ACTIONS } from 'src/app/global/constant/common-constant';
import { CommonService } from 'src/app/global/services/common.service';
import { environment } from 'src/environments/environment';

@Injectable()
export class HomeService {
  constructor(private commonService: CommonService) {}

  postRequest(requestData) {
    const endpoint = API_ACTIONS.LOAN_OFFERS;
    const url = environment.BASE_URL + environment.BASE_PATH + endpoint;
    return this.commonService.postApiCall(requestData, url, true);
  }
}
</code></pre>

<p>Here is my <strong>HomeComponent.ts</strong></p>

<pre class=""lang-js prettyprint-override""><code>proceed() {
  for (const fields in this.homeForm.controls) {
    if (this.homeForm.controls.hasOwnProperty(fields)) {
      this.homeForm.get(fields).markAsTouched();
    }
  }
  if (this.homeForm.invalid) {
    return;
  }

  const reqObj: any = {};
  reqObj.cardNumber = '1212'
  reqObj.consent = 'I Agree';
  reqObj.deviceId = '2cx3e';

  this.homeService.postRequest(reqObj).subscribe((response: any) =&gt; {
    console.log('response', response);
    if (response.meta.status === 0) {
      this.dataService.setLoanDetails(response.data);
      const homeFormRawValue = this.homeForm.getRawValue();
      this.dataService.setHomePageData(homeFormRawValue);

      this.router.navigate(['/dashboard']);
    }
  });
}
</code></pre>

<p>Here is <strong>my Spec.ts</strong></p>

<pre class=""lang-js prettyprint-override""><code>describe('HomeComponent', () =&gt; {
  let component: HomeComponent;
  let fixture: ComponentFixture&lt;HomeComponent&gt;;
  let homeService: HomeService;
  let commonService: CommonService;

  beforeEach(async(() =&gt; {

    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        RouterTestingModule,
        CommonModule,
        HttpClientModule,
        ToastrModule.forRoot({
          timeOut: 3000,
          positionClass: 'toast-bottom-right',
          maxOpened: 1,
          preventDuplicates: true,
        }),
      ],
      declarations: [HomeComponent],
      providers: [
        {
          provide: HomeService,
          useClass: MockHomeServiceStub,
        },
        CommonService,
        DataService,
      ],
    }).compileComponents();
    commonService = TestBed.inject(CommonService);
    homeService = TestBed.inject(HomeService);
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
   it('form should be submitted when click on proceed button', () =&gt; {
    component.proceed();
   });

  it('test case of services', () =&gt; {
    const requestData = {
      cardNumber: '1212',
      consentText: 'I Agree TAndC',
      deviceId: '2c3c',
    };
    homeService.postRequest(requestData);
    expect(homeService.postRequest).toHaveBeenCalled();
  });

});
</code></pre>

<p>Here is my <strong>postApiCall</strong> method</p>

<pre class=""lang-js prettyprint-override""><code>import { Injectable } from '@angular/core';
import { HttpPostRequest } from '../models/http-post-request';
import { HttpRequestService } from './http-request.service';

@Injectable()
export class CommonService {
  constructor(private httpRequestService: HttpRequestService) {}

  postApiCall(reqObj, url, isLoader) {
    const postRequestObject: HttpPostRequest = new HttpPostRequest(
      url,
      reqObj,
      {
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    );

    return this.httpRequestService.doPostRequest(postRequestObject, isLoader);
  }
}

</code></pre>
",https://stackoverflow.com/questions/61591363/anuglar-9-unit-testing-for-service-for-post-request,"['angular', 'unit-testing', 'angular6', 'karma-jasmine', 'angular9']",67,False,0,1
Best practices for Unit testing with Catch2 in Visual Studio,"<p>I'm new to unit testing in C++ and want to get some advice on this.
I use Visual Studio 2019 for development and I chose Catch2 as my testing library, I also got the Test Adapter for Catch2 installed.</p>

<p>I read docs for both Catch2 and Test Adapter for Catch2 on GitHub, but I still cannot figure out a proper way to use unit test in Visual Studio.</p>

<p>Let's assume that I already have a project with some classes in it and I want to test those classes.
Should I put files with test code in the same project or should I create new test projects within the solution?</p>

<p>When I try the first approach, Test Explorer doesn't discover tests unless I comment out the main() function of the project.
With second approach, I get a bunch of unresolved external symbol errors for my classes' methods, although I set correct relative paths to header files and referenced the main project from the test project:</p>

<pre><code>LNK2019 unresolved external symbol ""public: bool __thiscall MyClass::Check(int,int)"" (?Check@MyClass@@QAE_NHH@Z) referenced in function ""void __cdecl ____C_A_T_C_H____T_E_S_T____0(void)"" (?____C_A_T_C_H____T_E_S_T____0@@YAXXZ)
</code></pre>

<p>I would appreciate if someone show me a correct way to do unit testing with Catch2 in VS.</p>
",https://stackoverflow.com/questions/59645381/best-practices-for-unit-testing-with-catch2-in-visual-studio,"['unit-testing', 'visual-c++', 'catch-unit-test', 'catch2']",9443,True,6,1
separate unit testing and E2E testing in npm build,"<p>I am using ant-design-pro in my project. For unit testing it's jest and for e2e testing it's puppeteer. To run tests we have npm run test:all which basically runs tests for all types of tests. Is there a way to separate these files to run tests separately like run only jest files(.test.js) or e2e files(.e2e.js)?</p>
<p>Thanks in advance for your help</p>
",https://stackoverflow.com/questions/63787187/separate-unit-testing-and-e2e-testing-in-npm-build,"['reactjs', 'jestjs', 'puppeteer', 'ant-design-pro']",575,False,0,1
Clear directories after unit testing in Python using tearDownClass,"<p>I wonder how we can clear the directories after unit test in Python. I need to do it inside the classmethod <code>tearDownClass</code> instead of <code>tearDown</code> because I only want to clear this up once all the tests are done, not after every single test. The reason of this is that the created files and directories will be used in the next tests. But, at the same time, I also want to pass the directory path to <code>setUp</code> because I need that to instantiate my object. For example:</p>
<pre><code>import unittest
import os
import pandas as pd


class Class1():
    def __init__(self,in_dir,out_dir):
        self.in_dir = in_dir
        self.out_dir = out_dir
        self.excel_path = os.path.join(self.out_dir,'Excels')

    def create_dir(self):
        os.makedirs(self.excel_path)
        text = {'text':['ABC']}
        df = pd.DataFrame(text)
        df.to_csv(os.path.join(self.excel_path,'test1.csv'))

    def use_csv(self):
        for root,dirs,files in os.walk(self.excel_path):
            df = pd.DataFrame()
            for file in files:
                df_append = pd.read_csv(os.path.join(root,file))
                df = df.append(df_append)
        return df


class TestA(unittest.TestCase):

    def setUp(self):
        self.in_dir = './in_dir'
        self.out_dir = './out_dir'
        self.C = Class1(self.in_dir, self.out_dir)

    @classmethod
    def setUpClass(cls):
        #how to call out_dir in this classmethod?
        if not os.path.exists(cls.out_dir):
            os.makedirs(cls.out_dir)

    @classmethod
    def tearDownClass(cls):
        #how to call out_dir in this classmethod?
        shutil.rmtree(cls.out_dir)


    def test_1(self):
        self.C.create_dir()
        self.assertEqual(len(os.listdir(self.C.excel_path)),1)

    def test_2(self):
        self.assertIsInstance(self.C.use_csv(),pd.DataFrame)

</code></pre>
<p>If I clear up the directories using <code>tearDown</code> I will remove the generated <code>test1.csv</code> after testing <code>test_1</code>, hence, I'm thinking to use <code>tearDownClass</code> instead.</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/62547178/clear-directories-after-unit-testing-in-python-using-teardownclass,"['python', 'unit-testing', 'oop']",186,False,0,0
Python Unit Testing: Dictionary initialization across files not working,"<p>I am buiding a data storage system for one of my python projects. For this I am building and testing a type validation.</p>
<p>The data should be type checked with the <code>data_storage_type_validation</code>before storage so I made a dictionary <code>validator_storage</code> which contains a class <code>StorageValidator</code> which contains all information about a given data.</p>
<p>This all works fine but when I test the <code>data_storage_type_validation</code> function using unit tests the dictionary initialization in the <code>setUpClass</code> function is not working. It seems that the dictionary <code>validator_storage</code> at /data_managment and the imported dictionary (using <code>from data_managment import validator_storage</code>) in /test_datamanagement is not the same.</p>
<p>I am grateful for every idea.</p>
<p><strong>EDIT</strong></p>
<hr />
<p>I think my question is why does <code>validator_storage[&quot;value0&quot;].type</code> return int (as it should) in <code>TestDataStorageTypeValidation</code> and bool in <code>data_storage_type_validation</code></p>
<hr />
<p><strong>My Code</strong></p>
<p>The <code>StorageValidator</code> class(/StorageValidator):</p>
<pre><code>class StorageValidator:

def __init__(self, t: type):
    self.type = t
</code></pre>
<p>The <code>data_storage_type_validation</code> function(/data_management):</p>
<pre><code>def data_storage_type_validation(data_label: str, data) -&gt; bool:

if type(data_label) in [str]:
    if data_label in validator_storage:
        print(&quot;Data &quot;,data)
        print(&quot;Data type&quot;, type(data))
        print(&quot;datalable &quot;, data_label)
        print(&quot;expected&quot;, validator_storage[data_label].type)
        print()
        if type(data) in [validator_storage[data_label].type]:
            return True
        else:
            return False
    else:
        raise LabelNotFound
else:
    raise TypeError
</code></pre>
<p>The test <code>TestDataStorageTypeValidation</code>(/test_data_management):</p>
<pre><code>class TestDataStorageTypeValidation(unittest.TestCase):
@classmethod
def setUpClass(cls) -&gt; None:
    value_int_validator = StorageValidator
    value_int_validator.__init__(value_int_validator, t=int)
    print(&quot;Int:&quot;, value_int_validator.type)
    validator_storage[&quot;value0&quot;] = value_int_validator
    print(&quot;Int:&quot;, validator_storage[&quot;value0&quot;].type)

    value_float_validator = StorageValidator
    value_float_validator.__init__(value_float_validator ,t=float)
    validator_storage[&quot;value3.14&quot;] = value_float_validator

    value_complex_validator = StorageValidator
    value_complex_validator.__init__(value_complex_validator, t=complex)
    validator_storage[&quot;value5j&quot;] = value_complex_validator

    value_string_validator = StorageValidator
    value_string_validator.__init__(value_string_validator, t=str)
    validator_storage[&quot;valuestring&quot;] = value_string_validator

    value_list_validator = StorageValidator
    value_list_validator.__init__(value_list_validator, t=list)
    validator_storage[&quot;value[]&quot;] = value_list_validator

    value_dict_validator = StorageValidator
    value_dict_validator.__init__(value_dict_validator, t=dict)
    validator_storage[&quot;value{}&quot;] = value_dict_validator

    value_bool_validator = StorageValidator
    value_bool_validator.__init__(value_bool_validator, t=bool)
    validator_storage[&quot;valueTrue&quot;] = value_bool_validator

def test_data_storage_type_validation_success_data_valid(self):
    #return_int = data_storage_type_validation(&quot;value0&quot;, 1)
    #self.assertEqual(return_int, True)

    return_float = data_storage_type_validation(&quot;value3.14&quot;, 3.14)
    print(&quot;Return:&quot;,return_float)
    self.assertEqual(return_float, True)

    return_complex = data_storage_type_validation(&quot;value5j&quot;, 5j)
    self.assertEqual(return_complex, True)

    return_string = data_storage_type_validation(&quot;valuestring&quot;, &quot;string&quot;)
    self.assertEqual(return_string, True)

    return_list = data_storage_type_validation(&quot;value[]&quot;, [])
    self.assertEqual(return_list, True)

    return_dict = data_storage_type_validation(&quot;value{}&quot;, {})
    self.assertEqual(return_dict, True)

    return_bool = data_storage_type_validation(&quot;valueTrue&quot;, True)
    self.assertEqual(return_bool, True)

def test_data_storage_type_validation_success_data_not_valid(self):
    return_int = data_storage_type_validation(&quot;value0&quot;, &quot;false_type&quot;)
    self.assertEqual(return_int, False)

    return_float = data_storage_type_validation(&quot;value3.14&quot;, &quot;false_type&quot;)
    self.assertEqual(return_float, False)

    return_complex = data_storage_type_validation(&quot;value5j&quot;, &quot;false_type&quot;)
    self.assertEqual(return_complex, False)

    return_string = data_storage_type_validation(&quot;valuestring&quot;, [])
    self.assertEqual(return_string, False)

    return_list = data_storage_type_validation(&quot;value[]&quot;, &quot;false_type&quot;)
    self.assertEqual(return_list, False)

    return_dict = data_storage_type_validation(&quot;value{}&quot;, &quot;false_type&quot;)
    self.assertEqual(return_dict, False)

    return_bool = data_storage_type_validation(&quot;valueTrue&quot;, &quot;false_type&quot;)
    self.assertEqual(return_bool, False)

def test_data_storage_type_validation_label(self):
    self.assertRaises(LabelNotFound, data_storage_type_validation, &quot;test_label&quot;, 1)

def test_data_storage_type_validation_type(self):
    self.assertRaises(TypeError, data_storage_type_validation, 5, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, 3.1415, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, 5j, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, [], &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, {}, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, True, &quot;test&quot;)
</code></pre>
",https://stackoverflow.com/questions/62991794/python-unit-testing-dictionary-initialization-across-files-not-working,"['python', 'unit-testing', 'dictionary', 'testing', 'initialization']",151,True,0,1
How to unit test without unit testing private methods?,"<p>I have quite a bit of code in a method that broadly looks like this</p>

<pre><code>public void A(boolean f1, boolean f2, boolean f3, int var1, int var2, String var3) {
    if(f1){
        doSomething(var1)
    } else if(f2) {
        doSomethingElse(var1);
        doSomethingMore(var3);
    } else if(f3) {
        doSomethingDifferent();
        doSomethingElse(var2);
        doSomethingDifferentAgain();
    }
}

private void doSomething(int var) { ... }
private void doSomethingElse(int var) { ... }
private void doSomethingMore(String var) { ... }
private void doSomethingDifferent() { ... }
private void doSomethingDifferentAgain() { ... }
</code></pre>

<p>Now, if I have these methods all defined as private, how should I be testing them? The logic in each of the methods is fairly self enclosed, but testing just the public method will need a lot more ""handling"" in the test that a test for just the method.</p>

<p>What is the recommended way to test code like this?</p>
",https://stackoverflow.com/questions/61705542/how-to-unit-test-without-unit-testing-private-methods,"['unit-testing', 'testing', 'junit']",31,False,0,1
ag-grid unit testing using jasmine karma in angular9,"<p>I have defined my ag-grid as follows:
.HTML page:</p>
<pre><code>&lt;button (click)=&quot;getSelectedRows()&quot;&gt;Get Selected Rows&lt;/button&gt;

&lt;ag-grid-angular
#agGrid
    style=&quot;width: 500px; height: 500px;&quot;
    class=&quot;ag-theme-alpine&quot;
    [rowData]=&quot;rowData | async&quot;
    [columnDefs]=&quot;columnDefs&quot;
    rowSelection=&quot;multiple&quot;
    &gt;
&lt;/ag-grid-angular&gt;
</code></pre>
<p>the TS page:</p>
<pre><code>import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { GridOptions } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';


@Component({
  selector: 'app-samplegrid',
  templateUrl: './samplegrid.component.html',
  styleUrls: ['./samplegrid.component.scss']
})
export class SamplegridComponent implements OnInit {
  @ViewChild('agGrid') agGrid: AgGridAngular;


 columnDefs = [
  {headerName: 'Make', field: 'make', sortable: true, filter: true,
  checkboxSelection: true},
  {headerName: 'Model', field: 'model', sortable: true, filter: true},
  {headerName: 'Price', field: 'price', sortable: true, filter: true}
];
rowData: any;

  constructor(private http:HttpClient) { }

  ngOnInit(){
    this.rowData = this.http.get('https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/sample-data/smallRowData.json');
    
    
  }
  getSelectedRows(){
    const selectedNodes = this.agGrid.api.getSelectedNodes();
        const selectedData = selectedNodes.map( node =&gt; node.data );
        const selectedDataStringPresentation = selectedData.map( node =&gt; node.make + ' ' + node.model).join(', ');
        alert(`Selected nodes: ${selectedDataStringPresentation}`);
        return selectedDataStringPresentation;
    }
  }
</code></pre>
<p>My requirement is to perform unit testing for this component  to check cell content and also when the particular row is selected.</p>
<p>I have written my test scripts as follows:</p>
<pre><code>it('the grid cells should be as expected', () =&gt; {
  const appElement = fixture.nativeElement;
  const cellElements = appElement.querySelectorAll('.ag-cell-value');
  console.log(cellElements,&quot;agGrid&quot;);
  expect(cellElements.length).toEqual(9);
  expect(cellElements[0].textContent).toEqual(&quot;Toyota&quot;);
  expect(cellElements[1].textContent).toEqual(&quot;Celica&quot;);
  expect(cellElements[2].textContent).toEqual(&quot;35000&quot;);
});
</code></pre>
<p>this is failing with error :TypeError: Cannot read property 'textContent' of undefined</p>
<p>Also i am trying to imitate a select event and in order to get the selectd row i have written a test script as :</p>
<pre><code> it('getting the selected row data from the grid.', () =&gt; {
    fixture.detectChanges();
    expect(component.agGrid.api).toBeTruthy();
    let user_Data=component.agGrid.api.getSelectedRows();
    expect(user_Data).toBeDefined();
    console.log(user_Data,&quot;@ user_Data&quot;)
    
});
</code></pre>
<p>this is not failing but throwing user_data as blank.I wanted to know if there is any particular way of mocking data for ag-grid or mock ag-grid as a whole for unit testing purpose.
ANy help is welcomed.TIA.</p>
",https://stackoverflow.com/questions/62635647/ag-grid-unit-testing-using-jasmine-karma-in-angular9,"['angular', 'unit-testing', 'karma-jasmine', 'ag-grid-angular']",2954,False,0,0
How to check multiply results in unit testing Swift?,"<p>I am doing unit testing for a program. I have a func:</p>

<pre><code> static func make(for lesson: TrainingProgram.Lesson,
                     in program: TrainingProgram,
                     results: [String: TrickResults]) -&gt; [TrickContent]
</code></pre>

<p>In unit testing I written this:</p>

<pre><code>let session = TrainingSessionFactory.make(for: lesson,
                                                  in: program,
                                                  results: [trainedTrickId: result])
</code></pre>

<p>And I want to test in results: <code>[trainedTrickId: result]</code> and like <code>[trainedTrickId: resultsTwo]</code>, <code>[trainedTrickId: resultsThree]</code></p>

<p>But want to shorten my test code so don't want to make another session for different results. How do I do that?</p>

<p>result, resultsTwo, resultsThree have different values:</p>

<pre><code>let result = TrickResults(id: trainedTrickId,
                                  knowledge: 4,
                                  points: 0,
                                  lastTrainedOn: 0,
                                  lastRatedOn: 0)
</code></pre>
",https://stackoverflow.com/questions/59863013/how-to-check-multiply-results-in-unit-testing-swift,"['swift', 'unit-testing']",73,True,0,1
Unit testing dialog componentInstance event emitter in entry component,"<p>I have an entry Dialog component(EntryDialog) and an actual Dialog component(MyDialog). I have a subscriber in entry component which is subscribing to an event emitter in my main dialog component. Struggling with testing this below part, would appreciate your help. </p>

<h3>Part to test</h3>

<blockquote>
<pre><code>this.dialogRef.componentInstance.myEventEmitter.subscribe((type: string) =&gt; {
  if (type) {
    this.assignSample(type);
  }
});
</code></pre>
</blockquote>

<h3>Entry Component</h3>

<pre><code>@Component({
  selector: 'app-entry-dialog',
})
@Component({template: ''})
export class EntryDialog {
  dialogRef: MatDialogRef&lt;MyDialog&gt;;
  constructor(
      private readonly dialog: MatDialog,
  ) {
    this.dialogRef = this.dialog.open(MyDialog, {
      data: someData,
      disableClose: true,
    });
    this.dialogRef.componentInstance.myEventEmitter.subscribe((type: string) =&gt; {
      if (type) {
        this.assignSample(type);
      }
    });
  }

  private assignSample(type: string) {
    // some code here
  }
</code></pre>

<h3>Main Dialog Component</h3>

<pre><code>@Component({
  selector: 'app-my-dialog',
  templateUrl: './my_dialog.ng.html',
})
export class MyDialog {
  @Output() myEventEmitter = new EventEmitter&lt;string&gt;(true);

  constructor(
      @Inject(MAT_DIALOG_DATA) readonly sample: string,
      public dialogRef: MatDialogRef&lt;MyDialog&gt;,
  ) {
    merge(
        this.dialogRef.backdropClick(),
        this.dialogRef.keydownEvents().pipe(filter(
            (keyboardEvent: KeyboardEvent) =&gt; keyboardEvent.key === 'Escape')))
        .pipe(take(1))
        .subscribe(() =&gt; {
          this.dialogRef.close();
        });
  }

  emitEvent() {
    this.myEventEmitter.emit(""data"");
    this.dialogRef.close();
  }
</code></pre>
",https://stackoverflow.com/questions/62173177/unit-testing-dialog-componentinstance-event-emitter-in-entry-component,"['javascript', 'angular', 'typescript', 'jasmine']",722,True,0,1
Unit testing assertions in command line applications with Click,"<p>I need to unit test that an assertion is raised in a command line function.</p>

<p><code>click</code> provides functionality to test command line applications, and <code>unittest</code> provides functionality to test that assertions are raised. My problem is combining the two.</p>

<p>What I'm testing is similar to the code below. There is a function with a command-line argument and an option that must be specified if that the argument is a certain value. It is similar in spirit to this example:</p>

<pre><code>import unittest
import click
from click.testing import CliRunner

@click.command()
@click.argument('name')
@click.option('--age')
def hello(name, age):
    if name == 'Peter' and not age:
        raise ValueError('Please specify an age!')
    click.echo('Hello %s!' % name)


class TestClickAssertion(unittest.TestCase):
    def test_hello_world(self):
        with self.assertRaises(ValueError):
            runner = CliRunner()
            result = runner.invoke(hello, ['Peter'])
            print(result)
</code></pre>

<p>The issue I have, is that running with unittest in pycharm, I get an <code>AssertionError: ValueError not raised</code> but the <code>print()</code> command prints <code>&lt;Result ValueError('Please specify an age!',)&gt;</code>: which is what I want!</p>

<p>How do I get this test to pass?</p>
",https://stackoverflow.com/questions/60204007/unit-testing-assertions-in-command-line-applications-with-click,"['python', 'unit-testing', 'command-line-arguments']",180,True,0,1
Unit testing axios.mockImplementation calls keeps giving me unchanged state?,"<p>I'm still trying to learn unit testing and I've used a lot of guides, but for some reason in regards to axios testing, I'm messing up. </p>

<p>Note: I have ""jest.mock(""axios"");"" already set at the top of my testpage </p>

<pre><code>getUserInfo = async () =&gt; {
  let authToken =
        ""Bearer "" + Cookies.get(""auth-token"").replace(""__#__"", ""."");

    const instance = await axios.create({
        baseURL: ""http://127.0.0.1:8000/"",
        timeout: 8000,
        headers: {
            ""Content-Type"": ""application/json"",
            ""X-Requested-With"": ""XMLHttpRequest"",
            Authorization: authToken
        }
    });

    instance
        .get(""api/userinfo"")
        .then(json =&gt; {
            this.setState({
                user: json.data
            });
        })
        .catch(error =&gt; console.log(error));
};

componentDidMount() {
    this.getUserInfo();
}
</code></pre>

<p>and my testing is :</p>

<pre><code>  it(""fetches data correctly"", async () =&gt; {  

    const userJSON = {
        data: {
            name: ""John Doe"",
            email: ""johndoe@mail.com"",
            phone_number: ""123-456-7890"",
            profile_url: ""url""
        }
    };


    axios.get.mockImplementationOnce(() =&gt; Promise.resolve({ userJSON }));

    const instance = await renderer.create(&lt;ProfilePage /&gt;).getInstance();
    expect(instance.state.user).toEqual(userJSON)}
</code></pre>

<p>and this is the output of the test which fails: </p>

<pre><code>Expected: {""data"": {""email"": ""johndoe@mail.com"", ""name"": ""John Doe"", ""phone_number"": ""123-456-7890"", ""profile_url"": ""url""}}
Received: []
</code></pre>
",https://stackoverflow.com/questions/61181344/unit-testing-axios-mockimplementation-calls-keeps-giving-me-unchanged-state,"['javascript', 'reactjs', 'unit-testing', 'mocking', 'axios']",301,True,0,1
separate unit testing and E2E testing in npm build,"<p>I am using ant-design-pro in my project. For unit testing it's jest and for e2e testing it's puppeteer. To run tests we have npm run test:all which basically runs tests for all types of tests. Is there a way to separate these files to run tests separately like run only jest files(.test.js) or e2e files(.e2e.js)?</p>
<p>Thanks in advance for your help</p>
",https://stackoverflow.com/questions/63787187/separate-unit-testing-and-e2e-testing-in-npm-build,"['reactjs', 'jestjs', 'puppeteer', 'ant-design-pro']",575,False,0,1
Clear directories after unit testing in Python using tearDownClass,"<p>I wonder how we can clear the directories after unit test in Python. I need to do it inside the classmethod <code>tearDownClass</code> instead of <code>tearDown</code> because I only want to clear this up once all the tests are done, not after every single test. The reason of this is that the created files and directories will be used in the next tests. But, at the same time, I also want to pass the directory path to <code>setUp</code> because I need that to instantiate my object. For example:</p>
<pre><code>import unittest
import os
import pandas as pd


class Class1():
    def __init__(self,in_dir,out_dir):
        self.in_dir = in_dir
        self.out_dir = out_dir
        self.excel_path = os.path.join(self.out_dir,'Excels')

    def create_dir(self):
        os.makedirs(self.excel_path)
        text = {'text':['ABC']}
        df = pd.DataFrame(text)
        df.to_csv(os.path.join(self.excel_path,'test1.csv'))

    def use_csv(self):
        for root,dirs,files in os.walk(self.excel_path):
            df = pd.DataFrame()
            for file in files:
                df_append = pd.read_csv(os.path.join(root,file))
                df = df.append(df_append)
        return df


class TestA(unittest.TestCase):

    def setUp(self):
        self.in_dir = './in_dir'
        self.out_dir = './out_dir'
        self.C = Class1(self.in_dir, self.out_dir)

    @classmethod
    def setUpClass(cls):
        #how to call out_dir in this classmethod?
        if not os.path.exists(cls.out_dir):
            os.makedirs(cls.out_dir)

    @classmethod
    def tearDownClass(cls):
        #how to call out_dir in this classmethod?
        shutil.rmtree(cls.out_dir)


    def test_1(self):
        self.C.create_dir()
        self.assertEqual(len(os.listdir(self.C.excel_path)),1)

    def test_2(self):
        self.assertIsInstance(self.C.use_csv(),pd.DataFrame)

</code></pre>
<p>If I clear up the directories using <code>tearDown</code> I will remove the generated <code>test1.csv</code> after testing <code>test_1</code>, hence, I'm thinking to use <code>tearDownClass</code> instead.</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/62547178/clear-directories-after-unit-testing-in-python-using-teardownclass,"['python', 'unit-testing', 'oop']",186,False,0,0
Python Unit Testing: Dictionary initialization across files not working,"<p>I am buiding a data storage system for one of my python projects. For this I am building and testing a type validation.</p>
<p>The data should be type checked with the <code>data_storage_type_validation</code>before storage so I made a dictionary <code>validator_storage</code> which contains a class <code>StorageValidator</code> which contains all information about a given data.</p>
<p>This all works fine but when I test the <code>data_storage_type_validation</code> function using unit tests the dictionary initialization in the <code>setUpClass</code> function is not working. It seems that the dictionary <code>validator_storage</code> at /data_managment and the imported dictionary (using <code>from data_managment import validator_storage</code>) in /test_datamanagement is not the same.</p>
<p>I am grateful for every idea.</p>
<p><strong>EDIT</strong></p>
<hr />
<p>I think my question is why does <code>validator_storage[&quot;value0&quot;].type</code> return int (as it should) in <code>TestDataStorageTypeValidation</code> and bool in <code>data_storage_type_validation</code></p>
<hr />
<p><strong>My Code</strong></p>
<p>The <code>StorageValidator</code> class(/StorageValidator):</p>
<pre><code>class StorageValidator:

def __init__(self, t: type):
    self.type = t
</code></pre>
<p>The <code>data_storage_type_validation</code> function(/data_management):</p>
<pre><code>def data_storage_type_validation(data_label: str, data) -&gt; bool:

if type(data_label) in [str]:
    if data_label in validator_storage:
        print(&quot;Data &quot;,data)
        print(&quot;Data type&quot;, type(data))
        print(&quot;datalable &quot;, data_label)
        print(&quot;expected&quot;, validator_storage[data_label].type)
        print()
        if type(data) in [validator_storage[data_label].type]:
            return True
        else:
            return False
    else:
        raise LabelNotFound
else:
    raise TypeError
</code></pre>
<p>The test <code>TestDataStorageTypeValidation</code>(/test_data_management):</p>
<pre><code>class TestDataStorageTypeValidation(unittest.TestCase):
@classmethod
def setUpClass(cls) -&gt; None:
    value_int_validator = StorageValidator
    value_int_validator.__init__(value_int_validator, t=int)
    print(&quot;Int:&quot;, value_int_validator.type)
    validator_storage[&quot;value0&quot;] = value_int_validator
    print(&quot;Int:&quot;, validator_storage[&quot;value0&quot;].type)

    value_float_validator = StorageValidator
    value_float_validator.__init__(value_float_validator ,t=float)
    validator_storage[&quot;value3.14&quot;] = value_float_validator

    value_complex_validator = StorageValidator
    value_complex_validator.__init__(value_complex_validator, t=complex)
    validator_storage[&quot;value5j&quot;] = value_complex_validator

    value_string_validator = StorageValidator
    value_string_validator.__init__(value_string_validator, t=str)
    validator_storage[&quot;valuestring&quot;] = value_string_validator

    value_list_validator = StorageValidator
    value_list_validator.__init__(value_list_validator, t=list)
    validator_storage[&quot;value[]&quot;] = value_list_validator

    value_dict_validator = StorageValidator
    value_dict_validator.__init__(value_dict_validator, t=dict)
    validator_storage[&quot;value{}&quot;] = value_dict_validator

    value_bool_validator = StorageValidator
    value_bool_validator.__init__(value_bool_validator, t=bool)
    validator_storage[&quot;valueTrue&quot;] = value_bool_validator

def test_data_storage_type_validation_success_data_valid(self):
    #return_int = data_storage_type_validation(&quot;value0&quot;, 1)
    #self.assertEqual(return_int, True)

    return_float = data_storage_type_validation(&quot;value3.14&quot;, 3.14)
    print(&quot;Return:&quot;,return_float)
    self.assertEqual(return_float, True)

    return_complex = data_storage_type_validation(&quot;value5j&quot;, 5j)
    self.assertEqual(return_complex, True)

    return_string = data_storage_type_validation(&quot;valuestring&quot;, &quot;string&quot;)
    self.assertEqual(return_string, True)

    return_list = data_storage_type_validation(&quot;value[]&quot;, [])
    self.assertEqual(return_list, True)

    return_dict = data_storage_type_validation(&quot;value{}&quot;, {})
    self.assertEqual(return_dict, True)

    return_bool = data_storage_type_validation(&quot;valueTrue&quot;, True)
    self.assertEqual(return_bool, True)

def test_data_storage_type_validation_success_data_not_valid(self):
    return_int = data_storage_type_validation(&quot;value0&quot;, &quot;false_type&quot;)
    self.assertEqual(return_int, False)

    return_float = data_storage_type_validation(&quot;value3.14&quot;, &quot;false_type&quot;)
    self.assertEqual(return_float, False)

    return_complex = data_storage_type_validation(&quot;value5j&quot;, &quot;false_type&quot;)
    self.assertEqual(return_complex, False)

    return_string = data_storage_type_validation(&quot;valuestring&quot;, [])
    self.assertEqual(return_string, False)

    return_list = data_storage_type_validation(&quot;value[]&quot;, &quot;false_type&quot;)
    self.assertEqual(return_list, False)

    return_dict = data_storage_type_validation(&quot;value{}&quot;, &quot;false_type&quot;)
    self.assertEqual(return_dict, False)

    return_bool = data_storage_type_validation(&quot;valueTrue&quot;, &quot;false_type&quot;)
    self.assertEqual(return_bool, False)

def test_data_storage_type_validation_label(self):
    self.assertRaises(LabelNotFound, data_storage_type_validation, &quot;test_label&quot;, 1)

def test_data_storage_type_validation_type(self):
    self.assertRaises(TypeError, data_storage_type_validation, 5, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, 3.1415, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, 5j, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, [], &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, {}, &quot;test&quot;)
    self.assertRaises(TypeError, data_storage_type_validation, True, &quot;test&quot;)
</code></pre>
",https://stackoverflow.com/questions/62991794/python-unit-testing-dictionary-initialization-across-files-not-working,"['python', 'unit-testing', 'dictionary', 'testing', 'initialization']",151,True,0,1
How to unit test without unit testing private methods?,"<p>I have quite a bit of code in a method that broadly looks like this</p>

<pre><code>public void A(boolean f1, boolean f2, boolean f3, int var1, int var2, String var3) {
    if(f1){
        doSomething(var1)
    } else if(f2) {
        doSomethingElse(var1);
        doSomethingMore(var3);
    } else if(f3) {
        doSomethingDifferent();
        doSomethingElse(var2);
        doSomethingDifferentAgain();
    }
}

private void doSomething(int var) { ... }
private void doSomethingElse(int var) { ... }
private void doSomethingMore(String var) { ... }
private void doSomethingDifferent() { ... }
private void doSomethingDifferentAgain() { ... }
</code></pre>

<p>Now, if I have these methods all defined as private, how should I be testing them? The logic in each of the methods is fairly self enclosed, but testing just the public method will need a lot more ""handling"" in the test that a test for just the method.</p>

<p>What is the recommended way to test code like this?</p>
",https://stackoverflow.com/questions/61705542/how-to-unit-test-without-unit-testing-private-methods,"['unit-testing', 'testing', 'junit']",31,False,0,1
Unit testing a Get request in a spring project,"<p>I developed an application which gets the details from the user via console and the data is stored in a Mongo database. After saving data is passed to angular frontend using spring api. The data is passed to the frontend without any error. Now I need to unit test the method which returns the list of books.</p>
<pre><code>@RestController
@RequestMapping(&quot;/api&quot;)
public class Controller {

@Autowired
    BookRepository bookRepo;

@GetMapping(&quot;/books&quot;)
    public List&lt;Book&gt; getBooks(){
        return bookRepo.findAll();
    }
}
</code></pre>
<p>BookRepository class extends with MongoRepository.</p>
<p>The unit test I've written so far.</p>
<pre><code>    class BookControllerTest {

    private Controller controller;

    private BookRepository repository;

    @Test
    public void getBooksTest(){

        Book b1 = new Book(&quot;12345&quot;,&quot;James&quot;,&quot;male&quot;);
        Book b2 = new Book(&quot;67890&quot;,&quot;Vicky&quot;,&quot;Female&quot;);

        List&lt;Book&gt; bookList = new ArrayList&lt;&gt;();
        bookList.add(b1);
        bookList.add(b2);
        System.out.println(bookList);

        repository.save(b1);
        repository.save(b2);
        List&lt;Book&gt; newList = controller.getBooks();
        System.out.println(newList);

        assertEquals(bookList,newList);
    }

}
</code></pre>
<p>A java.lang.NullPointerException is obtained when trying to save the data to the repository and I think the array list 'newList' also null.<br></p>
<p>Please help me to solve this problem on how to test this method.</p>
",https://stackoverflow.com/questions/63008254/unit-testing-a-get-request-in-a-spring-project,"['java', 'spring', 'unit-testing', 'junit']",750,True,0,2
Unit testing router component with Jest / React -&gt; snapshot failed,"<p>I am currently working on a small application and am busy with the Jest unit tests. Here I am trying to work with shallow rendering. Unfortunately the snapshots don't match and I don't know why (I've only been working with React and Jest for a week).</p>
<p>tests/index.test.tsx</p>
<pre><code>import { shallow, configure } from 'enzyme';
import toJson from 'enzyme-to-json';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import { AppRouter } from '..';

configure({ adapter: new Adapter() })
test('App component', () =&gt; {
  const wrapper = shallow(&lt;AppRouter routes={[]} /&gt;);
  expect(toJson(wrapper)).toMatchSnapshot();
});
</code></pre>
<p>routes/index.tsx</p>
<pre><code>export const AppRouter = ({ history, routes }: Props) =&gt; {
  return (
    &lt;Router basename={BASE_NAME} &gt;
      &lt;AppRoutes routes={routes} /&gt;
    &lt;/Router&gt;
  );
};
</code></pre>
<p>index.tsx.snap (snapshot with toJson -&gt; enzyme-to-json )</p>
<pre><code>exports[`App component 1`] = `ShallowWrapper {}`;

exports[`App component should match snapshot 1`] = `
ShallowWrapper {
  Symbol(enzyme.__root__): [Circular],
  Symbol(enzyme.__unrendered__): &lt;AppRouter
    routes={Array []}
  /&gt;,
  Symbol(enzyme.__renderer__): Object {
    &quot;batchedUpdates&quot;: [Function],
    &quot;getNode&quot;: [Function],
    &quot;render&quot;: [Function],
    &quot;simulateError&quot;: [Function],
    &quot;simulateEvent&quot;: [Function],
    &quot;unmount&quot;: [Function],
  },
  Symbol(enzyme.__node__): Object {
    &quot;instance&quot;: null,
    &quot;key&quot;: undefined,
    &quot;nodeType&quot;: &quot;class&quot;,
    &quot;props&quot;: Object {
      &quot;basename&quot;: &quot;/view/project-setup/&quot;,
      &quot;children&quot;: &lt;AppRoutes
        routes={Array []}
      /&gt;,
    },
    ....
</code></pre>
<p>Jest fail message</p>
<pre><code> FAIL  routes/tests/index.tsx
  ● App component

    expect(received).toMatchSnapshot()

    Snapshot name: `App component 1`

    - Snapshot
    + Received

    - ShallowWrapper {}
    + &lt;BrowserRouter
    +   basename=&quot;&quot;
    + &gt;
    +   &lt;AppRoutes
    +     routes={Array []}
    +   /&gt;
    + &lt;/BrowserRouter&gt;

       8 | test('App component', () =&gt; {
       9 |   const wrapper = shallow(&lt;AppRouter routes={[]} /&gt;);
    &gt; 10 |   expect(toJson(wrapper)).toMatchSnapshot();
         |                           ^
      11 | });
      12 | 

      at Object.&lt;anonymous&gt; (src/routes/__tests__/index.tsx:10:27)

 › 1 snapshot failed.
</code></pre>
",https://stackoverflow.com/questions/63736672/unit-testing-router-component-with-jest-react-snapshot-failed,"['reactjs', 'unit-testing', 'react-redux', 'react-router', 'jestjs']",440,False,0,0
Unit testing a method in Angular with Karma/Jasmin,"<p>I have to test a method in Angular with Jasmine/Karma, but I always get the error message:</p>

<blockquote>
  <p>TypeError: undefined is not iterable (cannot read property Symbol
  (Symbol.iterator))</p>
</blockquote>

<p>I constructed the method like this:</p>

<pre><code>  myMethod(locs: MyCustomType1[], clocs: MyCustomType2[]) {
    clocs = clocs
      .filter(cl =&gt; cl !== null &amp;&amp; cl.l_ids !== null);
    locs = locs
      .filter(l =&gt; l !== null &amp;&amp; l.id !== null);

    clocs.forEach(
      cl =&gt; {
        cl['l_names'] = [];
        locs.forEach(
          l =&gt; {
            if (cl.l_ids.includes(l.id)) {
              clocs['l_names'].push(l.name);
            }
          }
        );
      }
    );
  }
</code></pre>

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

<pre><code>  describe('#MyMethod', () =&gt; {
    beforeEach(() =&gt; {
      component.clocs = mockClocs;
      component.locs = mockLocs;
      component.myMethod(mockLocs, mockClocs);
    });
    describe('#myMethod)', () =&gt; {
      it('The clocs and locs array should by defined', () =&gt; {
        expect(component.clocs).toBeDefined();
        expect(component.locs).toBeDefined();
      });

      it('The clocs array should include ""Location2"" and ""Location3"" with the locationIds 2, 3', () =&gt; {
        expect(component.clocs[1]['l_names'].includes('Location2')).toBeTruthy();
        expect(component.clocs[1]['l_names'].includes('Location3')).toBeTruthy();
      });
    });
  });
</code></pre>

<p>The mentioned error message gets thrown for every expect() method in my it() statement. If I log the array I can see that they are defined with the needed values but the expect() method returns undefined. Hmm</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/60947464/unit-testing-a-method-in-angular-with-karma-jasmin,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",759,False,-1,2
Expect return HTML in ReactJS unit testing using JEST,"<p>I'm trying to unit test this function</p>
<pre><code>export const scoreText = score =&gt; {
  if (score &lt; 1.0) {
    return &lt;span style={{ color: '#fd7878' }}&gt;{score}&lt;/span&gt;;
  }

  if (score &gt;= 1.0 &amp;&amp; score &lt;= 1.5) {
    return &lt;span style={{ color: '#fd7878' }}&gt;{score}&lt;/span&gt;;
  }

  if ((score &gt;= 1.51 &amp;&amp; score &lt;= 2.49) || (score &gt;= 2.5 &amp;&amp; score &lt;= 3.0)) {
    return &lt;span style={{ color: '#2fcc71' }}&gt;{score}&lt;/span&gt;;
  }

  return score;
};
</code></pre>
<p>This is my code now. How can I unit test to expect to return a HTML code?</p>
<pre><code>describe('scoreText', () =&gt; {
  it('score less than 1.0', () =&gt; {
    expect(scoreText(0).toBeLessThan(1.0));
  });
  it('score not less than or equal to 1.0 greater than or equal to 1.5', () =&gt; {
    expect(scoreText(1.2).toBeLessThanOrEqual(1.5));
  });
  it('score not less than or equal to 1.5 greater than or equal to 2.49', () =&gt; {
    expect(scoreText(2.0).toBeLessThanOrEqual(2.49));
  });
});
</code></pre>
",https://stackoverflow.com/questions/65014994/expect-return-html-in-reactjs-unit-testing-using-jest,"['reactjs', 'jestjs']",967,True,0,2
Unit testing with firebase auth emulator requires real service account?,"<p>We are using the firebase emulators to write integration tests. One of our functions modifies the claims on a user. As such, our test checks to see if the claim has been added. In our test, we call the following function:</p>
<pre><code>         admin.auth().getUser(user.userId)
</code></pre>
<p>Our intention is to then check the claims. Unfortunately, when this function is called, we get an error.</p>
<blockquote>
<p>(node:96985) UnhandledPromiseRejectionWarning: Error: Credential
implementation provided to initializeApp() via the &quot;credential&quot;
property failed to fetch a valid Google OAuth2 access token with the
following error: &quot;Error fetching access token: Error while making
request: getaddrinfo ENOTFOUND metadata.google.internal. Error code:
ENOTFOUND&quot;.</p>
</blockquote>
<p>Keep in mind we are running against the local auth emulator, not a cloud service. We found an issue on github which seems to be related: <a href=""https://github.com/firebase/firebase-tools/issues/1708"" rel=""noreferrer"">https://github.com/firebase/firebase-tools/issues/1708</a></p>
<p>Unfortunately, the recommended course of action in that issue is to use an actual service account file from an actual cloud service. We do not check such files into our repos as this would be a security hazard. Does anyone know of a better way to deal with this situation?</p>
<p>In case it is relevant, we also get the following warning:</p>
<blockquote>
<p>{&quot;severity&quot;:&quot;WARNING&quot;,&quot;message&quot;:&quot;Warning, FIREBASE_CONFIG and
GCLOUD_PROJECT environment variables are missing. Initializing
firebase-admin will fail&quot;}</p>
</blockquote>
",https://stackoverflow.com/questions/65209669/unit-testing-with-firebase-auth-emulator-requires-real-service-account,"['javascript', 'firebase']",608,False,6,0
when unit testing controller i&#39;m getting an assertion error,"<p>i have created a basic CRUD api with spring boot.I have written test cases for the controller class,but i'm getting error when running the test.
<strong>The code's i tried is given Below</strong></p>
<p><strong>model</strong></p>
<pre><code>package com.example.crudrestapi.model;


import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Customer {

    @Id
    @GeneratedValue private Long id;
    private String name;
    private String address;
    private String phoneNumber;
    private String gstin;
    private float outstandingBalance;
}
</code></pre>
<p><strong>CrudController</strong></p>
<pre><code>public class CrudController {

    @Autowired
    CustomerRepo customerRepo;
     @PostMapping(&quot;/customers&quot;)
    public @ResponseBody
    Customer postCustomer(@RequestBody Customer customer) {
        return customerRepo.save(customer);

    }


    @PutMapping(&quot;customers/{customerId}&quot;)
    public ResponseEntity&lt;Customer&gt; updateCustomer(@RequestBody Customer newCustomer, @PathVariable Long customerId) {

        Optional&lt;Customer&gt; optionalCustomer = customerRepo.findById(customerId);
        if (optionalCustomer.isPresent()){
            Customer c = optionalCustomer.get();
            if (newCustomer.getName() != null)
                c.setName(newCustomer.getName());
            if (newCustomer.getGstin() != null)
                c.setGstin(newCustomer.getGstin());
            if (newCustomer.getPhoneNumber() != null)
                c.setPhoneNumber(newCustomer.getPhoneNumber());
            if (newCustomer.getAddress() != null)
                c.setAddress(newCustomer.getAddress());
            if (newCustomer.getOutstandingBalance() != 0.0f)
                c.setOutstandingBalance(newCustomer.getOutstandingBalance());
            return new ResponseEntity&lt;&gt;(customerRepo.save(c), HttpStatus.OK);
        }else{
            return new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping(&quot;customers/{customerId}&quot;)
    public String deleteCustomer(@PathVariable Long customerId) throws ResourceNotFoundException {
        return customerRepo.findById(customerId)
                .map(customer -&gt; {
                    customerRepo.delete(customer);
                    return &quot;Success&quot;;
                })
                .orElseThrow(() -&gt; new ResourceNotFoundException());
    }
}
</code></pre>
<p><strong>CrudControllerTest</strong></p>
<pre><code>package com.example.crudrestapi.controller;

import com.example.crudrestapi.model.Customer;
import com.example.crudrestapi.repository.CustomerRepo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Arrays;
import java.util.Optional;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ExtendWith(SpringExtension.class)
@WebMvcTest(CrudController.class)
class CrudControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    CustomerRepo customerRepo;


    @Test
    void postCustomer() throws Exception {
        Customer customer = Customer.builder().name(&quot;name&quot;).address(&quot;address&quot;).build();
        given(customerRepo.save(customer));
        mockMvc.perform(post(&quot;/customers&quot;)
                .contentType(MediaType.APPLICATION_JSON)
                .content(customer.toString())
                )
                .andExpect(status().isOk());
    }


   
    @Test
    void deleteCustomer() throws Exception {
        Customer customer = Customer.builder().name(&quot;name&quot;).address(&quot;address&quot;).build();
        given(customerRepo.findById(Long.parseLong(&quot;1&quot;))).willReturn(Optional.empty());
        mockMvc.perform(delete(&quot;/customers/{customerId}&quot;, 1)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
}
</code></pre>
<p><em>Error I'm Getting for POST api test</em></p>
<pre><code>    java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;400&gt;
Expected :200
Actual   :400
&lt;Click to see difference&gt;


    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at com.example.crudrestapi.controller.CrudControllerTest.postCustomer(CrudControllerTest.java:55)
    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:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
    Suppressed: org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-&gt; at com.example.crudrestapi.controller.CrudControllerTest.postCustomer(CrudControllerTest.java:50)

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 is completed

        at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.resetMocks(ResetMocksTestExecutionListener.java:82)
        at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.resetMocks(ResetMocksTestExecutionListener.java:69)
        at org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener.afterTestMethod(ResetMocksTestExecutionListener.java:63)
        at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:441)
        at org.springframework.test.context.junit.jupiter.SpringExtension.afterEach(SpringExtension.java:205)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAfterEachCallbacks$11(TestMethodTestDescriptor.java:253)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$12(TestMethodTestDescriptor.java:269)
        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$13(TestMethodTestDescriptor.java:269)
        at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAllAfterMethodsOrCallbacks(TestMethodTestDescriptor.java:268)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAfterEachCallbacks(TestMethodTestDescriptor.java:252)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
        ... 43 more

2020-12-27 18:23:51.851  INFO 10488 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code -1
</code></pre>
<p><em>Delete Api test case Error</em></p>
<blockquote>
<p>java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;404&gt; Expected
:200 Actual   :404</p>
</blockquote>
<p>I'm failing in the above test cases.I don't know what is the issue.I'm Just a noob in testing environment .Any Suggestion would be a great help to me.</p>
<p><strong>EDIT</strong></p>
<p><em>Post api Error</em></p>
<pre><code> org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-&gt; at com.example.crudrestapi.controller.CrudControllerTest.postCustomer(CrudControllerTest.java:52)

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 is completed
</code></pre>
",https://stackoverflow.com/questions/65466113/when-unit-testing-controller-im-getting-an-assertion-error,"['java', 'spring-boot', 'unit-testing']",241,True,-2,1
Python/Pandas: Unit testing with hypothesis - reproducing falsifying example,"<p>Using the <code>hypothesis</code> library for unit testing, I am wondering how I can reproduce a falsifying example <code>pd.DataFrame</code>?</p>
<p>The output looks like this:</p>
<pre><code>Falsifying example: test_data_frame_data(
    data=                            sec_1  sec_2  sec_3
    2020-01-01 00:00:00.000001    0.0   -0.0    0.0
    2020-01-01 00:00:00.000000    0.0   -0.0    0.0
    2020-01-01 00:00:00.000257    0.0   -0.0    0.0
    2020-01-01 00:00:00.000258    0.0   -0.0    0.0
    2020-01-01 00:00:00.000261    0.0   -0.0    0.0
    ...                           ...    ...    ...
    2020-01-01 00:00:01.526858    0.0   -0.0    0.0
    2020-01-01 01:00:01.065796    0.0   -0.0    0.0
    2020-01-01 01:00:01.065797    0.0   -0.0    0.0
    2020-01-01 01:01:01.065795    0.0   -0.0    0.0
    2020-01-01 00:01:01.000020    0.0   -0.0    0.0

    [300 rows x 3 columns],
)
</code></pre>
<p><code>Hypothesis</code> didn't print a <code>seed</code> or a hint to <code>@reproduce_failure</code>.</p>
<p>I simply would like to use the falsifying example to debug my code.</p>
",https://stackoverflow.com/questions/63685033/python-pandas-unit-testing-with-hypothesis-reproducing-falsifying-example,"['python', 'pandas', 'debugging', 'python-hypothesis']",235,True,0,1
Unit Testing a function which uses a self variables,"<p>I have started writing unit tests and right now am in a situation where I need to test a function which uses a self or global class variable.</p>
<pre><code>main_class_obj = Mainclass()

@patch.object(main_class_obj, 'db_obj', mock_db_conn)
    def test_transform_coordinates(self):

        expected_result_X = 5462
        expected_result_Y = 9842

        x,y= main_class_obj.transform_links(75,50)
        assert expected_result_X == x
        assert expected_result_Y == y

def transform_links(self, x_coord, y_coord):
    
    try:
        p = pyproj.Proj(self.proj4text)
        x, y= p(x_coord, y_coord, inverse=True)
        return x, y
    except Exception as e:
        logger.exception(&quot;Error&quot;)
</code></pre>
<p>In my transform_links function , I am using a self variable, When I run my unit tests its failing to pick it up since its initialized in the init part of the main class.</p>
<p>How does one write unit tests in such scenario.</p>
",https://stackoverflow.com/questions/64104913/unit-testing-a-function-which-uses-a-self-variables,"['python', 'pytest', 'python-unittest']",52,False,0,0
Unit testing a function which changes private member variables,"<p>I have the following class:</p>

<pre><code>class foo {
    public:
        foo() : the_count(0) {}
        ~foo() = default;

        void add_one_to_count() { the_count++; };

    private:
        int the_count;
};
</code></pre>

<p>In this class, a public function changes a private member variable. How can I unit-test this in such a way that I can verify what the value of <code>the_count</code> is without making a getter function?</p>
",https://stackoverflow.com/questions/60856007/unit-testing-a-function-which-changes-private-member-variables,"['c++', 'unit-testing', 'googletest']",408,False,0,1
Vue Composition Api with Vuetify fails unit testing with jest,"<p>I try to run unit tests on vue components, the compnents are written with @vue/composition-api package and they also use vuetify.</p>

<p>The Application runs like expected, but when I run the tests I don't have access to the breakpoint property under context.root.$vuetify. When I print the context.root.$vuetify a see the vue component instance.</p>

<p>The error is ""Cannot read property 'mdAndDown' of undefined"" when i try to access it like that:</p>

<pre><code>context.root.$vuetify.breakpoint.mdAndDown
</code></pre>

<p>This is is my jest config file:</p>

<pre class=""lang-js prettyprint-override""><code>module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
  transform: { '^.*\\.js$': 'babel-jest' },
  transformIgnorePatterns: ['node_modules/(?!vue-router|@babel|vuetify)'],
  setupFiles: [
    ""&lt;rootDir&gt;/tests/unit/setup-env.ts"",
  ],
};
</code></pre>

<p>This is the Component file:</p>

<pre class=""lang-html prettyprint-override""><code>&lt;template&gt;
  &lt;v-app
    class=""sst-app-container""
  &gt;
    &lt;cmp-loading
      v-show=""!loadedBasic""
    /&gt;
    &lt;div
      id=""app-wrp""
      v-show=""loadedBasic""
    &gt;
      &lt;cmp-side-bar /&gt;
      &lt;v-content
        class=""fill-height""
      &gt;
        &lt;router-view&gt;&lt;/router-view&gt;
      &lt;/v-content&gt;
    &lt;/div&gt;
  &lt;/v-app&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import {
  computed, createComponent, onMounted, reactive, toRefs, watch,
} from '@vue/composition-api';
import basicSetup from '@/modules/core/composables/basic-setup';
import initMd from '@/modules/core/devices/mouse/composables/init-md';
import store from '@/stores';
import cmpSideBar from '../components/sidebar/CoreSideBar.mouse.vue';
import cmpLoading from '../components/loading/CoreLoading.vue';


export default createComponent({
  components: {
    cmpLoading,
    cmpSideBar,
  },
  setup(props, context) {
    console.log(context.root.$vuetify)
    const basics = basicSetup();

    return {
      ...basics,
    };
  },
});
&lt;/script&gt;
</code></pre>

<p>This is my test:</p>

<pre class=""lang-js prettyprint-override""><code>import Vue from 'vue';
import Vuetify from 'vuetify';
import BtnCmp from '../../../../../components/vc-btn.vue';
import CmApi from '@vue/composition-api';
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import {
  faPlug,
  faSignOut,
  faCog,
  faUser,
  faTachometer,
  faArrowLeft,
  faArrowRight,
} from '@fortawesome/pro-duotone-svg-icons';

library.add(
  faPlug,
  faSignOut,
  faCog,
  faUser,
  faTachometer,
  faArrowLeft,
  faArrowRight,
);

import { Breakpoint, Theme, Application, Goto, Icons, Lang, Presets } from 'vuetify/lib/services';
import {
  mount,
  createLocalVue,
} from '@vue/test-utils';
import Core from '../views/Core.mouse.vue';

const vue = createLocalVue();

vue.component('font-awesome-icon', FontAwesomeIcon);
vue.component('vc-btn', BtnCmp);

vue.use(Vuetify);
vue.use(CmApi);

describe('Core', () =&gt; {
  let vuetify;

  beforeEach(() =&gt; {
    vuetify = new Vuetify({
      mocks: {
        breakpoint: new Breakpoint({
          breakpoint: {
           scrollBarWidth: 0,
           thresholds: {
             xs: 0,
             sm: 0,
             md: 0,
             lg: 0,
           },
        },
      },
    });
  });

  it('renders the correct markup', async () =&gt; {
    // Now mount the component and you have the wrapper
    const wrapper = mount(Core, {
      localVue: vue,
      vuetify,
      stubs: ['router-link', 'router-view'],
      mocks: {
        $t: () =&gt; 'some specific text'
      },
    });

    expect(wrapper.html()).toContain('....');
  });
});
</code></pre>
",https://stackoverflow.com/questions/60213495/vue-composition-api-with-vuetify-fails-unit-testing-with-jest,"['unit-testing', 'vue.js', 'jestjs', 'vuetify.js']",2531,False,5,1
"ViewModel Unit testing multiple view states with LiveData, Coroutines and MockK","<p>I have a function in ViewModel with 2 states, first state is always LOADING, second state depends on result of api or db interactions.</p>
<p>This is the function</p>
<pre><code>fun getPostWithSuspend() {

    myCoroutineScope.launch {

        // Set current state to LOADING
        _postStateWithSuspend.value = ViewState(LOADING)

        val result = postsUseCase.getPosts()

        // Check and assign result to UI
        val resultViewState = if (result.status == SUCCESS) {
            ViewState(SUCCESS, data = result.data?.get(0)?.title)
        } else {
            ViewState(ERROR, error = result.error)
        }

        _postStateWithSuspend.value = resultViewState
    }
}
</code></pre>
<p>And no error, test works fine for checking final result of ERROR or SUCCESS</p>
<pre><code>   @Test
    fun `Given DataResult Error returned from useCase, should result error`() =
        testCoroutineRule.runBlockingTest {

            // GIVEN
            coEvery {
                useCase.getPosts()
            } returns DataResult.Error(Exception(&quot;Network error occurred.&quot;))

            // WHEN
            viewModel.getPostWithSuspend()

            // THEN
            val expected = viewModel.postStateWithSuspend.getOrAwaitMultipleValues(dataCount = 2)

//            Truth.assertThat(&quot;Network error occurred.&quot;).isEqualTo(expected?.error?.message)
//            Truth.assertThat(expected?.error).isInstanceOf(Exception::class.java)
            coVerify(atMost = 1) { useCase.getPosts() }
        }
</code></pre>
<p>But i couldn't find a way to test whether <code>LOADING</code> state has occurred or not, so i modified existing extension function to</p>
<pre><code>fun &lt;T&gt; LiveData&lt;T&gt;.getOrAwaitMultipleValues(
    time: Long = 2,
    dataCount: Int = 1,
    timeUnit: TimeUnit = TimeUnit.SECONDS,
    afterObserve: () -&gt; Unit = {}
): List&lt;T?&gt; {

    val data = mutableListOf&lt;T?&gt;()
    val latch = CountDownLatch(dataCount)

    val observer = object : Observer&lt;T&gt; {
        override fun onChanged(o: T?) {
            data.add(o)
            latch.countDown()
            this@getOrAwaitMultipleValues.removeObserver(this)
        }
    }
    this.observeForever(observer)

    afterObserve.invoke()

    // Don't wait indefinitely if the LiveData is not set.
    if (!latch.await(time, timeUnit)) {
        this.removeObserver(observer)
        throw TimeoutException(&quot;LiveData value was never set.&quot;)
    }

    @Suppress(&quot;UNCHECKED_CAST&quot;)
    return data.toList()
}
</code></pre>
<p>To add data to a list when LiveData changes and store states in that list but
it never returns LOADING state because it happens before observe starts. Is there a way to test multiple values of <code>LiveData</code>?</p>
",https://stackoverflow.com/questions/63339306/viewmodel-unit-testing-multiple-view-states-with-livedata-coroutines-and-mockk,"['android', 'unit-testing', 'android-livedata', 'kotlin-coroutines']",7329,True,11,6
Integrate unit testing for appsync mapping templates in serverless framework,"<p>Is there a method to create unit tests to test the queries and mutations of AWS AppSync before deploying it(using serverless framework).</p>

<p>I have created appsync api and data source is relational database, but now i want to integrate test case for all queries and mutations which are in vtx file format  but not getting relevant information.</p>
",https://stackoverflow.com/questions/61245783/integrate-unit-testing-for-appsync-mapping-templates-in-serverless-framework,"['unit-testing', 'graphql', 'serverless-framework', 'aws-appsync']",204,False,5,0
"Check if a function has been called, Angular unit testing","<p>I have called a function inside ngOnInit,</p>

<pre><code>ngOnInit() {
 this.isSubscribable();
}
</code></pre>

<p>I wan to do unit testing for this ngOnInit like this:</p>

<pre><code>    it('Check isSubscribable is called from ngOnInit', async(async() =&gt; {
      spyOn(component, 'isSubscribable').and.callThrough();
      fixture.detectChanges();
      await fixture.whenStable();
      expect(component.isSubscribable).toHaveBeenCalled();

    }))
</code></pre>

<p>This is not working. I need some help on this.</p>
",https://stackoverflow.com/questions/59820272/check-if-a-function-has-been-called-angular-unit-testing,"['angular', 'jasmine']",4254,True,4,2
How to use Dependency Injection with Spring Boot Unit Testing?,"<p>Is it possible to use dependency injection with unit tests using Spring Boot? For integration testing <code>@SpringBootTest</code> start the whole application context and container services. But is it possible to enable dependency injection functionality at unit test granularity?</p>
<p>Here's the example code</p>
<pre><code>@ExtendWith(SpringExtension.class)
public class MyServiceTest {
    
    @MockBean
    private MyRepository repo;
    
    @Autowired
    private MyService service; // &lt;-- this is null
    
    @Test
    void getData() {
        MyEntity e1 = new MyEntity(&quot;hello&quot;);
        MyEntity e2 = new MyEntity(&quot;world&quot;);
        
        Mockito.when(repo.findAll()).thenReturn(Arrays.asList(e1, e2));
        
        List&lt;String&gt; data = service.getData();
        
        assertEquals(2, data.size());
    }
}

@Service
public class MyService {
    
    private final MyRepository repo; // &lt;-- this is null
    
    public MyService(MyRepository repo) {
        this.repo = repo;
    }
    
    public List&lt;String&gt; getData() {
        return repo.findAll().stream()
                .map(MyEntity::getData)
                .collect(Collectors.toList());
    }
}
</code></pre>
<p>Or should I just manage the SUT (service class) as POJO and manually inject the mocked dependencies? I want to keep tests fast but minimize boilerplate code.</p>
",https://stackoverflow.com/questions/65247432/how-to-use-dependency-injection-with-spring-boot-unit-testing,"['java', 'spring', 'spring-boot', 'unit-testing', 'mockito']",3099,True,4,2
Sails.js: Unable to stub a helper for unit testing purposes,"<p><strong>Node version</strong>: v12.18.3
<strong>Sails version</strong> <em>(sails)</em>:  1.2.3</p>
<hr/>
<p>I am unable to stub a sails helper when performing unit tests. I have a helper that handles all the communication with a database. Moreover, I have an API, which uses this helper. In my tests, I am trying to stub the helper using sinon as such:</p>
<p>The API:</p>
<pre><code>fn: async function (inputs, exits) {
 // Stuff done here
 // I need to stub this helper
 let result = await sails.helpers.arangoQuery.with({
      requestId: REQUEST_ID,
      query: query,
      queryParams: params
    });
  
}
</code></pre>
<p>My test:</p>
<pre><code>describe('Get Organization', () =&gt; {
    it('Server Error - Simulates a failure in fetching the data from ArangoDB', (done) =&gt; {
        sinon.stub(sails.helpers, 'arangoQuery').returns(null, {status: &quot;success&quot;});

        supertest(sails.hooks.http.app)
            .get('/organization')
            //.expect(200)
            .end((error, response) =&gt; {
              return done()
            }
      })
})

</code></pre>
<p>When I run the test, I get the following error:</p>
<pre><code>  error: Error: cannot GET /organization (500)
      at Response.toError (/opt/designhubz/organization-service/node_modules/superagent/lib/node/response.js:94:15)
      at ResponseBase._setStatusProperties (/opt/designhubz/organization-service/node_modules/superagent/lib/response-base.js:123:16)
      at new Response (/opt/designhubz/organization-service/node_modules/superagent/lib/node/response.js:41:8)
      at Test.Request._emitResponse (/opt/designhubz/organization-service/node_modules/superagent/lib/node/index.js:752:20)
      at /opt/designhubz/organization-service/node_modules/superagent/lib/node/index.js:916:38
      at IncomingMessage.&lt;anonymous&gt; (/opt/designhubz/organization-service/node_modules/superagent/lib/node/parsers/json.js:19:7)
      at IncomingMessage.emit (events.js:327:22)
      at endReadableNT (_stream_readable.js:1220:12)
      at processTicksAndRejections (internal/process/task_queues.js:84:21) {
    status: 500,
    text: '{}',
    method: 'GET',
    path: '/organization'
  }
</code></pre>
<p>There are no documentations at all regarding this issue. Can anyone tell me how I can stub a helper?</p>
",https://stackoverflow.com/questions/63779249/sails-js-unable-to-stub-a-helper-for-unit-testing-purposes,"['unit-testing', 'sails.js', 'sinon', 'stub']",481,True,4,1
DataSource class and Retrofit Unit testing using coroutines and Mockito,"<p>Hi I am writing Unit tests for my repository and data layer in network module but while writing unit tests for my DataSource layer I am getting error from Mockito.</p>

<p>SaltDataSource class:</p>

<pre><code>class SaltDataSource : BaseDataSource() {
/**
 * This method will get salt from server
 */
suspend fun getSalt(saltRequest: SaltRequest) =
    getResult { TMSService.instance.getSaltAsync(SALT_URL, saltRequest) }
}
</code></pre>

<p>TMS Service retrofit interface: </p>

<pre><code>interface TMSService {

@POST
suspend fun postHeartBeatAsync(
    @Url url: String, @Header(""Authorization"") authToken: String,
    @Body
    heartBeatList: PostHeartBeat
):
        Response&lt;HeartBeatResponse&gt;

@POST
suspend fun getSaltAsync(@Url url: String, @Body saltRequest: SaltRequest):
        Response&lt;SaltResponse&gt;

companion object {
    //creating singleton object of TMSService
    val instance: TMSService by lazy {
        ApiClient.retrofitInstance.create(TMSService::class.java)
    }
}

}
</code></pre>

<p>SaltDataSourceTestClass:</p>

<pre><code>/**
 * Unit Test class for SaltDataSource
 */
@RunWith(MockitoJUnitRunner::class)
class SaltDataSourceTest {

@Mock
private lateinit var tmsService: TMSService

@Mock
private lateinit var saltRequest: SaltRequest

private lateinit var saltDataSource: SaltDataSource

private lateinit var saltResponse: SaltResponse

@Before
fun beforeTest() {
    saltDataSource = SaltDataSource()
}

@Test
fun givenSaltRequest_whenGetSaltCalled_shouldCallGetSaltApi() {
    runBlocking {
        saltDataSource.getSalt(saltRequest)

        delay(2000)
        Mockito.verify(tmsService).getSaltAsync(""url"", saltRequest)
    }
}

}
</code></pre>

<p>I am getting this issue while trying to verify my call using Mockito:</p>

<pre><code>Wanted but not invoked:
tmsService.getSaltAsync(""url"", saltRequest);
</code></pre>

<p>I have checked http logs and I am getting response i.e this method is getting called.</p>
",https://stackoverflow.com/questions/62059275/datasource-class-and-retrofit-unit-testing-using-coroutines-and-mockito,"['java', 'android', 'unit-testing', 'kotlin', 'mockito']",361,False,3,0
Unit Testing a http rest client implemented using boost::beast,"<p>I have an HTTP REST client implemented using boost::beast.</p>

<p>RESTClient.hpp</p>

<pre><code>#pragma once

#include &lt;boost/beast/core.hpp&gt;
#include &lt;boost/beast/http.hpp&gt;
#include &lt;boost/beast/version.hpp&gt;
#include &lt;boost/asio/strand.hpp&gt;
#include &lt;boost/property_tree/json_parser.hpp&gt;
#include &lt;boost/property_tree/ptree.hpp&gt;

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;


// Performs an HTTP GET and prints the response
class RESTClient : public std::enable_shared_from_this&lt;RESTClient&gt; {

public:
    explicit RESTClient(net::io_context&amp; ioc);

    virtual ~RESTClient();

    virtual void run(char const* host, char const* port, char const* target, int version);

    virtual void onResolve(beast::error_code ec, tcp::resolver::results_type results);

    virtual void onConnect(beast::error_code ec, tcp::resolver::results_type::endpoint_type);

    virtual void onWrite(beast::error_code ec, std::size_t bytes_transferred);

    virtual void onRead(beast::error_code ec, std::size_t bytes_transferred);

private:
    void createGetRequest(char const* host, char const* target, int version);

    void createPostRequest(char const* host, char const* target, int version, char const *body);

    std::string createBody();

    tcp::resolver m_resolver;
    beast::tcp_stream m_stream;
    beast::flat_buffer m_buffer; // (Must persist between reads)
    http::request&lt;http::string_body&gt; m_httpRequest;
    http::response&lt;http::string_body&gt; m_httpResponse;
};
</code></pre>

<p>RESTClient.cpp</p>

<pre><code>#include &lt;boost/beast/core.hpp&gt;
#include &lt;boost/beast/http.hpp&gt;
#include &lt;boost/beast/version.hpp&gt;
#include &lt;boost/asio/strand.hpp&gt;
#include &lt;boost/lexical_cast.hpp&gt;
#include &lt;cstdlib&gt;
#include &lt;iostream&gt;
#include &lt;memory&gt;
#include &lt;string&gt;
#include ""RESTClient.hpp""

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

void fail(beast::error_code ec, char const* what) {
    std::cerr &lt;&lt; what &lt;&lt; "": "" &lt;&lt; ec.message() &lt;&lt; ""\n"";
}


RESTClient::RESTClient(net::io_context&amp; ioc)
    : m_resolver(net::make_strand(ioc)), m_stream(net::make_strand(ioc)) {

}

RESTClient::~RESTClient() = default;


void RESTClient::run(char const* host, char const* port, char const* target, int version) {

    createPostRequest(host, target, version, createBody().c_str());

    m_resolver.async_resolve(host, port, beast::bind_front_handler(
        &amp;RESTClient::onResolve,
        shared_from_this()));
}

void RESTClient::onResolve(beast::error_code ec, tcp::resolver::results_type results) {
    if (ec) {
        return fail(ec, ""resolve"");
    }

    std::cout &lt;&lt; ""onResolve ******"" &lt;&lt; std::endl;
    m_stream.expires_after(std::chrono::seconds(30));

    m_stream.async_connect(results, beast::bind_front_handler(
        &amp;RESTClient::onConnect,
        shared_from_this()));
}

void
RESTClient::onConnect(beast::error_code ec, tcp::resolver::results_type::endpoint_type) {
    if (ec) {
        return fail(ec, ""connect"");
    }

    std::cout &lt;&lt; ""onConnect ******"" &lt;&lt; std::endl;

    m_stream.expires_after(std::chrono::seconds(30));

    http::async_write(m_stream, m_httpRequest,
                      beast::bind_front_handler(
                          &amp;RESTClient::onWrite,
                          shared_from_this()));
}

void
RESTClient::onWrite(beast::error_code ec, std::size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, ""write"");
    }

    std::cout &lt;&lt; ""onWrite ******"" &lt;&lt; std::endl;

    http::async_read(m_stream, m_buffer, m_httpResponse, beast::bind_front_handler(
        &amp;RESTClient::onRead,
        shared_from_this()));
}

void RESTClient::onRead(beast::error_code ec, std::size_t bytes_transferred) {

    boost::ignore_unused(bytes_transferred);

    if (ec) {
        return fail(ec, ""read"");
    }

    std::cout &lt;&lt; ""onRead ******"" &lt;&lt; std::endl;

    std::cout &lt;&lt; m_httpResponse &lt;&lt; std::endl;


    m_stream.socket().shutdown(tcp::socket::shutdown_both, ec);

    if (ec &amp;&amp; ec != beast::errc::not_connected) {
        return fail(ec, ""shutdown"");
    }
}

void RESTClient::createGetRequest(char const* host, char const* target, int version) {
    m_httpRequest.version(version);
    m_httpRequest.method(http::verb::get);
    m_httpRequest.target(target);
    m_httpRequest.set(http::field::host, host);
    m_httpRequest.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
}


void RESTClient::createPostRequest(char const* host, char const* target, int version, char const* body) {
    m_httpRequest.version(version);
    m_httpRequest.method(http::verb::post);
    m_httpRequest.target(target);
    m_httpRequest.set(http::field::host, host);
    m_httpRequest.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
    m_httpRequest.set(http::field::content_length, boost::lexical_cast&lt;std::string&gt;(strlen(body)));
    m_httpRequest.set(http::field::body, body);
    m_httpRequest.prepare_payload();
}


std::string RESTClient::createBody() {
    boost::property_tree::ptree tree;
    boost::property_tree::read_json(""test.json"",tree);
    std::basic_stringstream&lt;char&gt; jsonStream;
    boost::property_tree::json_parser::write_json(jsonStream, tree, false);
    std::cout &lt;&lt; ""json stream :"" &lt;&lt; jsonStream.str() &lt;&lt; std::endl;
    return jsonStream.str();
}


int main(int argc, char** argv) {
    // Check command line arguments.
    if (argc != 4 &amp;&amp; argc != 5) {
        std::cerr &lt;&lt;
                  ""Usage: http-client-async &lt;host&gt; &lt;port&gt; &lt;target&gt; [&lt;HTTP version: 1.0 or 1.1(default)&gt;]\n"" &lt;&lt;
                  ""Example:\n"" &lt;&lt;
                  ""    http-client-async www.example.com 80 /\n"" &lt;&lt;
                  ""    http-client-async www.example.com 80 / 1.0\n"";
        return EXIT_FAILURE;
    }
    auto const host = argv[1];
    auto const port = argv[2];
    auto const target = argv[3];
    int version = argc == 5 &amp;&amp; !std::strcmp(""1.0"", argv[4]) ? 10 : 11;

    // The io_context is required for all I/O
    net::io_context ioc;
    std::cout &lt;&lt; ""version: "" &lt;&lt; version &lt;&lt; std::endl;

    // Launch the asynchronous operation
    std::make_shared&lt;RESTClient&gt;(ioc)-&gt;run(host, port, target, version);

    // Run the I/O service. The call will return when
    // the get operation is complete.
    ioc.run();

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

<p>I want to unit test this client. I want to be able to POST a specific JSON from this client, and have the mock server reply with another specific JSON. what is the best way to do this. I am using google test</p>
",https://stackoverflow.com/questions/60650471/unit-testing-a-http-rest-client-implemented-using-boostbeast,"['c++', 'boost', 'googletest', 'boost-beast']",1010,False,3,0
Unit testing LiveData observerForever results in NullPointer Exception with Junit5,"<p>I am using Android databinding to listen to live data changes and I would like to observe changes on the viewmodel level (Rather then observing on fragment and then sending a callback to the viewmodel)
The <code>observerForever</code> is interesting as it serves the purpose for me. However when I run a test I get the following error:</p>

<pre><code>java.lang.NullPointerException
at androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77)
at androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116)
at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:461)
at androidx.lifecycle.LiveData.observeForever(LiveData.java:222)
at com.bcgdv.ber.maha.login.ui.LoginViewModel.&lt;init&gt;(LoginViewModel.kt:43)
at com.bcgdv.ber.maha.login.ui.LoginViewModelTest.&lt;init&gt;(LoginViewModelTest.kt:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.platform.commons.util.ReflectionUtils.newInstance(ReflectionUtils.java:443)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:60)
</code></pre>

<p>My code is as follows in the viewmodel class:</p>

<pre><code>val observerEmail: Observer&lt;String&gt; = Observer {
    setEmailError(it)
    checkLoginButton()
}
var email = MutableLiveData&lt;String&gt;()
init {
    email.observeForever(observerEmail)
}
</code></pre>

<p>Also to note is I am using Junit5.</p>

<pre><code>@ExtendWith(InstantTaskExecutorExtension::class)
class LoginViewModelTest {
    val emailAddress = ""xyz@xyz.com""
    val password = ""password""
    val user: User = User(""1"", ""xyz@xyz.com"", ""password"")
val loginUsecase: LoginUseCase = mock {
    on { loginUser(emailAddress, password) } doReturn (Single.just(user))
}

private val loginViewModel: LoginViewModel = LoginViewModel(
    loginUsecase,
    LoginCredentialsValidator(),
    Schedulers.trampoline(),
    Schedulers.trampoline()
)

@Test
fun should_return_user_as_null_initially() {
    whenever(loginUsecase.getUser()).thenReturn(null)
    loginViewModel.init()
    assertEquals(
        expected = null,
        actual = loginViewModel.obsEmail.get()
    )
}}
</code></pre>

<p>And this is the InstantTaskExecutorExtension.</p>

<pre><code>class InstantTaskExecutorExtension : BeforeEachCallback, AfterEachCallback {

override fun beforeEach(context: ExtensionContext?) {
    ArchTaskExecutor.getInstance()
            .setDelegate(object : TaskExecutor() {
                override fun executeOnDiskIO(runnable: Runnable) = runnable.run()

                override fun postToMainThread(runnable: Runnable) = runnable.run()

                override fun isMainThread(): Boolean = true
            })
}

override fun afterEach(context: ExtensionContext?) {
    ArchTaskExecutor.getInstance().setDelegate(null)
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/61582063/unit-testing-livedata-observerforever-results-in-nullpointer-exception-with-juni,"['android', 'junit', 'data-binding', 'android-livedata', 'observer-pattern']",1927,False,3,1
InvalidCastException unit testing with InMemoryDatabase after EF Core 5 update,"<p><em>Note: This appears to be a different issue from this other question as my problem pertains to Expressions and has nothing to do with NetTopologySuite or Owned types: <a href=""https://stackoverflow.com/questions/64779031/invalidcastexception-after-upgrading-to-ef-core-5-0"">InvalidCastException after upgrading to EF Core 5.0</a></em></p>
<p>I am having a number of unit tests fail after finally updating my project from EF Core 2.2 to EF Core 5.0. All are failing with a variation of:</p>
<blockquote>
<p>System.InvalidCastException : Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'Microsoft.EntityFrameworkCore.Query.QueryRootExpression'.</p>
</blockquote>
<p>For example, as a follow up to this question of mine: <a href=""https://stackoverflow.com/questions/58102821/translating-query-with-group-by-and-count-to-linq"">Translating query with GROUP BY and COUNT to Linq</a></p>
<p>I updated my query to the EF Core 3.0+ example given in the accepted answer, the only change being I am using a defined class in the results instead of an anonymous type:</p>
<pre><code>var countData = await _context.Sale
    .GroupBy(s =&gt; s.InternalUser.UserName)
    .Select(g =&gt; new SaleCountSummary
    {
        UserName = g.Key,
        InsertCount = g.Sum(s =&gt; s.Version == 1 ? 1 : 0),
        UpdateCount = g.Sum(s =&gt; s.Version &gt; 1 ? 1 : 0),
    })
    .ToListAsync();
</code></pre>
<p>This queries the <code>Sale</code> table to see how many rows each <code>InternalUser</code> has inserted and how many they have updated based on the <code>Version</code> number in the row.</p>
<p>This throws the aforementioned exception when called from a unit test using the InMemoryDatabase, but it translates to SQL and works just fine in my application against an actual SQL Server database.</p>
",https://stackoverflow.com/questions/64808709/invalidcastexception-unit-testing-with-inmemorydatabase-after-ef-core-5-update,"['c#', 'linq', 'entity-framework-core']",406,False,3,0
&quot;make: *** No rule to make target&quot; Using Unity Unit Testing,"<p>I ended up installing ceedling which uses ruby code to auto-generate test runs. Much better tool set for learning imo. I'm going to leave the question open in case anybody else has the same issue and someone else has the answer. </p>

<p>Hi StackOverflow family, </p>

<p>I'm currently in the process of reading through ""Test-Driven Development for Embedded C"" and am attempting to get Unity (unit tester) to work. I am able to compile some <a href=""http://www.throwtheswitch.org/unity"" rel=""nofollow noreferrer"">example code</a> using gcc.</p>

<p>When I try to follow <a href=""http://www.throwtheswitch.org/build/make"" rel=""nofollow noreferrer"">the make tutorial</a> and run 'make' in my command line:</p>

<pre><code>make: *** No rule to make target 'build/results/TestEx.txt', needed by 'test'.  Stop.
</code></pre>

<p>I tried to follow the <a href=""http://www.throwtheswitch.org/build/make"" rel=""nofollow noreferrer"">tree outline from throwtheswitch</a>, and my personal tree is below (removed Unity's files for clarity):</p>

<pre><code>.
├── build
│   ├── depends
│   ├── objs
│   └── results
├── makefile
├── src
│   ├── ex.c
│   └── ex.h
├── test
│   └── TestEx.c
├── testex
└── Unity
.

.

.
</code></pre>

<p>My makefile looks as such (Remember, it's copied):</p>

<pre><code>ifeq ($(OS),Windows_NT)
  ifeq ($(shell uname -s),) # not in a bash-like shell
    CLEANUP = del /F /Q
    MKDIR = mkdir
  else # in a bash-like shell, like msys
    CLEANUP = rm -f
    MKDIR = mkdir -p
  endif
    TARGET_EXTENSION=.exe
else
    CLEANUP = rm -f
    MKDIR = mkdir -p
    TARGET_EXTENSION=out
endif

.PHONY: clean
.PHONY: test

PATHU = Unity/src/
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 `grep -s IGNORE $(PATHR)*.txt`
    @echo ""-----------------------\nFAILURES:\n-----------------------""
    @echo `grep -s FAIL $(PATHR)*.txt`
    @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>Running <code>make -d test</code> (removed text to fit in body, but condensed to the important bits): </p>

<pre><code>    Trying pattern rule with stem 'TestEx'.
    Trying implicit prerequisite 'build/TestEx'.
    Looking for a rule with intermediate file 'build/TestEx'.
     Avoiding implicit rule recursion.
     Avoiding implicit rule recursion.
     Trying pattern rule with stem 'TestEx'.
     Trying implicit prerequisite 'build/TestEx,v'.
     Trying pattern rule with stem 'TestEx'.
     Trying implicit prerequisite 'build/RCS/TestEx,v'.
     Trying pattern rule with stem 'TestEx'.
     Trying implicit prerequisite 'build/RCS/TestEx'.
     Trying pattern rule with stem 'TestEx'.
     Trying implicit prerequisite 'build/s.TestEx'.
     Trying pattern rule with stem 'TestEx'.
     Trying implicit prerequisite 'build/SCCS/s.TestEx'.
   No implicit rule found for 'build/results/TestEx.txt'.
   Finished prerequisites of target file 'build/results/TestEx.txt'.
  Must remake target 'build/results/TestEx.txt'.
make: *** No rule to make target 'build/results/TestEx.txt', needed by 'test'.  Stop.
</code></pre>
",https://stackoverflow.com/questions/60862734/make-no-rule-to-make-target-using-unity-unit-testing,"['c', 'makefile', 'unity-test-framework']",892,True,3,2
How to set 2d array as parameter for unit testing,"<p>If expected variable is integer, it simply goes like this</p>

<pre><code>[DataRow(2)]
[TestMethod]
public void TestMethod(int expected)
{
      // some code...
}
</code></pre>

<p>But what should one do when there is 2d array int[,] instead of int parameter?
When I try to do this</p>

<pre><code>[DataRow(new int[,] { {0, 0}, {0, 0} })]
[TestMethod]
public void TestMethod(int[,] expected)
{
      // some code...
}
</code></pre>

<p>error says </p>

<blockquote>
  <p>An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type</p>
</blockquote>
",https://stackoverflow.com/questions/59806518/how-to-set-2d-array-as-parameter-for-unit-testing,"['c#', 'unit-testing', 'mstest', 'data-driven-tests', 'parameterized-unit-test']",961,True,3,1
How to catch a call to exit() (for unit testing),"<p>I'm writing a dynamic array for a personal project and am trying to unit test all the functions. I'm trying to write a unit test for <code>util_dyn_array_check_index()</code> but am having problems doing so because I made the design decision to call <code>exit(-1)</code> if there is an index out of bounds. I want to check in my unit test that it calls <code>exit()</code> when provided with an invalid index. But if I ever give it an invalid index, it just exits my testing program. Is it possible to somehow catch that a call to <code>exit()</code> was thrown, or redefine <code>exit()</code> in my testing program to prevent it from ending the tests?</p>
<p>From <a href=""https://stackoverflow.com/a/15154722/9178974"">this answer</a> I've looked into <code>atexit()</code>, but it looks like that doesn't stop an exit, just performs one or more user-defined functions before exiting. This doesn't work for me because I have other tests to run after this one. My last thought is I could make <code>util_dyn_array_check_index()</code> a macro instead of a function, and redefine <code>exit()</code> to be a different function in my testing program, but I'd rather not make it a macro if I can avoid it.</p>
<p>Here's my code:</p>
<p>The details of this struct don't really matter, just provided for completeness</p>
<pre><code>//basically a Vec&lt;T&gt;
typedef struct {
    //a pointer to the data stored
    void * data;
    //the width of the elements to be stored in bytes
    size_t stride;
    //the number of elements stored
    size_t len;
    //the number of elements able to be stored without reallocating
    size_t capacity;
} util_dyn_array;
</code></pre>
<p>Here is the function I want to test.</p>
<pre><code>//exits with -1 if index is out of bounds
inline void util_dyn_array_check_index(util_dyn_array * self, size_t index) {
    if (index &gt;= self-&gt;len) {
        exit(-1);
    }
    return;
}
</code></pre>
<p>Here is a skeleton of what I would like the test to be (omitted some macro magic I'm using to make writing tests nicer, for clarity).</p>
<pre><code>bool test_dyn_array_check_index() {
    util_dyn_array vector = util_dyn_array_new(sizeof(int), 16);
    for(int i = 0; i &lt; 16; i++) {
        util_dyn_array_push(&amp;vector, (void*)&amp;i);
    }

    for(int i = 0; i &lt; 16; i++) {
        //if nothing happens, its successful
        util_dyn_array_check_index(&amp;vector, i);
    }

    //somehow check that it calls exit without letting it crash my program
    {
        util_dyn_array_check_index(&amp;vector, 16);
    }

    return true;

}
</code></pre>
<p>Obviously I could change my code to return a <code>bool</code> or write to <code>errno</code>, but I'd prefer it to exit as its usually an unrecoverable bug.</p>
",https://stackoverflow.com/questions/64190847/how-to-catch-a-call-to-exit-for-unit-testing,"['c', 'unit-testing', 'exit']",1220,True,2,5
"Flutter/Dart unit testing, how to advance time for Timer","<p>I have a <code>Stream&lt;T&gt;</code> in my flutter app which uses <code>timeout()</code> under hood. Everything works fine, but running unit tests takes a while, since they have to wait every time for the timeout. </p>

<p>As I can see from sources <code>timeout()</code> implementation is based on <code>Timer()</code>. Is there any way to artificially advance time for <code>Timer()</code> on unit test environment?</p>

<p>For example in RxJava there is <code>TestScheduler</code> which has methods like <code>advanceTimeBy/advanceTimeTo</code>. I am looking for similar functionality.</p>

<p><strong>Update:</strong></p>

<p>The code could look like this:</p>

<pre><code>extension StreamEx&lt;T&gt; on Stream&lt;T&gt; {

  /// timeout only the first emission
  Stream&lt;T&gt; timeoutFirst(Duration timeLimit) =&gt;
      MergeStream([
        take(1).timeout(timeLimit), 
        skip(1),
      ]);
}
</code></pre>

<p>My requirement for the test here is that its runtime should not depend on whatever passed as <code>timeLimit</code> to the method. It possible with RxJava but how to fix it at Darts streams.</p>

<p><strong>Update:</strong></p>

<p>The test could look like this:</p>

<pre><code>void main() async {
  group(
    'StreamEx.timeoutFirst',
    () {
      const TIMEOUT = Duration(milliseconds: 100);
      const DELAY = Duration(milliseconds: 110);
      test(
        'should throw `TimeoutException` if it took too long for the first emission',
        () async {
          final subject = BehaviorSubject&lt;int&gt;();
          final stream = subject.timeoutFirst(TIMEOUT).dump('tag0');

          expectLater(
            stream,
            emitsInOrder([
              emitsError(isInstanceOf&lt;TimeoutException&gt;()),
              emits(equals(1)),
              emits(equals(2)),
            ]),
          );

          await Future.delayed(DELAY);
          subject.add(1);
          subject.add(2);
          subject.close();
        },
      );
    },
  );
}
</code></pre>
",https://stackoverflow.com/questions/61591644/flutter-dart-unit-testing-how-to-advance-time-for-timer,"['unit-testing', 'flutter', 'asynchronous', 'time']",851,False,2,0
how to update state in mockstore in ngrx unit testing?,"<p>I have a object defined as:</p>

<pre class=""lang-js prettyprint-override""><code>obj:{
  name:""string"",
  system:""string""
}
</code></pre>

<p>however I am trying to update the value in mockstore as:</p>

<pre class=""lang-js prettyprint-override""><code>store.setState({
  name:""Rose"",
  system:""Updated Dummy""
});
store.refreshState();
fixture.detectChanges();
</code></pre>

<p>but the value  is not updating. How can I update the value and then verify that it has been updated as a part of unit testing?</p>
",https://stackoverflow.com/questions/62134764/how-to-update-state-in-mockstore-in-ngrx-unit-testing,"['angular', 'unit-testing', 'ngrx']",2092,True,2,1
"Unit testing Django ModelForm with ImageField, tests show invalid form","<p>Trying to test a Django ModelForm, but the test cases are failing. Passing the required data but, it still shows ""The image field is required"" and tests show invalid form. </p>

<p><strong>models.py</strong></p>

<pre><code># models.py

import sys

from PIL import Image
from io import BytesIO

from django.contrib.auth.models import User
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
from django.utils.translation import ugettext as _


class ProfileImage(models.Model):
    user = models.OneToOneField(User, verbose_name=_(""user""), on_delete=models.CASCADE)
    image = models.ImageField(upload_to=""profile"")
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

    def save(self, *args, **kwargs):
        if not self.id:
            uploaded_image = Image.open(self.image)
            rgb_image = uploaded_image.convert(""RGB"")
            output = BytesIO()
            image_resized = rgb_image.resize((300, 300))
            image_resized.save(output, format=""JPEG"", quality=100)
            output.seek(0)
            self.image = InMemoryUploadedFile(
                output, ""ImageField"", ""{}.jpg"".format(self.image.name.split('.')[0]),
                ""image/jpeg"", sys.getsizeof(output), None
            )
        super().save(*args, **kwargs)

</code></pre>

<p><strong>forms.py</strong></p>

<pre><code># forms.py

from PIL import Image

from django import forms
from django.forms.utils import ErrorList
from django.utils.translation import ugettext as _

from .models import (
    ProfileImage,
)


class ProfileImageForm(forms.ModelForm):
    class Meta:
        model = ProfileImage
        fields = [""image""]

    def clean(self):
        image = self.cleaned_data.get(""image"")
        if image:
            image = Image.open(image)
            width, height = image.size
            image_format = image.format
            if image_format not in (""PNG"", ""JPEG"", ""MPO""):
                msg = _(""Unsupported image type. Please upload a *png or *jpg image."")
                self._errors[""image""] = ErrorList([msg])
                del image

            if width &lt; 300 or height &lt; 300:
                msg = _(""Image is too small! Please upload image of size 300px x 300px or More."")
                self._errors[""image""] = ErrorList([msg])
                del image
        return self.cleaned_data

</code></pre>

<p><strong>test_forms.py</strong></p>

<pre><code># test_forms.py

import os
import tempfile

from mixer.backend.django import mixer
import numpy
from PIL import Image

from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase

from base.models import (
    ProfileImage
)
from base.forms import (
    ProfileImageForm,
)


# utils functions
def get_test_image(height=100, width=100):
    """"""
    Generate image for test purpose

    Args:
        height(int): image height
        width(int): image width

    Returns:
        image(str): image path
    """"""

    image = tempfile.NamedTemporaryFile(suffix="".png"", dir=settings.MEDIA_ROOT, delete=True).name
    imarray = numpy.random.rand(height, width, 3) * 255
    im = Image.fromarray(imarray.astype(""uint8"")).convert(""RGBA"")
    im.save(image)
    return image


def delete_test_image(image):
    """"""
    Delete image generated for test purpose

    Args:
        image(str): image path

    Returns:

    """"""

    if os.path.exists(image):
        os.remove(image)


class TestFormData(TestCase):
    def setUp(self):
        self.standard_profile_test_image = get_test_image(300, 300)

    # 1st way, Fails
    def test_image_form_valid_1(self):
        image_path = self.standard_profile_test_image
        profile_img_instance = mixer.blend(ProfileImage, image=image_path)
        image = profile_img_instance.image
        form_data = {""image"": image}
        form = ProfileImageForm(form_data)
        self.assertTrue(form.is_valid())
        delete_test_image(profile_img_instance.image.path)

    # 2nd way, Fails
    def test_image_form_valid_2(self):
        image_path = self.standard_profile_test_image
        with open(image_path, ""rb"") as f:
            file_data = f.read()
            file_name = f.name
        form_data = {""image"": SimpleUploadedFile(file_name, file_data)}
        form = ProfileImageForm(data=form_data)
        self.assertTrue(form.is_valid())

    def tearDown(self):
        delete_test_image(self.standard_profile_test_image)

</code></pre>

<p>When I ran these two tests both of them threw errors: <code>form is invalid</code></p>

<p>The form shows <code>the image field is required</code> even though I passed the required data.</p>

<pre><code>&gt;&gt;&gt; form
&gt;&gt;&gt; &lt;ProfileImageForm bound=True, valid=False, fields=(image)&gt;
&gt;&gt;&gt; form.errors
&gt;&gt;&gt; {'image': ['This field is required.']}
&gt;&gt;&gt; form.non_field_errors()
&gt;&gt;&gt; []
</code></pre>
",https://stackoverflow.com/questions/59608148/unit-testing-django-modelform-with-imagefield-tests-show-invalid-form,"['python', 'django', 'unit-testing', 'django-forms']",509,True,2,1
Comparing byte arrays with EF Core InMemoryDatabase for unit testing,"<p>Using the InMemoryDatabase provider, the <code>==</code> operator does a normal reference comparison of byte arrays the same as it would for any 2 ordinary byte arrays in memory. When doing a query against an actual database the same operator is translated to a SQL command using <code>=</code> which does a sequence comparison.</p>

<p>I have a few queries that look up a User using their Windows SID which is a byte array type, for example:</p>

<pre><code>AppUser user = await appContext.AppUsers
    .SingleOrDefaultAsync(u =&gt; u.WindowsSid == currentIdentitySid);
</code></pre>

<p>In normal operation with a real database they work, but I am unable to unit test them because the queries in unit tests still do a reference comparison. If I change the query to use <code>.SequenceEqual</code> instead of <code>==</code> then they work, but that doesn't get translated to SQL when using a real database. There is a documented issue for this here: <a href=""https://github.com/dotnet/efcore/issues/13260"" rel=""nofollow noreferrer"">https://github.com/dotnet/efcore/issues/13260</a></p>

<p>In the meantime, is there any way possible to do a <code>byte[]</code> comparison that will work with the InMemoryDatabase as well as a real one?</p>
",https://stackoverflow.com/questions/60175641/comparing-byte-arrays-with-ef-core-inmemorydatabase-for-unit-testing,"['c#', 'entity-framework-core']",539,False,2,0
Angular unit testing with custom typings gives Cannot find namespace,"<p>I am using custom typings for my angular project to avoid rework in client side for strict typings. However, it is not working while running unit tests. </p>

<p>I am not sure, how to bring this namespace while running unit tests. Below is the code we have</p>

<p><strong>Component</strong></p>

<pre><code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  title = 'app';
  public employees: Company.Core.DTO.IEmployee[];
}
</code></pre>

<p><strong>SPEC</strong></p>

<pre><code>import { NO_ERRORS_SCHEMA } from ""@angular/core"";
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

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

    let fixture: ComponentFixture&lt;AppComponent&gt;;
    let component: AppComponent; 

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

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

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

  });
</code></pre>

<p><strong>Typings</strong> in file (app/typings/Company.typings.ts) autogenerated by <a href=""http://type.litesolutions.net/"" rel=""nofollow noreferrer"">TypeLite</a></p>

<pre><code>declare module Company.Core.DTO {
  interface IEmployee {
    Number: number;
    Age: number;    
    Name: string;   
  }
}
</code></pre>

<p>Error while executing unit test </p>

<blockquote>
  <p>error TS2503: <strong>Cannot find namespace Company</strong></p>
</blockquote>

<p>This happens only during unit testing compilation. While running application, we are not getting this error. </p>

<p>Tried this <a href=""https://stackoverflow.com/questions/42394697/angular2-cannot-find-namespace-google/42416954#42416954"">Angular2 Cannot find namespace &#39;google&#39;</a> but no luck</p>

<p><strong>NPM packages</strong></p>

<pre><code>Angular : 8.2.12
jasmine-core : ~3.5.0
karma: ^4.4.1
karma-jasmine : ~2.0.1
typescript: 3.5.3
</code></pre>
",https://stackoverflow.com/questions/61206128/angular-unit-testing-with-custom-typings-gives-cannot-find-namespace,"['angular', 'unit-testing', 'angular8']",1325,True,2,1
Uncaught TypeError shown in Karma when unit testing in Angular,"<p>Suppose i have a service named <strong>testService</strong> with a function <strong>getData</strong> in it. Also i have a component ( say <strong>A</strong> ) into which the service is injected.</p>

<pre><code>export class A implements OnInit,OnDestroy{
    saveObj;

    constructor(public service:testService){

    }

    ngOnDestroy(){
      if(this.saveObj) this.saveObj.unsubscribe();
    }

    ngOnInit(){
        this.saveObj = this.service.getData.subscribe(res =&gt; {
            this.func(res);
        },
        err =&gt; {
            console.log(""Error Occured"");
            this.saveObj.unsubscribe();
        });
    }

    private func(result: any){
        // Some code
    }
}
</code></pre>

<p>Now i am doing <strong><em>unit testing</em></strong> for this component. The problem is in some cases , it throws an error:</p>

<pre><code>Uncaught TypeError: _this.saveObj.unsubscribe is not a function thrown
</code></pre>

<p>Code snippet of spec.ts:</p>

<pre><code>// testServiceStub is just a mock of testService. 

beforeEach(async(()=&gt;{
    testServiceStub = jasmine.createSpyObj(['getData']);

    TestBed.configureTestingModule({
        declarations : [A],
        schemas : [NO_ERRORS_SCHEMA],
        providers : [
            { provide : testService, useValue: testServiceStub }
        ]
    }).compileComponents();
}))

beforeEach(async(()=&gt;{
    fixture = TestBed.createComponent(A);
    component = fixture.componentInstance;
}))

it('checks whether error is handled or not',()=&gt;{
    spyOn(console,'log');
    testServiceStub.getData.and.returnValue(throwError({status:404})); 
    fixture.detectChanges();
    expect(console.log).toHaveBeenCalled(); // shows the TypeError
})


it('checks whether value is handled or not',()=&gt;{
    testServiceStub.getData.and.returnValue(of(mockData)); // some mock data
    fixture.detectChanges();
    expect(component.func).toHaveBeenCalled();  // also shows the TypeError
})
</code></pre>

<p>I also referred this link <a href=""https://stackoverflow.com/questions/41191077/unsubscribe-is-not-a-function-on-an-observable"">unsubscribe is not a function on an observable</a> . But the problem is it also works in some cases and no error is shown.</p>

<p>Please help me figure out the reason and possible scenarios.</p>

<p>UPD: Added onDestroy lifecycle hook</p>
",https://stackoverflow.com/questions/61725741/uncaught-typeerror-shown-in-karma-when-unit-testing-in-angular,"['angular', 'unit-testing']",681,True,2,1
Specific questions about unit-testing Service Fabric Applications using Mocks,"<p>This question is a follow up to: <a href=""https://stackoverflow.com/questions/65321526/writing-unittests-for-a-service-fabric-application-class"">Writing UnitTests for a Service Fabric Application Class</a></p>
<p>My application definition is of the type - simplified it to solve the most basic of problems I am facing:</p>
<pre><code>namespace SearchService
{
    internal sealed class SearchServiceClass : StatelessService
    {
        //variables defined followed by constructor
        private string jsonStr;
        public SearchServiceClass(StatelessServiceContext context)
            : base(context)
        {
            try
            {
                var dataPackage = Context.CodePackageActivationContext
                .GetDataPackageObject(&quot;Data&quot;);
                jsonStr = File.ReadAllText(dataPackage.Path + @&quot;\data.json&quot;);
            }
            catch
            {
                //exception handling code
                throw;
            }
        }
        
        public bool IsDataJsonLoaded
        {
            get
            {
                return !(jsonStr == null);
            }
        }
    }
}
</code></pre>
<p>And the test class looks like:</p>
<pre><code>namespace SearchService.Tests
{
    [TestClass]
    public class SearchServiceClassTest
    {
        [TestMethod]
        public void SearchServiceClassConstructor()
        {
           var searchServiceClass = new SearchServiceClass(MockStatelessServiceContextFactory.Default);
           Assert.IsTrue(searchServiceClass.IsDataJsonLoaded);
        }
    }
}
</code></pre>
<p>The exception I get is that <strong>&quot;System.NullReferenceException: Object reference not set to an instance of an object.</strong>&quot; which is arising from the fact that &quot;dataPackage.Path&quot; is not being set to a valid value in the &quot;var dataPackage = Context.CodePackageActivationContext.GetDataPackageObject(&quot;Data&quot;);&quot; line.</p>
<p>How do I replicate the CodePackageActivationContext using the mock? The &quot;Data&quot; here refers to DataPackage which is a folder by the name &quot;Data&quot; and resides with the code for the SearchServiceClass.</p>
",https://stackoverflow.com/questions/65334180/specific-questions-about-unit-testing-service-fabric-applications-using-mocks,"['c#', '.net', 'unit-testing', 'moq', 'azure-service-fabric']",277,True,1,1
Unit testing method designed to find specific worksheets in spreadsheet,"<p>In an application that is designed to read a specific spreadsheet, assumed to have certain worksheets, there is a method designed to return these worksheets. This is using the Epplus library:</p>

<pre><code>public ExcelWorksheet findExcelSheet(ExcelPackage spreadsheet, string v);
{
    foreach (var sheet in spreadsheet.Workbook.Worksheets)
    {
        if ((sheet.Name).CompareTo(v)==0)
        {
            // matching sheet found
            return sheet;
        }
    }

    // at this point, the sheet has not been found
    // we are assuming the user has supplied the correct spreadsheet, with the required worksheets
    // if not, the program cannot continue, as it is totally dependent on this. It will not work with any old spreadsheet
    throw new Exception(""Could not find required Excel worksheet: "" + v);
}
</code></pre>

<p>As is commented in the code, its purpose is to check the worksheets with the required names are there, and return them as <code>ExcelWorksheet</code> objects. They are called three times, as there are three <strong>required</strong> worksheets.</p>

<p>This method needs to be unit-tested with <code>Microsoft.VisualStudio.TestTools.UnitTesting</code></p>

<pre><code>public void findExcelSheet_Test()
{
    // arrange
    ExcelPackage testSpreadsheet = new ExcelPackage();
    ExcelWorksheet testWsFPS = testSpreadsheet.Workbook.Worksheets.Add(""FPS"");
    ExcelWorksheet testWsDRS = testSpreadsheet.Workbook.Worksheets.Add(""DRS"");
    ExcelWorksheet testWsDPC = testSpreadsheet.Workbook.Worksheets.Add(""DPC"");

    // act

    // assert
}
</code></pre>

<p>The test method above is a starting point. What would be the best way to go about this? </p>
",https://stackoverflow.com/questions/60219717/unit-testing-method-designed-to-find-specific-worksheets-in-spreadsheet,"['c#', '.net', 'unit-testing', 'exception', 'epplus']",286,True,1,1
Unit testing a query to a CRM database with Nunit,"<p>I have the following method that I am trying to write unit tests for:</p>
<pre><code>        public Entity GetContactByEmail(string email)
        {
            var queryExpression = new QueryExpression(CRMFieldNames.Contact.EntityName);

            queryExpression.ColumnSet = new ColumnSet(CRMFieldNames.Contact.EmailAddress1);

            queryExpression.Criteria.AddCondition(CRMFieldNames.Contact.EmailAddress1, ConditionOperator.Equal, email);

            var entities = _crmExecutor.Execute(service =&gt; service.RetrieveMultiple(queryExpression));

            if (entities.Entities.Count &gt; 0)
            {
                return entities.Entities[0];
            }

            return entities.Entities.FirstOrDefault();
        }
</code></pre>
<p>I have attempted the following unit test:</p>
<pre><code>     [Test]
        public void GetContactByEmail_AnyCase_ReturnsEntity()
        {
            var email = &quot;lorem@ipsum.com&quot;;
            var repository = CreateEmailSendRepository();
            var query = new QueryExpression(&quot;contact&quot;);
            var entityCollection = new EntityCollection();
            entityCollection.Entities.Add(new Entity());

            _crmExecutor.Execute(_organizationService =&gt; _organizationService.RetrieveMultiple(query)).Returns(entityCollection);

            var result = repository.GetContactByEmail(email);
            Assert.IsInstanceOf&lt;Entity&gt;(result);
        }

        private EmailSendRepository CreateEmailSendRepository()
            =&gt; new EmailSendRepository(_crmExecutor);

</code></pre>
<p>It is failing on the conditional in the <code>GetContactByEmail</code> method saying that <code>entities</code> = null. Can someone please point me in the right direction of giving entities a value here?</p>
",https://stackoverflow.com/questions/63173905/unit-testing-a-query-to-a-crm-database-with-nunit,"['c#', '.net', 'unit-testing', 'nunit', 'crm']",123,False,1,0
Angular paginator does not bind properly during karma unit testing,"<p>I have been working on building an Angular app. It consists of a table with pagination, sorting and filtering.
Everything works fine when I run <code>ng serve</code>, but the pagination does not work when I run <code>ng test</code>.
I want to write test cases for the paginator, but <code>datasource.paginator.length</code> gives me 0 even with the datasource having the data.</p>

<p>Below is a screenshot where the paginator does not bind in the test run.</p>

<p><a href=""https://i.stack.imgur.com/HaUSt.jpg"" rel=""nofollow noreferrer"">Paginator does not bind</a></p>

<p>Below is my code snippet: </p>

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

<pre><code>
  public weatherData : Array&lt;CityWeather&gt;;

  @ViewChild(GraphComponent) graphComponent : GraphComponent;

  /**
   * Table related variables
   */
  displayedColumns: string[] = ['id', 'city_name', 'country', 'temperature', 'feels_like', 'humidity', 'weather_description'];

  public dataSource : MatTableDataSource&lt;any&gt;;

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  constructor(private weatherService: WeatherService) {}

  ngOnInit() {
    this.weatherService.getWeather(cityIds)
      .subscribe(data =&gt; {
        this.weatherData = this.extractCityWeather(data);
        this.dataSource = new MatTableDataSource(this.weatherData);
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
      }
    );
  }
</code></pre>

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

<pre><code>describe('AppComponent', () =&gt; {
    let component: AppComponent;
    let fixture: ComponentFixture&lt;AppComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [
                AppComponent,
                GraphComponent
            ],
            imports: [
                BrowserModule,
                BrowserAnimationsModule,
                HttpClientModule,
                MaterialModule
            ],
            providers: [
                {
                    provide: WeatherService,
                    useClass: WeatherServiceMock
                },
                MatPaginator,
                MatSort
            ],
            schemas: [ NO_ERRORS_SCHEMA ]
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        component.graphComponent = new GraphComponentMock();
        component.ngOnInit();
        fixture.detectChanges();
    });

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

    it('should populate datasource', () =&gt; {
        expect(component.dataSource).not.toBeNull();
    })

    /**
    * Filtering test case
    */
    it('city filter should filter out 1 city', () =&gt; {
        component.applyFilter('cam');
        expect(component.dataSource.filteredData.length).toEqual(1);
    })

    it('city filter should not filter anything', () =&gt; {
        component.applyFilter('RANDOM_CITY_NAME_ALSKJDLASKJ');
        expect(component.dataSource.filteredData.length).toEqual(0);
    })

    it('pagination should work', () =&gt; {
        let i=1;
        while(component.dataSource.paginator.hasNextPage()) {
            i++;
            component.dataSource.paginator.nextPage();
        }
        expect(i).toEqual(4);
    })

});
</code></pre>

<p><code>@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator</code> here <code>static:true</code> is used because if its removed I will have to mock this object in the test run. MatPaginator expects several arguments as contructor which led to another problem.</p>

<p>Please help me understand why pagination does not work. 
Thanks in advance! :)</p>
",https://stackoverflow.com/questions/61514764/angular-paginator-does-not-bind-properly-during-karma-unit-testing,"['angular', 'unit-testing', 'pagination', 'karma-jasmine', 'paginator']",3835,True,1,1
how to prevent records from commit in odoo unit testing,"<p>While writing test cases in Odoo 10 custom modules, I'm using <code>self.env['test.model'].create({..})</code>, this is actually committing the records in DB instead of getting rolled back after the completion of test cases. I used <code>SingleTrasactionCase</code> and <code>TransactionCase</code> to write my test cases.</p>
<p>Can someone suggest to me the cleanup code I can add to prevent this from happening?</p>
<p>Below is my sample code:</p>
<pre class=""lang-py prettyprint-override""><code>class TestModel(SingleTransactionCase):
     def setUp(self:
        super(TestModel, self).setUp()
        self.testMod = self.env['test.model'].create({..})

     def test_form_submit(self):
        self.testMod.form_submit()
        self.assertEquals(...)
</code></pre>
",https://stackoverflow.com/questions/65116748/how-to-prevent-records-from-commit-in-odoo-unit-testing,"['unit-testing', 'odoo']",305,False,1,0
Unit testing ActivatedRoute queryParams unsubscribe on destroy of a component,"<p>I am trying to test the ngOnDestroy() method of this component but not able to find the correct way to do that. What should be the right way to do it?</p>

<pre><code>import {Component, OnDestroy} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';


@Component({.......})
export class MyComponent implements OnDestroy {

  private readonly destroyed = new Subject();

  constructor(private readonly route: ActivatedRoute) {
    this.route.queryParams.pipe(takeUntil(this.destroyed)).subscribe(params =&gt; {
      // custom code here
    });
  }

  ngOnDestroy() {
    this.destroyed.next();
    this.destroyed.complete();
  }
}
</code></pre>
",https://stackoverflow.com/questions/61918700/unit-testing-activatedroute-queryparams-unsubscribe-on-destroy-of-a-component,"['javascript', 'angular', 'typescript', 'jasmine', 'angular-activatedroute']",315,False,1,0
"python3 unit testing, patching return of instance method not working","<p>I am trying to do the following:</p>

<pre><code>@patch('uuid.uuid4', autospec=True)
def test_generate_adid(self, patched_uuid, app_api):
    patched_uuid.return_value = ""9e51ab81-6d65-4b81-af3b-8f7f49d69ba7""
    adid = app_api.generate_adid()
    assert adid == ""9e51ab81-6d65-4b81-af3b-8f7f49d69ba7""
</code></pre>

<p>Where <code>app_api</code> is a fixture of the class under test.</p>

<p>However, in my <code>app_api</code> class, <code>uuid4()</code> is not getting patched and keeps returning a uuid other than the one I am trying to force. Here is what the <code>generate_adid()</code> instance method looks like:</p>

<pre><code>from uuid import uuid4    
def generate_adid(self):
        adid = str(uuid4())
        return adid
</code></pre>

<p>The failing unit test error: </p>

<p><code>AssertionError: assert '90b29e86-e3b0-40aa-8971-f868f90cb009' == '9e51ab81-6d65-4b81-af3b-8f7f49d69ba7'</code></p>

<p>I have consulted this post: <a href=""https://stackoverflow.com/questions/44395755/how-to-mock-uuid-generation-in-a-test-case"">How to mock uuid generation in a test case?</a> but still am having no luck.</p>

<p>What am I doing wrong? Thanks to all of those who reply in advance. </p>

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

<pre><code>from requests import Session
from random import uniform
from hashlib import md5
from hmac import new
from uuid import uuid4
from json import dumps

class AppApi:

    def __init__(self, account):
        self.account = account
        self.session = Session()

    def generate_adid(self):
        adid = str(uuid4())
        return adid
</code></pre>

<p>Test Case:</p>

<pre><code>from src import AppApi
from pytest import fixture
from unittest.mock import patch
from json import loads


ACCOUNT = {
    ""email"": ""user@email.com"",
    ""username"": ""user"",
    ""password"": ""s3cr3t""
}

@fixture
def app_api():
    app_api = AppApi(ACCOUNT)
    yield app_api

class TestAppApi:

    @patch('uuid.uuid4')
    def test_generate_adid(self, patched_uuid, app_api):
        patched_uuid.return_value = ""9e51ab81-6d65-4b81-af3b-8f7f49d69ba7""
        adid = app_api.generate_adid()
        assert adid == ""9e51ab81-6d65-4b81-af3b-8f7f49d69ba7""
</code></pre>
",https://stackoverflow.com/questions/60594340/python3-unit-testing-patching-return-of-instance-method-not-working,"['python-3.x', 'unit-testing', 'pytest', 'uuid']",819,True,1,1
Getting &quot;TypeError: cis.createLoader is not a function&quot; unit testing BsDatepickerDirective,"<p>The following is a piece of code of my unit testing.</p>
<pre><code>let BsDatepickerConfigStub = {};

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        ...
        providers: [
            { provide: BsDatepickerConfig, useValue: BsDatepickerConfigStub }
        ]
    }).compileComponents();
    fixture = TestBed.createComponent(GoalDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});
</code></pre>
<p>Whenever I run the test</p>
<pre><code>it('should create', () =&gt; {
    expect(component).toBeTruthy();
});
</code></pre>
<p>I get this error:</p>
<p>TypeError: cis.createLoader is not a function at new BsDatepickerDirective</p>
<p>What is right way to mock all Bootstrap items in unit testing?</p>
",https://stackoverflow.com/questions/62653137/getting-typeerror-cis-createloader-is-not-a-function-unit-testing-bsdatepicke,"['angular', 'typescript', 'unit-testing', 'angular-bootstrap']",76,False,1,0
Issue unit testing this function in node with node-fetch,"<p>I'm trying to unit test this function.... following the documentation.</p>
<p>Any ideas why i'm getting this error? According to the documentation we can see it being called this way... What am I missing. <a href=""https://jestjs.io/docs/en/bypassing-module-mocks"" rel=""nofollow noreferrer"">https://jestjs.io/docs/en/bypassing-module-mocks</a></p>
<p>Thankx</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>async function isValid(pair) {
    const path = process.env.PATH;
    const query = '/check';
    const requestOptions = ccyServiceRequestOptions(pair);
    try {
        const response = await fetch(path + query, requestOptions);
        const json = await response.json();
        return json.result.pair === pair;
    } catch (err) {
        if (err instanceof TypeError) {
            return false;
        }
        else {
            log.error(err);
            throw err;
        }
    }
}

------------------------------------------------------------------------------------------
jest.mock('node-fetch');

const fetch = require('node-fetch');
const {Response} = jest.requireActual('node-fetch');


beforeEach(() =&gt; {
    jest.clearAllMocks()
})


it('should call with valid url', async () =&gt; {
        const pair = 'EURUSD';
        fetch.mockReturnValue(Promise.resolve(new Response({})));

        await ccyPairIsValid(pair);

        expect(fetch).toHaveBeenCalled();
        expect(fetch.mock.calls[0][0]).toHaveBeenCalledWith(process.env.PATH + '/check');
    })</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>Error: expect(received).toHaveBeenCalledWith(...expected)

Matcher error: received value must be a mock or spy function

Received has type:  string
Received has value: ""http://localhost:8000/check""</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/62844079/issue-unit-testing-this-function-in-node-with-node-fetch,"['javascript', 'node.js', 'unit-testing', 'fetch']",113,False,1,1
PHP Unit testing setting JWT token after login test completes,"<p>Hi I'm trying to set JWT token after the login test is complete in a global var and then extend all tests off of that class, now I'm not sure if I am even doing it right so any help is appreciated or documentation I could look up</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;?php
use Illuminate\Support\Facades\Config;

class AuthenticationTest extends TestCase {
    /**
     * @var string
     */
    public $token = '';

    /**
     * Register test user
     *
     * @return void
     */
    public function testRegister()
    {
        $this-&gt;json('post', '/auth/register', [
            'email' =&gt; Config::get('tests.email'),
            'password' =&gt; Config::get('tests.password'),
            'companyName' =&gt; Config::get('tests.companyName'),
            'firstname' =&gt; Config::get('tests.firstname'),
            'lastname' =&gt; Config::get('tests.lastname')
        ]);
        $this-&gt;assertEquals(200, $this-&gt;response-&gt;status());
        $this-&gt;seeJsonEquals([
            'message' =&gt; ""Registration successful, please confirm email to login"",
            'status'  =&gt; true,
        ]);
    }
    /**
     * Login test user
     *
     * @return void
     */
    public function testLogin()
    {
        $email = Config::get('tests.email');
        $password = Config::get('tests.password');
        $encryptedToken = base64_encode($email . "":"" . $password);
        $this-&gt;json('post', 'auth/login', ['token' =&gt; $encryptedToken]);
        $this-&gt;assertEquals(200, $this-&gt;response-&gt;status());
        $this-&gt;seeJsonStructure([
            'token',
            'refresh',
            'status'
        ]);
        $content = json_decode($this-&gt;response-&gt;getContent());
        $this-&gt;assertObjectHasAttribute('token', $content);
        $this-&gt;token = $content-&gt;token;
        $this-&gt;token;

    }
}
?&gt;</code></pre>
</div>
</div>
</p>
<p>The login test works as it should but the token isn't being set for other tests that extend off of this test case ad use $this-&gt;token to send the JWT token</p>
",https://stackoverflow.com/questions/63123561/php-unit-testing-setting-jwt-token-after-login-test-completes,"['php', 'unit-testing', 'lumen']",2061,True,1,1
How to mock rxjs/Websocket in angular for Unit Testing,"<p>I created a service which handles websocket communication with a server and Im trying to create unit tests for it but I cant find a way to mock <a href=""https://rxjs-dev.firebaseapp.com/api/webSocket/webSocket"" rel=""nofollow noreferrer"">rxjs/Websocket</a>.</p>

<p>I found a similar question <a href=""https://stackoverflow.com/questions/48584094/how-to-mock-rxjs-observable-websocket-for-unit-tests"">here</a>, but I cant use it with the new version of rxjs. Any help will be very helpful. </p>

<p>I could also, inject WebSocket as a service and mock the service in my test but it seems like a workaround and I prefer a better solution </p>

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

<p><code>socket.service.ts</code></p>

<pre class=""lang-js prettyprint-override""><code>//imports 

@Injectable()
export class SocketService {
  private baseUrl = ENV.WS_WORKSPACES_URL;

  socket$: WebSocketSubject&lt;any&gt;;

  constructor(
    private userService: UserService
  ) { }

  initSocket(): void {
    this.socket$ = webSocket(`${this.baseUrl}clusters`);
    const user = this.userService.getUser();

    if (user) {
      this.send({token: user.token});
    }
  }

  send(data: any): void {
    this.socket$.next(data);
  }
}
</code></pre>

<p><code>socket.service.spec.ts</code></p>

<pre class=""lang-js prettyprint-override""><code>//imports

describe(""SocketService"", () =&gt; {
  let service: SocketService;
  let userServiceSpy;
  let socket;
  const token = ""whatever"";

  beforeEach(() =&gt; {
    userServiceSpy = jasmine.createSpyObj(""UserService"", [""getUser""]);
    userServiceSpy.getUser.and.returnValue(null);
    socket = {next: jasmine.createSpy()};
    TestBed.configureTestingModule({
      providers: [
        {provide: UserService, useValue: userServiceSpy},
        SocketService
      ]
    });

    service = TestBed.inject(SocketService);

    socket = {} //this should be my mock
  });

  it(""should be created"", () =&gt; {
    expect(service).toBeTruthy();
  });

  it(""should open connection"", () =&gt; {
    service.initSocket();

    expect(socket.next).not.toHaveBeenCalled();
    expect(service.socket$).toBeDefined();
  });

  it(""should open connection with auth"", () =&gt; {
    const user = {token};
    userServiceSpy.getUser.and.returnValue(user);

    service.initSocket();
    expect(socket.next).toHaveBeenCalledWith(user);
  });

  it(""should send a message"", () =&gt; {
    service.initSocket();

    const message = {};
    service.send(message);

    expect(socket.next).toHaveBeenCalledWith(message);
  });
});
</code></pre>
",https://stackoverflow.com/questions/61325961/how-to-mock-rxjs-websocket-in-angular-for-unit-testing,"['angular', 'typescript', 'unit-testing', 'websocket', 'rxjs']",2157,True,1,1
Building a regex with UUID in between for unit testing?,"<p>I have a unique file name generator and struggling with the REGEX pattern. I want to assert within my unit test that the output string is valid:</p>

<pre><code>    private static final String FILE_NAME_DELIMITER = ""-"";
    private static final Supplier&lt;String&gt; getRandomUUID = () -&gt;
            UUID.randomUUID().toString().replace(FILE_NAME_DELIMITER, """");
</code></pre>

<p>This is how the UUID is generated. </p>

<p>This is the output string <code>filePrefix-yyyyMMdd-UUID.csv.gz</code></p>

<p>The regex I am looking for is <code>any_length_alpha_numeric_prefix-yyyyMMdd-UUID.extensionType.gz</code></p>

<ul>
<li>any_length_alpha_numeric_prefix = any letters or numbers of variable length</li>
<li>yyyyMMdd = this date format should exist in this location</li>
<li>UUID = the UUID generated from the above code</li>
<li>extensionType.gz = needs to be .csv.gz</li>
</ul>
",https://stackoverflow.com/questions/60715380/building-a-regex-with-uuid-in-between-for-unit-testing,"['java', 'regex']",271,True,1,1
Unit Testing Guice modules where one module installs another module,"<p>FYI, I am using Mockito and TestNg</p>

<p>I know how to test my logic in a Guice module by using <code>@Bind</code> to mock my external dependencies. </p>

<p>Here I have a module (say <code>Foo</code>) which has <code>install(new Bar());</code> in the <code>configure</code> method.</p>

<p>I can bind the various external dependencies in Foo, but I don't know how to deal with things in Bar.</p>

<p>ex)</p>

<pre><code>public class FooTest {

@Bind
@Mock
SomeExternalDependency1 someExternalDependency1;

@Bind
@Mock
SomeExternalDependency2 someExternalDependency2;

@BeforeClass
public void setup() {
    MockitoAnnotations.initiMocks(this);
    injector = Guice.createInjector(Modules.override(new Foo())with(
        new TestFooModule()), BoundFieldModule.of(this));
    injector.injectMembers(this);
}

@Test
public void testSomething() {
    //asssert something here
}

static class TestFooModule extends AbstractModule {
    @Override
    protected void configure() { }
}
</code></pre>

<p>But when I run this test, it complains about the external dependencies in <code>Bar</code>.</p>

<p>How do I test the Foo module without instantiating the Bar module?</p>

<p>For modules that don't install 'children' modules, this sort of testing works fine.</p>
",https://stackoverflow.com/questions/59900662/unit-testing-guice-modules-where-one-module-installs-another-module,"['java', 'testng', 'guice']",436,True,1,1
Unit testing go code with fatal flows in a loop,"<p>I am trying to add tests to a go cli code. 
The code has a lot of <code>log.Fatal</code> flows.
A bit of googling led me <a href=""https://blog.antoine-augusti.fr/2015/12/testing-an-os-exit-scenario-in-golang/"" rel=""nofollow noreferrer"">here</a>, so I followed it and got the tests working.
But, the way my tests are, they are setup to run the function being tested in a loop with different arguments.</p>

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

<pre><code>func TestGetXXX_FatalFlow(t *testing.T) {
    type args struct {
        varA string
        varB    string
    }
    tests := []struct {
        name     string
        args     args
        expected string
    }{
        {
            name:     ""Scenario 1: varA and varB both blank"",
            args:     args{},
            expected: ""message1"",
        },
        {
            name: ""Scenario 2: varA and varB not blank but invalid"",
            args: args{
                varA: ""somevalueA"",
                varB: ""somevalueB"",
            },
            expected: ""message2"",
        },
     }
    for _, tt := range tests {

        t.Run(tt.name, func(t *testing.T) {

            // Only run the failing part when a specific env variable is set
            if os.Getenv(""BE_CRASHER"") == ""1"" {
                GetXXX(tt.args.serverName, tt.args.address)
                return
            }

            // Start the actual test in a different subprocess
            cmd := exec.Command(os.Args[0], ""-test.run=TestGetXXX_FatalFlow"")
            cmd.Env = append(os.Environ(), ""BE_CRASHER=1"")
            stdout, _ := cmd.StderrPipe()
            if err := cmd.Start(); err != nil {
                t.Fatal(err)
            }

            // Check that the log fatal message is what we expected
            gotBytes, _ := ioutil.ReadAll(stdout)

            if !strings.Contains(string(gotBytes), tt.expected) {
                t.Fatalf(""Unexpected log message. Got %s but should contain %s"", strippedMsg, tt.expected)
            }

            // Check that the program exited
            cmd.Env = append(os.Environ(), ""BE_CRASHER=0"")
            err = cmd.Wait()
            if e, ok := err.(*exec.ExitError); !ok || e.Success() {
                t.Fatalf(""Process ran with err %v, want exit status 1"", err)
            }
        })
    }
}
</code></pre>

<p>The problem I am running into is , I feel my method GetXXX is never called with the second pair of input variables, somehow the method GetXXX keeps getting called with just the very first pair of argument in tests array.
I am not so sure if its because this spawns a child process.</p>

<p>Any help will be greatly appreciated.
Thanks</p>
",https://stackoverflow.com/questions/59569009/unit-testing-go-code-with-fatal-flows-in-a-loop,"['unit-testing', 'go']",567,True,1,1
useMutation onCompleted function is not invoked in react unit testing,"<p>This is how my component look likes.
Inside the component I am making a mutation and the handleOnComplete function is invoked once the mutation query is completed.
This code is working fine.</p>
<pre><code>function BrandingSearch() {
  const [searchList, setSearchList] = useState([]);

  const [searchQuery, { loading, error }] = useMutation(SEARCH_NO_INDEX, {
    onCompleted: handleOnComplete,
    variables: {
      rootType: 'branding',
      input: {}
    }
  });

  useEffect(() =&gt; {
    searchQuery();
  }, [])

  function handleOnComplete(res) {
    if (res &amp;&amp; res.searchNoIndex &amp;&amp; res.searchNoIndex.payload) {
      const payload = res.searchNoIndex.payload;
      const dataList = payload.map((item) =&gt; ({ ...item, id: item.name })); //Get requests require name instead of id
      setSearchList(dataList)
    }
  }


  const component = (
    &lt;CardSearch
      searchList={searchList}
    /&gt;
  )

  return component;
}

export default BrandingSearch;
</code></pre>
<p>Below is my testcase, useEffect is being invoked in the testcase, but handleOnComplete is not being invoked.
How can I fix this.</p>
<p>Testcase:</p>
<pre><code>describe('Test BrandingSearch', () =&gt; {
  it('', async () =&gt; {
    let deleteMutationCalled = false;
    const mocks = [
      {
        request: {
          query: SEARCH_NO_INDEX,
          variables: {
            rootType: 'branding',
            input: {}
          }
        },
        result: () =&gt; {
          deleteMutationCalled = true;
          return { data:{} };
        }
      }
    ];
    let wrapper;
    act(() =&gt; {
      wrapper = create(
        &lt;MockedProvider mocks={mocks} addTypename={false}&gt;
          &lt;BrandingSearch /&gt;
        &lt;/MockedProvider&gt;
      )
    })
    let component = wrapper.root;
    expect(deleteMutationCalled).toBe(true);
    //Expecting this to be set true, once the mutation is fired.
  })
});
</code></pre>
<p>Any help is appreciated.</p>
",https://stackoverflow.com/questions/64871929/usemutation-oncompleted-function-is-not-invoked-in-react-unit-testing,"['reactjs', 'apollo', 'react-apollo', 'react-test-renderer']",910,False,1,1
Unit testing null inputs at the cost of syntax errors?,"<p>I've inherited a project with some unit tests validating null inputs even if it was clearly stated in the arguments that they are mandatory.</p>
<p>Below is an example of how the production code went.</p>
<pre><code>class Pasta {
  getIngredient(name: string) {
    if(name == null) {
      throw &quot;need input&quot;
    }
    console.log(name)
  }
}

var p = new Pasta()
p.getIngredient(&quot;noodles&quot;)
p.getIngredient()
</code></pre>
<p>My primary concern is when doing this in typescript it will clearly state a syntax error because the function getIngredient() needs to have something inputted. I get that comprehensive testing is key but is this even essential? The fact that it raises an error at IDE level means that this shouldn't be done, but that code is tolerating errors for comprehensiveness and if this was Kotlin it wouldn't even have compiled.</p>
<p>I would think that the lines</p>
<pre><code>    if(name == null) {
      throw &quot;need input&quot;
    }
</code></pre>
<p>and its test are not even needed.</p>
<p>If you think it is needed, why so? Thank you.</p>
",https://stackoverflow.com/questions/62637776/unit-testing-null-inputs-at-the-cost-of-syntax-errors,"['typescript', 'unit-testing']",94,False,1,1
ASP.NET MVC 5 - Unit Testing Service that uses only Identity,"<p>I have this class, that, actually, only does operations on top of ASP.NET Identity.</p>

<pre><code> public class AuthenticationService : IAuthenticationService
    {
        private readonly ApplicationSignInManager _signInManager;
        private readonly ApplicationUserManager _userManager;
        private readonly IAuthenticationManager _authManager;
        private readonly HttpContextBase _context;

        public AuthenticationService(
            ApplicationSignInManager signInManager, 
            ApplicationUserManager userManager, 
            IAuthenticationManager authManager,
            HttpContextBase context)
        {
            _signInManager = signInManager;
            _userManager = userManager;
            _authManager = authManager;
            _context = context;
        }

        public async Task&lt;SignInStatus&gt; SignIn(string email, string password)
        {
            var result = await _signInManager.PasswordSignInAsync(email, password, true, shouldLockout: false);
            return result;
        }

        public async Task&lt;IdentityResult&gt; Register(string email, string password)
        {
            var user = new AppUser
            {
                UserName = email,
                Email = email,
            };

            var result = await _userManager.CreateAsync(user, password);

            return result;
        }

        public void SignOut()
        {
            _authManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        }

        public async Task&lt;IdentityResult&gt; ForgotPassword(string email, string newPassword)
        {
            var user = await _userManager.FindByEmailAsync(email);
            string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user.Id);
            var result = await _userManager.ResetPasswordAsync(user.Id, resetToken, newPassword);

            return result;
        }

        public async Task&lt;AppUser&gt; GetUserByEmail(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);
            return user;
        }

        public string GetLoggedInUserId()
        {
            if(_context.User.Identity.IsAuthenticated)
            {
                return _context.User.Identity.GetUserId();
            }
            return string.Empty;
        }
    }
</code></pre>

<p>I don't know if I'm injecting the right dependencies. But my question is: </p>

<p><strong>In a class like this one, what would make sense to unit test? Since most methods call methods related to Identity and only return the result.</strong> </p>

<p>The only test that it seems right to do is what happens when I try to get the ID of a user if no user is authenticated.</p>
",https://stackoverflow.com/questions/61461179/asp-net-mvc-5-unit-testing-service-that-uses-only-identity,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing']",91,True,1,1
React JS Jest Unit Testing Enzyme Set state for testing,"<p>I am writing a jest and enzyme unit testing for a react js component that uses Reflux.</p>

<p>I finally got the test to check the componentdidmount and check the component with the folloiwng</p>

<pre><code>**const onWillMount = jest.fn()
MyComponent.protoType.componentWillMount = onWillMount
mount(&lt;MyComponent/&gt;)
expect(onWillMount).toHaveBeenCalled(1)**
</code></pre>

<p>but I have state variables which are populated before it passed back the rendering</p>

<p>using jest and  enzyme, how to do set the state variable like this.state.myList</p>

<p>I am getting the jest error myList of null.</p>

<p>I tried MyComponent.prototype.setState but that did not work</p>

<p>Any help is great appreciated. Thanks</p>

<pre><code>export default class MyComponent extends Reflux.Component {
  constructor(props) {
    super(props)
    this.stores= ['myStore']
    this.storeKeys = ['myDataList']
  }

  compentDidMount() {
    myAction.getMyList()
  }

  render() {
    const hasData = !_.isNil(this.state.myList)
  }
}
</code></pre>
",https://stackoverflow.com/questions/62197053/react-js-jest-unit-testing-enzyme-set-state-for-testing,"['reactjs', 'jestjs', 'enzyme']",227,False,1,0
getOrAwaitValue() method returned IllegalArgumentException when unit testing viewmodel in kotlin,"<p>I am getting the IllegalArgumentException when i run my <strong>PatientViewModelTest</strong> class, i struggled a lot to fix to problem on my own but failed to solve it. Actually i have no idea about why this error is occurring because i'm new in Kotlin as well as Unit Testing. This is my first application in kotlin. Please help me.</p>
<p>Thanks</p>
<p>PatientViewModel.kt</p>
<pre><code>import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.*
import com.aitriage.data.Patient
import com.aitriage.data.Staff
import com.aitriage.other.Event
import com.aitriage.other.Resource
import com.aitriage.repository.MainRepository
import kotlinx.coroutines.launch

class PatientViewModel @ViewModelInject constructor(private val mMainRepository: MainRepository): ViewModel()
{
    val patientList = mMainRepository.getAllPatients()

    private val _insertPatientStatus = MutableLiveData&lt;Event&lt;Resource&lt;Patient&gt;&gt;&gt;()

    val insertPatientStatus : LiveData&lt;Event&lt;Resource&lt;Patient&gt;&gt;&gt; = _insertPatientStatus

    fun insertPatientIntoDB(patient: Patient) = viewModelScope.launch {

        mMainRepository.insertPatient(patient)
    }

    fun insertPatient(age: String, createdAt: String, gender: String,hopitalId:String, patientId: String,race: String, sortKey: String, status: String){
        
        if (age.isEmpty() || createdAt.isEmpty() || gender.isEmpty() || hopitalId.isEmpty() || patientId.isEmpty() || race.isEmpty() || sortKey.isEmpty() || status.isEmpty())
        {
            _insertPatientStatus.postValue(Event(Resource.error(null,&quot;The fields can't be empty&quot;)))
            return
        }


        val staff = Staff(&quot;Himanshu&quot;)
        val patient = Patient(0,staff,age,createdAt, gender,hopitalId,patientId,race,sortKey,status)
        insertPatientIntoDB(patient)
        _insertPatientStatus.postValue(Event(Resource.success(patient)))


    }

 }
</code></pre>
<p>PatientViewModelTest.kt</p>
<pre><code>import android.os.Build
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.aitriage.MainCoroutineRule
import com.aitriage.getOrAwaitValue
import com.aitriage.other.Status
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito
import org.robolectric.annotation.Config

@Config(sdk = [Build.VERSION_CODES.O_MR1])
@ExperimentalCoroutinesApi
class PatientViewModelTest {
    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    var mainCoroutineRule = MainCoroutineRule()

    private lateinit var viewModel: PatientViewModel

    @Before
    fun setup() {
        viewModel = Mockito.mock(PatientViewModel::class.java)
    }

    @Test
    fun `insert patient with empty field, returns error`() {
        viewModel.insertPatient(&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with age is empty, returns error`() {
        viewModel.insertPatient(&quot;&quot;, &quot;ds&quot;, &quot;ds&quot;, &quot;gfdg&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with date is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;&quot;, &quot;ds&quot;, &quot;gfdg&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with gender is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;&quot;, &quot;gfdg&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with hopital id is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with patient id is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with race is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with sortkey is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with status is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;fd&quot;, &quot;&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()

        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with valid input, returns success`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()

        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.SUCCESS)
    }

    @Test
    fun add()
    {
        val actual = 4

        assertThat(actual).isEqualTo(4)
    }
}
</code></pre>
<p>LiveDataTestUtilClass.kt</p>
<pre><code>import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun &lt;T&gt; LiveData&lt;T&gt;.getOrAwaitValue(
        time: Long = 2,
        timeUnit: TimeUnit = TimeUnit.SECONDS,
        afterObserve: () -&gt; Unit = {}
): T {
    var data: T? = null
    val latch = CountDownLatch(1)
    val observer = object : Observer&lt;T&gt; {
        override fun onChanged(o: T?) {
            data = o
            latch.countDown()
            this@getOrAwaitValue.removeObserver(this)
        }
    }
    this.observeForever(observer)

    try {
        afterObserve.invoke()

        // Don't wait indefinitely if the LiveData is not set.
        if (!latch.await(time, timeUnit)) {
            throw TimeoutException(&quot;LiveData value was never set.&quot;)
        }

    } finally {
        this.removeObserver(observer)
    }

    @Suppress(&quot;UNCHECKED_CAST&quot;)
    return data as T
}
</code></pre>
<p>MainRepository.kt</p>
<pre><code>import com.aitriage.data.Help
import com.aitriage.data.input.ForgotPwdInput
import com.aitriage.data.input.LoginInput
import com.aitriage.data.Patient
import com.aitriage.database.HelpDao
import com.aitriage.database.PatientDao
import com.aitriage.network.ApiHelperImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class MainRepository @Inject constructor(
    private val patientDao: PatientDao,
    private val helpDao: HelpDao,
    private val apiHelper: ApiHelperImpl
) {

    suspend fun login(body: LoginInput) = apiHelper.login(body)
    suspend fun forgotPassword(body: ForgotPwdInput) = apiHelper.forgotPassword(body)

    fun getAllPatients() = patientDao.getAllPatients()


    suspend fun insertPatient(patient: Patient)
    {
        patientDao.insertPatient(patient)
    }


    fun getHelp() = helpDao.getHelp(1)

    suspend fun saveHelp(help: Help) = helpDao.saveHelp(help)

    suspend fun getRemoteHelp(authToken: String) = apiHelper.getHelp(authToken)
}
</code></pre>
<p>This is the actual error i am getting. Please have a look at the screenshot.
<a href=""https://i.stack.imgur.com/0yx4J.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
",https://stackoverflow.com/questions/64555380/getorawaitvalue-method-returned-illegalargumentexception-when-unit-testing-vie,"['java', 'android', 'unit-testing', 'kotlin', 'android-viewmodel']",436,False,1,0
How to create GitHub Actions for unit testing in .NET projects?,"<p>I use NUnit framework to test my .NET project. I want to run my tests via GitHub Actions. </p>

<p>What should be included in the assembly of my project? Maybe there are some standard examples?</p>
",https://stackoverflow.com/questions/59742930/how-to-create-github-actions-for-unit-testing-in-net-projects,"['c#', 'unit-testing', 'github', 'nunit', 'github-actions']",6208,True,7,1
Unit testing VueJs with Jest and Typescript - components not mounted,"<p>We are building an app with VueJs. We have previous experience with Angular unit testing with Jasmine and karma, so we decided to use Typescript for our VueJs app.</p>

<p>Currently I have written very simple specs for components, but it seems like the components are not getting mounted.</p>

<p>Here is an example of a <strong>component</strong>:</p>

<pre class=""lang-js prettyprint-override""><code>export default class TableOverview extends Vue {
  public mounted() {
    console.log(""mounted"");
  }
}
</code></pre>

<p>Here is my <strong>spec</strong>:</p>

<pre class=""lang-js prettyprint-override""><code>describe(""table-overview.vue"", () =&gt; {
  it(""logs mounted"", () =&gt; {
    const wrapper = mount(TableOverview);

    expect(wrapper).toBeDefined();
  });
});
</code></pre>

<p>I don't see anything in the console log.</p>

<p>What am I missing? This project was set with <strong>Vue CLI v4.3.1</strong></p>

<p>Here is the Vue <strong>info</strong>:</p>

<pre class=""lang-sh prettyprint-override""><code>  System:
    OS: Windows 10 10.0.18363
    CPU: (8) x64 Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz
  Binaries:
    Node: 8.11.3 - C:\Program Files\nodejs\node.EXE
    Yarn: Not Found
    npm: 5.6.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: 44.18362.449.0
  npmPackages:
    @vue/babel-helper-vue-jsx-merge-props:  1.0.0
    @vue/babel-plugin-transform-vue-jsx:  1.1.2
    @vue/babel-preset-app:  4.2.3
    @vue/babel-preset-jsx:  1.1.2
    @vue/babel-sugar-functional-vue:  1.1.2
    @vue/babel-sugar-inject-h:  1.1.2
    @vue/babel-sugar-v-model:  1.1.2
    @vue/babel-sugar-v-on:  1.1.2
    @vue/cli-overlay:  4.2.3
    @vue/cli-plugin-babel: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-eslint: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-router:  4.2.3
    @vue/cli-plugin-typescript: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-unit-jest: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-vuex: ~4.2.0 =&gt; 4.2.3
    @vue/cli-service: ~4.2.0 =&gt; 4.2.3
    @vue/cli-shared-utils:  4.2.3
    @vue/component-compiler-utils:  3.1.1
    @vue/eslint-config-prettier: ^6.0.0 =&gt; 6.0.0
    @vue/eslint-config-typescript: ^5.0.1 =&gt; 5.0.2
    @vue/preload-webpack-plugin:  1.1.1
    @vue/test-utils: 1.0.0-beta.31 =&gt; 1.0.0-beta.31
    @vue/web-component-wrapper:  1.2.0
    eslint-plugin-vue: ^6.1.2 =&gt; 6.2.2
    jest-serializer-vue:  2.0.2
    typescript: ~3.7.5 =&gt; 3.7.5
    vue: ^2.6.11 =&gt; 2.6.11
    vue-class-component:  7.2.3
    vue-eslint-parser:  7.0.0
    vue-hot-reload-api:  2.3.4
    vue-jest:  3.0.5
    vue-loader:  15.9.1
    vue-property-decorator: ^8.3.0 =&gt; 8.4.1
    vue-style-loader:  4.1.2
    vue-template-compiler: ^2.6.11 =&gt; 2.6.11
    vue-template-es2015-compiler:  1.9.1
    vuetify: ^2.2.25 =&gt; 2.2.25
    vuetify-loader: ^1.4.3 =&gt; 1.4.3
    vuex: ^3.1.2 =&gt; 3.1.3
    vuex-class: ^0.3.2 =&gt; 0.3.2
    vuex-module-decorators: ^0.17.0 =&gt; 0.17.0
  npmGlobalPackages:
    @vue/cli: Not Found
</code></pre>
",https://stackoverflow.com/questions/61894798/unit-testing-vuejs-with-jest-and-typescript-components-not-mounted,"['typescript', 'unit-testing', 'vue.js', 'jestjs', 'vue-component']",1674,True,1,1
How to get MvcResult when unit testing POST with MultipartFile,"<p>When i'm testing just trivial POST-requests, i can get MvcResult and get something from it:</p>
<pre><code>MvcResult result = mockMvc.perform(post(&quot;/api/register&quot;)
                .contentType(MEDIA_TYPE_JSON_UTF8)
                .content(new Gson().toJson(request)))
                .andExpect(status().isCreated())
                .andReturn();
Long tempId = Long.valueOf(JsonPath.read(result.getResponse().getContentAsString(), &quot;$.id&quot;).toString());
</code></pre>
<p>But when i'm using MultipartFile, i can only use MockMvcRequestBuilders and only check expectations.</p>
<pre><code>MockMultipartFile filePart = new MockMultipartFile(
                &quot;file&quot;,
                &quot;file.jpg&quot;,
                &quot;image/jpeg&quot;, file);
mockMvc.perform(MockMvcRequestBuilders.multipart(&quot;/api/loadfile&quot;)
                .file(filePart)
                .param(&quot;json&quot;, json))
                .andExpect(status().isOk()); 
</code></pre>
<p>How can i get MvcResult with multipart POST after request?</p>
",https://stackoverflow.com/questions/62838203/how-to-get-mvcresult-when-unit-testing-post-with-multipartfile,"['spring-boot', 'multipart', 'spring-test', 'mockmvc']",358,True,1,1
"Nova Laravel Unit Testing Expecting Return 201, But Return 403","<p>I'm gonna make a Unit Testing for my resource.
Here my testing function below :</p>
<pre><code>public function testCreateMyResource()
{
    $user = factory(\App\User::class)-&gt;states('admin')-&gt;create();
    $this-&gt;actingAs($user);
    $data = [
        'Field' =&gt; &quot;Example&quot;,
    ];

    $response = $this-&gt;actingAs($user)-&gt;postJson('/nova-api/my-resource?editing=true&amp;editMode=create',$data);
    $response-&gt;assertStatus(201);
    $response-&gt;assertJson(['status' =&gt; true]);
    $response-&gt;assertJson(['message' =&gt; &quot;Created!&quot;]);

}
</code></pre>
<p>But it was return 403.
I expected to return 201 as I login normally to Nova dashboard and create new record in the form.
It seems like forbidden to access the route inside Testing Class.
Is there anyway to access the route ? Please any body help me to solve this.</p>
",https://stackoverflow.com/questions/64640387/nova-laravel-unit-testing-expecting-return-201-but-return-403,"['laravel', 'unit-testing', 'phpunit', 'laravel-nova', 'laravel-unit-test']",180,False,1,0
ionic unit testing - the pipe &#39;date&#39; could not be found,"<p>I have a component that uses pipe date in template. It works in emulator and browser.</p>
<p>When executing unit tests - I get a</p>
<p>Error: The pipe 'date' could not be found!</p>
<p>For all test cases within that component.  Using latest ionic, angular, jasmine, karma, etc.</p>
<p>app.module.ts</p>
<pre><code>import { CommonModule, DatePipe } from '@angular/common';

@NgModule({
declarations: [AppComponent, DatePipe], 
imports: [ Common Module ],
providers: [CommonModule],
exports: [CommonModule]

...
</code></pre>
<p>users.page.spec.ts</p>
<pre><code>import { CommonModule, DatePipe } from '@angular/common';
describe('UsersPage', () =&gt; {
  let component: UsersPage;
  let fixture: ComponentFixture&lt;UsersPage&gt;;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ CommonModule],
      declarations:[DatePipe],
      schemas: [ NO_ERRORS_SCHEMA ],
      providers: [
        { provide: UserInfoService, useClass: MockUserInfoService },
        { provide: TaskHistoryService, useClass: MockTaskHistoryService },
        { provide: CommonModule, useClass: CommonModule}
      ],
    }).compileComponents();
    

    fixture = TestBed.createComponent(UsersPage);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
</code></pre>
<p>Error:</p>
<pre><code>Error: The pipe 'date' could not be found!
    at getPipeDef$1 (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:24393:1)
    at ɵɵpipe (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:24356:1)
    at UsersPage_Template (ng:///UsersPage.js:115:9)
    at executeTemplate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:7329:1)
    at renderView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:7138:1)
    at renderComponent (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:8382:1)
    at renderChildComponents (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:6997:1)
    at renderView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:7163:1)
    at ComponentFactory$1.create (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:22291:1)
    at initComponent (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:1983:1)
</code></pre>
<p>I also have CommonModule inside of providers for @Component of the component using the date pipe. It feels like I'm missing something simple. I've read through similar questions (for custom pipes) and tried to apply same fixes - so far nothing worked. Thanks in advance.</p>
<p>Lastly, some version numbers:</p>
<pre><code>Angular CLI: 10.0.3
Node: 14.5.0
OS: darwin x64

Angular: 10.0.4
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: &lt;error&gt;

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.1000.3
@angular-devkit/build-angular     0.1000.3
@angular-devkit/build-optimizer   0.1000.3
@angular-devkit/build-webpack     0.1000.3
@angular-devkit/core              10.0.3
@angular-devkit/schematics        10.0.3
@angular/cli                      10.0.3
@ngtools/webpack                  10.0.3
@schematics/angular               9.1.7
@schematics/update                0.1000.3
rxjs                              6.6.0
typescript                        3.9.7
webpack                           4.43.0
</code></pre>
",https://stackoverflow.com/questions/63439413/ionic-unit-testing-the-pipe-date-could-not-be-found,"['angular', 'unit-testing', 'ionic-framework']",1553,True,1,2
How to mock a class in C# unit testing project,"<p>I have a class I want to moq :</p>

<pre><code>    public class ODriver
    {
        public int DriverId { get; set; }      

        public virtual bool CanDrive()
        {
            return false;
        }
    }
</code></pre>

<p>She is used like this in the method I want to test :</p>

<pre><code>    var driver = new ODriver();

    // Must be false except in the unit test
    var canDrive = driver.CanDrive();
</code></pre>

<p>I mock the method like this in my unit test :</p>

<pre><code>  var driverMoq = new Mock&lt;ODriver&gt;();
  driverMoq.Setup(d =&gt; d.CanDrive()).Returns(true);
</code></pre>

<p>When the test is runned, the result of the CanDrive method returns false. What do I have to do in order to have the mocked class used ?</p>

<p>Thank you all !</p>
",https://stackoverflow.com/questions/62444851/how-to-mock-a-class-in-c-unit-testing-project,"['c#', 'unit-testing', 'mocking']",783,False,0,1
Unit testing the intercept function in an Angular HTTP interceptor,"<p>I've written an Angular 9 HTTP Interceptor, and I would like to unit test the intercept function in relative isolation. From what I've seen on <a href=""https://stackoverflow.com/questions/46225164/unit-testing-httpinterceptor-from-angular-4"">StackOverflow already</a>, people are suggesting to make fake HTTP requests or <a href=""https://stackoverflow.com/a/49176499/3356518"">return a basic request</a>, which isn't working for me as I use the .pipe method (<em>TypeError: next.handle(...).pipe is not a function</em>) </p>

<p>Here's my intercept function, what would you suggest to unit test this function please?</p>

<pre><code>intercept(request: HttpRequest &lt; unknown &gt;, next: HttpHandler): Observable &lt; HttpEvent &lt; unknown &gt;&gt; {
  this.loadingService.show();
  return next.handle(request).pipe(
    catchError((error: HttpErrorResponse) =&gt; {
      if (error.status !== 401) {
        this.snackBar.open(""There was an error when making your request! "" + error.message, 'Okay, I will refresh the page', { duration: 10000 });
      }
      return throwError(error);
    }),
    finalize(
      () =&gt; {
        this.loadingService.hide()
      }
    )
  );
}
</code></pre>
",https://stackoverflow.com/questions/61057827/unit-testing-the-intercept-function-in-an-angular-http-interceptor,"['angular', 'angular-httpclient', 'angular-httpclient-interceptors']",956,True,0,1
Unit Testing a nodejs function using `fs` wrapped in `promisify`,"<p>In the following code I have a function that is looking for a file in the file system based on a provided configuration.</p>

<pre><code>const fs = require('fs');
const { promisify } = require('util');

const lstat = promisify(fs.lstat);

async function doSomething(someFilePath) {
    try {
       const stats = await lstat(someFilePath);
    } catch (err) {
       throw err;
    }

    // do something with the file stats
}

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

<p>From here I'm trying to test the <code>doSomething</code> function but it fails because the file paths I'm providing don't actually exist. The below code <em>was</em> working when I was using <code>lstatSync</code> without <code>promisify</code>.</p>

<pre><code>const fs = require('fs');
const sinon = require('sinon');

const doSomething = require('./doSomething');

describe('The test', function() {

    let lstatStub;

    beforeEach(function() {
        lstatStub = sinon.stub(fs, 'lstatSync');
    });

    afterEach(function() { sinon.restore() });

    it('should pass', async function() {
        lstatStub.withArgs('image.jpg').returns({
            isFile: () =&gt; true,
            isDirectory: () =&gt; false,
        });

        assert(await doSomething('image.jpg')).ok();
    });

})
</code></pre>

<p>It now fails because <code>Error: ENOENT: no such file or directory, lstat 'image.jpg'</code>. I've tried wrapping the stub in <code>promisify</code> or exporting the <code>promisify</code>ed functions into the test to stub. Both didn't work.</p>

<p>How do I stub a <code>promisify</code>ed <code>fs</code> method?</p>
",https://stackoverflow.com/questions/61412987/unit-testing-a-nodejs-function-using-fs-wrapped-in-promisify,"['node.js', 'unit-testing', 'sinon', 'fs', 'node-promisify']",558,False,0,1
how to create an object of CellInfo for unit testing?,"<p>I am writing unit test case, What I can't understand is how can I make a dummy object of CellinfoGsm or of any technology and test my code from it. I did read the documentation and the base class of CellInfo but I can't understand how to use the Creator, Can anyone give me an example of how to make my own object with my own values for testing purposes. Any help would be highly appreciated.</p>
",https://stackoverflow.com/questions/62787859/how-to-create-an-object-of-cellinfo-for-unit-testing,"['android', 'unit-testing', 'parcelable', 'cellinfo', 'cellinfogsm']",78,False,0,1
Problem setting up VS2019 Community for unit testing a dll,"<p>I am using vs 2019 Community and have created a Class Library (.NET Framework) project named TestDLL.  </p>

<p>The project contains a single file ""TestDLL.cs"" which has TestDLL as a namespace, a public class named MyDll and a single method</p>

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

namespace TestDLL 
{ 
    public class MyDLL 
    { 
        static bool Opposite(bool input) 
        { 
            return !input; 
        } 
    }
}
</code></pre>

<p>To the solution I added Unit Test Project (.NET Framework) named UnitTest, added TinyLib_dll.dll as a reference, and created the very simple test.</p>

<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            bool start = true;
            bool result = MyDLL.Opposite(start);
            Assert.AreNotEqual(start, result, ""MyDll.Opposite failed"");
        }
    }
}
</code></pre>

<p>When I try to run the test, the dll file compiles successfully, but the UnitTest fails with ""Error  CS0103  The name 'MyDLL' does not exist in the current context  UnitTest"".  </p>

<p>It appears that although I have referenced the dll as a reference it is not being loaded into the test project.
Can someone help me out?</p>
",https://stackoverflow.com/questions/60801849/problem-setting-up-vs2019-community-for-unit-testing-a-dll,"['c#', 'unit-testing', 'dll']",46,False,0,2
Unit testing the service itself in Angular with SnackBar call,"<p>I am relatively new to Angular Material unit testing and also to Service unit testing.
I created a service for my application with which I can call a Material SnackBar open function and passing a message parameter through. It's working really fine in every component when it needed but the unit testing for it is something... terrible to me.</p>

<pre><code>import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarRef, MatSnackBarConfig } from '@angular/material/snack-bar';

@Injectable({
  providedIn: 'root',
})
export class NotificationService {
  private snackBarConfig: MatSnackBarConfig;
  private snackBarRef: MatSnackBarRef&lt;any&gt;;
  private snackBarAutoHide = '5000';

  constructor(private sb: MatSnackBar) {}

  openSnackBar(message) {
    this.snackBarConfig = new MatSnackBarConfig();
    this.snackBarConfig.duration = parseInt(this.snackBarAutoHide, 0);
    this.sb.open(message, 'Dismiss', this.snackBarConfig);
  }
}
</code></pre>

<p>And the so-called test specification file is this:</p>

<pre><code>import { Overlay } from '@angular/cdk/overlay';
import { TestBed } from '@angular/core/testing';
import { MatSnackBar } from '@angular/material/snack-bar';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator';
import { NotificationService } from './notification-service';

describe('NotificationService testing:', () =&gt; {
  let spectator: SpectatorService&lt;NotificationService&gt;;
  const createService = createServiceFactory({
    service: NotificationService,
    providers: [MatSnackBar, Overlay],
    entryComponents: [],
    mocks: [NotificationService],
  });

  beforeEach(() =&gt; (spectator = createService()));

  it('should openSnackBar() be known as function', () =&gt; {
    expect(typeof spectator.service.openSnackBar).toEqual('function');
  });

  it('should be created', () =&gt; {
    const dateService = spectator.inject(NotificationService);
    spyOn(spectator.service, 'openSnackBar');
    dateService.openSnackBar('Test');
    expect(spectator.service.openSnackBar).toHaveBeenCalledWith('Test');
  });
});
</code></pre>

<p>My question would be the followings:</p>

<ol>
<li>Why my karma coverage says the openSnackBar(message) method is not
tested? I mean at least I testing if it is a function or not.</li>
<li>How can I actually test a service like this on its own?</li>
</ol>

<p>Thank you in advance. </p>
",https://stackoverflow.com/questions/61681785/unit-testing-the-service-itself-in-angular-with-snackbar-call,"['angular', 'unit-testing', 'karma-jasmine', 'angular9', 'spectator']",1362,True,0,1
Minimal mock for unit testing angular Router and CanActivate guard,"<pre class=""lang-js prettyprint-override""><code>import {Router, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree} from '@angular/router';

@Injectable({provideIn: 'root'})
export class FooGuard implements CanActivate {
  constructor (private readonly router: Router) {}

  canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise&lt;UrlTree&gt; {
    const xxx = myMagic(next); // irrelevant app logic that depends on next url only

    return (async () =&gt; this.router.parseUrl(xxx));
  }
}
</code></pre>

<p>Trying to find an example of testing code for this piece without a page of extra boilerplate. Hopefully can get something closer to 5-6 lines of code per mock. Need: </p>

<ul>
<li>Mock for <code>Router</code></li>
<li>Mock for <code>ActivatedSnapshot</code></li>
</ul>
",https://stackoverflow.com/questions/59852259/minimal-mock-for-unit-testing-angular-router-and-canactivate-guard,"['angular', 'unit-testing', 'angular-router', 'angular-router-guards']",2491,True,-1,1
How to mock AWS amplify methods in Angular unit testing,"<p>I am using <a href=""https://aws.amazon.com/cognito/"" rel=""nofollow noreferrer"">AWS cognito</a>, <a href=""https://aws.amazon.com/amplify/"" rel=""nofollow noreferrer"">Amplify</a> and <a href=""https://angular.io/"" rel=""nofollow noreferrer"">Angular 10</a>.</p>
<p>I want a navbar not to be rendered if a user is not logged in:</p>
<p>app.html:</p>
<pre><code>&lt;ng-container *ngIf=&quot;isLoggedIn&quot;&gt;
  &lt;navbar&gt;&lt;/navbar&gt;
&lt;/ng-container&gt;
</code></pre>
<p>app.ts:</p>
<pre><code>constructor() {
  this.checkIfLoggedIn();
}

checkIfLoggedIn() {
  Auth.currentUserInfo().then((userData) =&gt; {
    if (userData) {
      this.isLoggedIn = true;
    }
  });
}
</code></pre>
<p>This works. However, my unit tests (<a href=""https://karma-runner.github.io/latest/index.html"" rel=""nofollow noreferrer"">Karma</a>/<a href=""https://jasmine.github.io/"" rel=""nofollow noreferrer"">Jasmine</a>) throw an error:</p>
<pre><code>Error: Amplify has not been configured correctly.
        The configuration object is missing required auth properties.
</code></pre>
<p>This is because I don't know hot to mock <code>Auth.currentUserInfo.then</code> correctly (despite reading various posts about it like <a href=""https://stackoverflow.com/questions/59215244/how-to-mock-aws-amplify-library-in-angular"">this</a> or <a href=""https://stackoverflow.com/questions/60454057/how-do-i-properly-mock-amplify-for-unit-testing-in-jasmine"">that</a>).</p>
<p>Attempts:</p>
<p><strong>1) SpyOn</strong></p>
<p>I thought it would be something like <code>spyOn(Auth, 'currentUserInfo').and.returnValue(Promise.resolve(true));</code></p>
<p><strong>2) Mocking <code>Auth</code> in providers</strong></p>
<p>like suggested in the <a href=""https://stackoverflow.com/questions/65250583/how-to-mock-aws-amplify-methods-in-angular-unit-testing?noredirect=1#comment115356708_65250583"">comments</a>.</p>
<pre><code>import { Auth } from 'aws-amplify';

beforeEach(async () =&gt; {
  await TestBed.configureTestingModule({
    declarations: [AppComponent],
    providers: [
      {
        provide: Auth,
        useValue: { currentUserInfo: () =&gt; Promise.resolve('hello') },
      },
    ],
  }).compileComponents();
}
</code></pre>
<p>Unfortunately they don't make the error message go away.</p>
",https://stackoverflow.com/questions/65250583/how-to-mock-aws-amplify-methods-in-angular-unit-testing,"['angular', 'unit-testing', 'karma-runner', 'aws-amplify', 'aws-amplify-sdk-js']",1528,True,1,1
How to use e2e or unit testing with nativescript-vue?,"<p>How to use e2e or unit testing with nativescript-vue?</p>
<p>Would you please describe a <a href=""https://github.com/wix/Detox/blob/master/docs/Introduction.GettingStarted.md"" rel=""nofollow noreferrer"">Getting Started</a> kind of guide?</p>
<p>Is there any tested <strong>testing method</strong> with nativescript 7 ?</p>
<p>Does <a href=""https://appium.io/"" rel=""nofollow noreferrer"">appium</a> or <a href=""https://github.com/wix/Detox"" rel=""nofollow noreferrer"">detox</a> really work?</p>
<p>Is it possible to update <a href=""https://github.com/rigor789/ui-tested-nsvue-app"" rel=""nofollow noreferrer"">ui-tested-nsvue-ap</a>p somehow?</p>
",https://stackoverflow.com/questions/64097583/how-to-use-e2e-or-unit-testing-with-nativescript-vue,"['nativescript', 'appium', 'nativescript-vue', 'detox']",144,True,0,1
Unit testing that localStorage.getItem has been called on document ready?,"<p>I have the following code, whereby a localStorage item is checked on document ready. If a localStorage item has not been set yet, it's set: </p>

<pre><code>$(document).ready(function () {             
   checkIfLoginTracked();                
})

function checkIfLoginTracked() {
   if (localStorage.getItem(""loginHasBeenTracked"") === null) {
         localStorage.setItem(""loginHasBeenTracked"", true);
   }
}
</code></pre>

<p>I am struggling to know how best to unit test this however? </p>

<p>I am using Qunit and Sinon and so far have been trying the following in the test block (spying on the local storage method and checking it's been called with the correct argument) </p>

<pre><code>var spy = sinon.spy(window.localStorage, ""getItem"");
assert.ok(spy.calledWith(""loginHasBeenTracked"", true));
</code></pre>

<p>This is returning false and saying not called. I don't know if I am missing something obvious, or if it's perhaps because it's on <code>document.ready</code> that it's difficult to test? Can anyone please point me in the right direction? </p>
",https://stackoverflow.com/questions/59840852/unit-testing-that-localstorage-getitem-has-been-called-on-document-ready,"['javascript', 'dom', 'storage', 'sinon', 'qunit']",927,False,0,1
Unit testing a specific MongoDb FilterDefintion in C# with Moq,"<p>Trying to unit test the following MongoDb update function in C#.</p>

<pre><code>var update = Builders&lt;InvestorMongoDao&gt;.Update
      .Set(x =&gt; x.EmailAddress, command.EmailAddress);

await this.myDatabase.Users
.UpdateOneAsync(x =&gt; x.UserId == userId), update)
.ConfigureAwait(false);
</code></pre>

<p>I can easily check whether this function is called with a generic filter:</p>

<pre><code>this.mockCollection
    .Verify(x =&gt; x.UpdateOneAsync(It.IsAny&lt;FilterDefinition&lt;MyDao&gt;&gt;(), 
        It.IsAny&lt;UpdateDefinition&lt;MyDao&gt;&gt;(), 
        It.IsAny&lt;UpdateOptions&gt;(), 
        It.IsAny&lt;CancellationToken&gt;()));
</code></pre>

<p>However, I want to try and verify that it's being called with the expected parameter. I cannot seem to find a way to extract the parameter I want to check from FilterDefinition. I have tried this:</p>

<pre><code>var foo = Builders&lt;MyDao&gt;.Filter.Eq(""UserId"", expectedUserId);
this.mockCollection
    .Verify(x =&gt; x.UpdateOneAsync(It.Is&lt;FilterDefinition&lt;MyDao&gt;&gt;(a =&gt; a == foo), 
        It.IsAny&lt;UpdateDefinition&lt;MyDao&gt;&gt;(), 
        It.IsAny&lt;UpdateOptions&gt;(), 
        It.IsAny&lt;CancellationToken&gt;()));
</code></pre>

<p>But the test states the invocation is not performed. What am I doing wrong?</p>
",https://stackoverflow.com/questions/60262266/unit-testing-a-specific-mongodb-filterdefintion-in-c-with-moq,"['c#', 'mongodb', 'unit-testing', 'moq']",1435,True,0,1
How to unit test a service in angular unit testing?,"<p>I have a function in my service as follows,,</p>

<pre><code> exportPayGapDetails(filterObject: PayGapDetailFilter): void {
  const url = `${this.payGapDetailExportUrls[filterObject.type]}`;

  this.http
  .post&lt;PollInitResponse&gt;(
    `/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222`,
    {}
  )
  .subscribe(
    res =&gt; {
      if (res) {
        this.pollingServiceService.pollRequest(
          `/adpi/rest/v2/sb/pe/v1/export/1/status`,
          this.ReadytoDownload.bind(this),
          this.PollCondition.bind(this)
        );
      } else {
        this.showToastMessage('error found);
      }
    },
    () =&gt; {
      this.showToastMessage('error found'

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

<p>My test case,</p>

<pre><code>  it('should call gender pay gap details init api when we pass type as GENDER_GAP on Export', fakeAsync(() =&gt; {
  spyOn(pollingService, 'pollRequest').and.callThrough();
  payGapDetailsService.exportPayGapDetails(filterDetailObject);
  // pollingService.pollSubscriptions.unsubscribe();
  tick();
  const req = http.expectOne(
    request =&gt;
      request.method === 'POST' &amp;&amp;
      request.url === '/adpi/rest/v2/sb/pe/v1/export/1/getStatusValue/222'
  );
  req.flush(exportInitSucessResponse);
  http.verify();
}));
</code></pre>

<p>When I run it throws me error,</p>

<pre><code>Error: Expected no open requests, found 1: GET /adpi/rest/v2/sb/pe/v1/export/1/status
</code></pre>

<p>I understood that it is realated to  this.pollingServiceService.pollRequest( this function, but I am not sure how to resolve it.Can anyone please suggest me help.Thanks.</p>
",https://stackoverflow.com/questions/60924534/how-to-unit-test-a-service-in-angular-unit-testing,"['javascript', 'angular', 'jasmine', 'karma-jasmine', 'angular-unit-test']",62,False,0,1
Angular 9 Unit Testing ngOnInit with a setTimeOut inside service,"<p>I have a component with a setTimeOut function inside service. To write unit test cases for that I'm using tick and fakeAsync to setTimeOut. But, it's not getting executed. even i am qurious about how can i write test case for <strong>window['MyAirtelAppReact']</strong> inside if condition.</p>

<p>And i have tried out using <strong>flushMicrotasks</strong> will clear all of the microtasks that are currently in the queue, but not sure if this is the way to do it?
How would I write a unit test to test this? </p>

<blockquote>
  <p>Component code:</p>
</blockquote>

<pre class=""lang-js prettyprint-override""><code>
constructor(
    private dataService: DataService,
    private loadinSrvc: LoadingService,
    private router: Router,
    private toastr: ToastrService,
    public dialog: MatDialog
  ){
  if (window['MyAirtelAppReact'] !== undefined) {
    if (
      window['MyAirtelAppReact'] &amp;&amp;
      window['MyAirtelAppReact'].getParameters
    ) {
      const deviceInfoString = window['MyAirtelAppReact'].getParameters();
      const deviceInfo = JSON.parse(deviceInfoString);
      this.dataService.setAppDetails(deviceInfo);
    }
  } else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
    window['webkit'].messageHandlers.getParameters.postMessage('');
  } else {
    const deviceInfo = {
      channel: 'web',
      deviceId: GLOBAL_PROPERTIES.DEVICE_ID,
    };
    this.dataService.setAppDetails(deviceInfo);
  }

  this.loadinSrvc.userChangeEvent.subscribe((user) =&gt;
    setTimeout(() =&gt; {
      this.showLoader = {
        text: this.loadinSrvc.getLoaderText() || 'Please wait...',
        isLoader: user,
      };
    })
  );

  this.router.events.subscribe((event: Event) =&gt; {
    if (event instanceof NavigationEnd) {
      this.loadinSrvc.setLoader(false);
    }
    if (event instanceof NavigationStart) {
      this.loadinSrvc.setLoader(true);
    }
    if (event instanceof NavigationError) {
      this.toastr.error('Something went wrong, please retry.');
      this.loadinSrvc.setLoader(false);
    }
  });
}

</code></pre>

<p>Spec file:</p>

<pre class=""lang-js prettyprint-override""><code>describe('AppComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        RouterTestingModule,
        CommonModule,
        HttpClientModule,
        ToastrModule.forRoot({
          timeOut: 3000,
          positionClass: 'toast-bottom-right',
          maxOpened: 1,
          preventDuplicates: true,
        }),
        MatDialogModule,
      ],
      declarations: [AppComponent],
      providers: [
        CommonService,
        { provide: DataService, useClass: MockDataService },
      ],
    }).compileComponents();
  }));

  // try2
  it('should test some asynchronous code', fakeAsync(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const component = fixture.componentInstance;
    fixture.detectChanges();
    component.showLoader = { isLoader: false, text: 'Please wait...' };

    const testObservable = from(Promise.resolve(true));
    let flag = false;

    testObservable.subscribe((result) =&gt; {
      flag = true;
    });

    flushMicrotasks();
    expect(flag).toBe(true); // PASSES
  }));
});
</code></pre>
",https://stackoverflow.com/questions/61585897/angular-9-unit-testing-ngoninit-with-a-settimeout-inside-service,"['angular', 'unit-testing', 'angular6', 'karma-jasmine', 'angular9']",1345,False,0,1
How to test Observable with auditTime() in Angular unit testing,"<p>I have an observable in a component like this:</p>
<pre><code>this.obs$ = this.someService.getMessage().pipe(auditTime(100),tap(do something))
</code></pre>
<p>and a test case like this:</p>
<pre><code>mockService = jasmine.createSpyObj(&quot;SomeService&quot;, [
        &quot;getMessage&quot;,
    ]);

mockService.getMessage.and.returnValue(of([]));

it(&quot;should get a value from service&quot;, fakeAsync(() =&gt; {
        let a;
        fixture.detectChanges();
        component.obs$.subscribe((b) =&gt; {
                   a=b; 
                  console.log(b)
        });
        tick(100);
        expect(a).toEqual(expectedValue);
    }
</code></pre>
<p>The service will return a subject$.asObservable();</p>
<p>However, no value is printed in console, and the test will fail as variable a is undefined</p>
<p>How do I test an observable with auditTime?</p>
",https://stackoverflow.com/questions/65001026/how-to-test-observable-with-audittime-in-angular-unit-testing,"['angular', 'typescript', 'rxjs', 'jasmine']",236,False,0,0
Unit testing - mocking a config file referenced in a method,"<p>I'm trying to test a method that contains a reference to a global variable containing some configs taken from a json file.</p>
<pre><code>async function methodToTest(var1, var2, var3) {
    const functionName = 'methodToTest';
    
    //guards here
    
    try {

        if ((var1 === 0 || var2 === 0 || var3 &lt; config.prop1.pro1_child) {
            return false;
        }

        return true;
}
</code></pre>
<p>And this is it's test, being serviceConfig the required config json file:</p>
<pre><code>const rewire = require('rewire');
const fileToBeTested = rewire(`${ __base }methods/fileContainingMethodToTest`);

    describe('Testing methodToTest', function () {
        it('Should return false if var1 = 0 or var2 = 0 or var3 &lt; configured value', async function () {
            const var1 = '0';
            const var2 = '1';
            const var3 = '400';

            const expectedResponse = false;

            //Create a stub for the configs file
            configStub = sinon.stub(serviceConfig, 'config').resolves(serviceConfig)

            const result = await fileToBeTested.methodToTest(var1, var2, var3);
            expect(result).to.be.equal(expectedResponse);
        });
    }
</code></pre>
<p>This is the conf.json file that &quot;feeds&quot; the config variable in the method that requires testing:</p>
<pre><code>{
&quot;p1&quot;:&quot;test1&quot;,
&quot;p2&quot;:&quot;test2&quot;,
&quot;prop1&quot;: { &quot;pro1_child&quot;: &quot;2000&quot; }
...
}
</code></pre>
<p>But I get <code>TypeError: Cannot stub non-existent own property config</code>
What could I be doing wrong?</p>
<p>These are the modules I'm using:</p>
<pre><code>&quot;mocha&quot;: &quot;^5.0.5&quot;,
&quot;rewire&quot;: &quot;^4.0.1&quot;,
&quot;sinon&quot;: &quot;^4.5.0&quot;,
&quot;chai&quot;: &quot;^4.2.0&quot;,
&quot;chai-as-promised&quot;: &quot;^7.1.1&quot;
</code></pre>
",https://stackoverflow.com/questions/64464403/unit-testing-mocking-a-config-file-referenced-in-a-method,"['node.js', 'mocha.js', 'chai', 'sinon', 'rewire']",540,False,0,1
Mocking member functions while unit testing C++ class gtest/gmock,"<p>I have a following class (This is a very simplified version of actual class.)</p>

<pre><code>class PostCalc
{
public:
    virtual int add(int a, int b) { return a+b; } // Actual function is complex
    virtual int multiply(int a, int b) { return a*b; } // So this one
    virtual int multiop(int a, int b) { return add(a, b) + multiply(a, b); } 
};
</code></pre>

<p>For example, If I want to do unit test of <code>multiop()</code> and mock other member functions [ <code>add()</code> and <code>multiply()</code> ], how we can achieve so? I am thinking to create mock class of PostCalc, gmocked <code>add()</code> and <code>multiply()</code> and created a delegate function for <code>multiop()</code>. </p>

<pre><code>  class PostCalcMock : public PostCalc                            
  {                                                                               
  public:                                                                            
      MOCK_METHOD2(add, int(int a, int b)); 
      MOCK_METHOD2(multiply, int(int a, int b));       

      // Delegate                                                            
      int delegateToMultiOp(int a, int b) { 
          return multiop(a, b);
      }                                                                           
  };
</code></pre>

<p>Is this a good way to handle? Any help is appreciated.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/61712325/mocking-member-functions-while-unit-testing-c-class-gtest-gmock,"['c++', 'googletest', 'googlemock']",1501,True,0,1
Unit testing Python mixin which references a function defined elsewhere,"<p>I have the following situation:</p>

<pre><code>mixin_foo.py
   class Foo:
      def doFoo(self):
        bar=self.defined_elsewhere()
        #....do work
</code></pre>

<p>Unit test:</p>

<pre><code>@patch('path_to_mixin_foo.mixin_foo.Foo.defined_elsewhere')
def test_do_foo(self, definedElsewhere)
    definedElsewhere.return_value = bar1
    self.FooTester.doFoo()
</code></pre>

<p>the defined_elsewhere() method is defined in a class that derives from that mixin. However, for development purposes, we are working on mixing_foo.Foo first before integrating it with the class. However, when I try to unit test the doFoo method, the following error is shown by pytest: Attributeerror &lt;....> does not have the attribute 'defined_elsewhere'. 
Is my patch correct and if there another way to unit test this method? Basically I want to mock out the call/return value of the self.defined_elsewhere so the doFoo method can be tested.</p>
",https://stackoverflow.com/questions/61127278/unit-testing-python-mixin-which-references-a-function-defined-elsewhere,"['python', 'mocking', 'pytest', 'pytest-mock']",733,True,0,1
unit testing repository that use flow coroutine kotlin in android,"<p>I want to write unit test for my <code>repository</code>. The <code>repository</code>'s methods return <code>flow</code>. The <code>addDiaryRate</code> method first of all <code>emit</code> loading state then return data from network. I want to verify that <code>addDiaryRate</code> method emit loading then data response. I write this test but my test failed.The error say expected and actual isn't same while they are equal.</p>
<blockquote>
<p>java.lang.AssertionError:
Expected: is &lt;DataState(error=null, loading=Loading(isLoading=true), data=null)&gt;
but: was &lt;DataState(error=null, loading=Loading(isLoading=false), data=Event(content=RateResponse(data=RateModel(id=1, symbolPath=symbol path, rate=3, point=2.0, diaryId=333, count=34)), hasBeenHandled=false))&gt;
Expected :is &lt;DataState(error=null, loading=Loading(isLoading=true), data=null)&gt;
Actual   :&lt;DataState(error=null, loading=Loading(isLoading=false), data=Event(content=RateResponse(data=RateModel(id=1, symbolPath=symbol path, rate=3, point=2.0, diaryId=333, count=34)), hasBeenHandled=false))&gt;</p>
</blockquote>
<p>I use sample code of codelab and google samples.
This is <code>MainRepository</code>:</p>
<pre><code>   class MainRepositoryImp constructor(
    private val apiService: MainApiService,
    private val suggestionModelDao: SuggestionModelDao,
    private val userDao: UserDao,
    private val babyDao: BabyDao,
    private val diaryHotDao: DiaryHotDao,
    private val diaryUserDao: DiaryUserDao,
    private val hashTagModelDao: HashTagModelDao,
    private val diaryTopDao: DiaryTopDao,
    private val diaryResultSearchDao: DiaryResultSearchDao,
    private val rateModelDao: RateModelDao,
    private val medalDao: MedalDao,
    private val blogModelDao: BlogModelDao,
    private val seenDiaryDao: SeenDiaryDao,
    private val rateModelAppDao: RateModelAppDao,
    private val diarySavedDao: DiarySavedDao,
    private val diaryAnotherUserDao: DiaryAnotherUserDao,
    private val anotherUserInfoDao: AnotherUserInfoDao,
    private val followDao: FollowDao,
    private val suggestProductDao: SuggestProductDao,
    private val blogSuggestWithHashTagDao: BlogSuggestWithHashTagDao,
    private val suggestHashtagDao: SuggestHashtagDao,
    private val sessionManager: SessionManager
) : MainRepository {
 override fun addRateToDiary(rate: String, diaryId: String): Flow&lt;DataState&lt;RateResponse&gt;&gt; =
        flow {
            emit(DataState.loading(true))

            val apiResult = safeApiCall(
                sessionManager.isConnectedToTheInternet()
            ) {
                apiService.addRate(
                    diaryId,
                    AddRateRequest(rate),
                    sessionManager.cachedAccessToken.value ?: &quot;&quot;
                )
            }

            emit(
                object : ApiResponseHandler&lt;RateResponse, RateResponse&gt;(
                    response = apiResult
                ) {
                    override suspend fun handleSuccess(resultObj: RateResponse): DataState&lt;RateResponse&gt; {
                        safeCacheCall {
                            diaryHotDao.updateRateStateDiary(
                                resultObj.data.symbolPath ?: &quot;&quot;,
                                diaryId,
                                resultObj.data.rate
                            )
                            var countRate = 0
                            var userId = 0
                            userDao.fetchUser()?.let {
                                countRate = it.countRates + 1
                                userId = it.id
                            }
                            userDao.updateCountRate(countRate, userId)
                        }
                        return DataState.data(resultObj)
                    }

                }.getResult()
            )
        }
}
</code></pre>
<p>This is my test class:</p>
<pre><code>@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
@InternalCoroutinesApi
class MainRepositoryTest
{
    private lateinit var repository: MainRepository
    private var apiService = FakeUnitTestApiService()

    private lateinit var suggestionModelDao: SuggestionModelDao
    private lateinit var userDao: UserDao
    private lateinit var babyDao: BabyDao
    private lateinit var diaryHotDao: DiaryHotDao
    private lateinit var diaryUserDao: DiaryUserDao
    private lateinit var hashTagModelDao: HashTagModelDao
    private lateinit var diaryTopDao: DiaryTopDao
    private lateinit var diaryResultSearchDao: DiaryResultSearchDao
    private lateinit var rateModelDao: RateModelDao
    private lateinit var medalDao: MedalDao
    private lateinit var blogModelDao: BlogModelDao
    private lateinit var seenDiaryDao: SeenDiaryDao
    private lateinit var rateModelAppDao: RateModelAppDao
    private lateinit var diarySavedDao: DiarySavedDao
    private lateinit var diaryAnotherUserDao: DiaryAnotherUserDao
    private lateinit var anotherUserInfoDao: AnotherUserInfoDao
    private lateinit var followDao: FollowDao
    private lateinit var suggestProductDao: SuggestProductDao
    private lateinit var blogSuggestWithHashTagDao: BlogSuggestWithHashTagDao
    private lateinit var suggestHashtagDao: SuggestHashtagDao


    private lateinit var sessionManager: SessionManager
    private lateinit var db: AppDatabase

    private lateinit var prefManager: PrefManager

    @Rule
    @JvmField
    val instantExecutorRule = InstantTaskExecutorRule()


    @ExperimentalCoroutinesApi
    @get:Rule
    var mainCoroutineRule = MainCoroutineRule()

    @Before
    fun init() {
      val app = ApplicationProvider.getApplicationContext&lt;Application&gt;()

        prefManager=PrefManager(app)
        db = Room.inMemoryDatabaseBuilder(
            app,
            AppDatabase::class.java
        ).allowMainThreadQueries().build()
        initDao()
        sessionManager = SessionManager(
            app,
            userDao,
            babyDao,
            diaryHotDao,
            diaryTopDao,
            diaryUserDao,
            hashTagModelDao,
            medalDao,
            suggestionModelDao,
            diaryResultSearchDao,
            rateModelDao,
            blogModelDao,
            seenDiaryDao,
            rateModelAppDao,
            diarySavedDao,
            diaryAnotherUserDao,
            anotherUserInfoDao,
            followDao,
            suggestProductDao,
            blogSuggestWithHashTagDao,
            suggestHashtagDao,
            prefManager
        )
  
        repository = MainRepositoryImp(
            apiService,
            suggestionModelDao,
            userDao,
            babyDao,
            diaryHotDao,
            diaryUserDao,
            hashTagModelDao,
            diaryTopDao,
            diaryResultSearchDao,
            rateModelDao,
            medalDao,
            blogModelDao,
            seenDiaryDao,
            rateModelAppDao,
            diarySavedDao,
            diaryAnotherUserDao,
            anotherUserInfoDao,
            followDao,
            suggestProductDao,
            blogSuggestWithHashTagDao,
            suggestHashtagDao,
            sessionManager
        )
    }

    private fun initDao() {
        suggestionModelDao = db.getSuggestionModelDao()
        userDao = db.getUserDao()
        babyDao = db.getBabyDao()
        diaryHotDao = db.getDiaryHotDao()
        diaryUserDao = db.getDiaryUserDao()
        hashTagModelDao = db.getHashTagModelDao()
        diaryTopDao = db.getDiaryTopDao()
        diaryResultSearchDao = db.getDiaryResultSearchDao()
        rateModelDao = db.getRateModelDao()
        medalDao = db.getMedalDao()
        blogModelDao = db.getBlogModelDao()
        seenDiaryDao = db.getSeenDiaryDao()
        rateModelAppDao = db.getRateModelAppDao()
        diarySavedDao = db.getDiarySavedDao()
        diaryAnotherUserDao = db.getDiaryAnotherUserDao()
        anotherUserInfoDao = db.getAnotherUserInfoDao()
        followDao = db.getFollowDao()
        suggestProductDao = db.getBlogProductDao()
        blogSuggestWithHashTagDao = db.getBlogSuggestWithHashTagDao()
        suggestHashtagDao = db.getBlogSuggestDao()
    }


    @Test
    fun addRateTest() = mainCoroutineRule.runBlockingTest{
        /** GIVEN  **/
        val response = RateResponse(
            RateModel(
                id = &quot;1&quot;,
                symbolPath = &quot;symbol path&quot;,
                rate = 3,
                point = 2f,
                diaryId = &quot;333&quot;,
                count = &quot;34&quot;
            )
        )

        /** WHEN **/
        repository.addRateToDiary(&quot;2&quot;,&quot;333&quot;).collect{

            assertThat(it, `is`(DataState.loading&lt;RateResponse&gt;(true)))

            assertThat(it,`is`(DataState.data&lt;RateResponse&gt;(response)))
        }
    }
</code></pre>
",https://stackoverflow.com/questions/64427462/unit-testing-repository-that-use-flow-coroutine-kotlin-in-android,"['android', 'unit-testing', 'kotlin-coroutines', 'kotlin-flow']",2626,True,0,1
Angular cannot read property &#39;nativeElement&#39; of null DOM unit testing,"<p>I have a form with a number of the input field and text-area, when a keyboard (enter) key event happens on the text-area need to evaluate the text-area is empty or not? If it is empty error displayed on the html mat-error tag. I would like to write the unit test case for this scenario. I can get the dom value using jquery in the browser console, but in the spec file can't able to get the DOM content.</p>

<p>spec.ts file</p>

<pre><code>    it('should be display warning message', () =&gt; {
          const textArea: HTMLTextAreaElement = fixture.debugElement.query(By.css('.need-access-shipping-address textarea')).nativeElement as HTMLTextAreaElement;
          textArea.value = ""asd`"";
          const event = new KeyboardEvent(""keypress"",{
            ""key"": ""Enter""
          });
          textArea.dispatchEvent(event);
          fixture.detectChanges();
          const nameDisplay: HTMLElement = fixture.debugElement.query(By.css('.need-access-shipping-address .mat-error')).nativeElement as HTMLElement;
          expect(nameDisplay.innerText).toBe('The format of the information entered is invalid');
    });
</code></pre>

<p>output getting as  <code>Expected: ""The format of the information entered is invalid""
    Received: undefined</code></p>

<p>Input <code>textArea.value = ""asd~""</code> reg expression error</p>

<p><code>textArea.value = ""asd""</code> is a valid input</p>

<p><a href=""https://i.stack.imgur.com/Hmddz.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Hmddz.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/59872217/angular-cannot-read-property-nativeelement-of-null-dom-unit-testing,"['angular', 'jasmine']",4958,True,0,1
Permission errors unit-testing Google Cloud Functions calling firestore db,"<p>I'm following the guide at <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a>, but I always get "" FirebaseError: Missing or insufficient permissions"" when I run my test. I have the correct <code>service-account.json</code> file and I'm setting up <code>firebase-functions-test</code> with it (that part goes without error).</p>

<p>I've tried it with the emulator running (setting the FIRESTORE_EMULATOR_HOST var), and without it (which I assume uses live data) but I always get this error, as soon as my code under test does a db request such as:</p>

<pre><code>  data = await db().collection('/machines').get()
</code></pre>

<p>So my function under test is getting called, but it just can't do anything.
I also tried calling <code>firebase.initializeApp()</code> the same way I do in my front-end app, but that doesn't help, although without it I get the error telling me to call Firebase App.initializeApp().</p>

<p><code>firebase use</code> is set to my current project.</p>

<p>I also tried running my test as <code>firebase emulators:exec jest</code>, no difference.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/60624919/permission-errors-unit-testing-google-cloud-functions-calling-firestore-db,"['firebase', 'unit-testing', 'google-cloud-functions', 'firebase-cli']",134,False,0,0
Jest Unit testing for conditional elements with react-hook-form,"<p>Im having a react hook form and some validation messages. I need to unit test this component. But all the time my conditional elements are not being rendered or updated. I've tried <code>wrapper.update();</code> but it's not serving the purpose.</p>
<p>My Component:</p>
<pre><code>&lt;form data-test='login-form' onSubmit={handleSubmit(onSubmit)}&gt;
   &lt;input data-test='password' name='password'
      ref={register({
           required: 'Password Required',
           minLength: {
              value: 6,
              message: 'Password should be 6 char long' ,
           },
          })}
    /&gt;
    {errors.password &amp;&amp; (
       &lt;p data-test='password-error'&gt;
          {(errors.password as any).message}
       &lt;/p&gt;
    )}
 &lt;button data-test='login-submit'&gt;
    Submit
 &lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>Unit Testing:</p>
<pre><code>const setup = (): ShallowWrapper =&gt;
      shallow(&lt;LoginForm  /&gt;);

 describe('Login Form Component', () =&gt; {
   let wrapper: ShallowWrapper;
   test('expect to show password required validation messages', async () =&gt; {
  
   wrapper = setup();
   const loginButton = wrapper.find(`[data-test='password-error']`);

   loginButton.simulate('click');

   wrapper.update();

   const emailError = wrapper.find(`[data-test='email-error']`);
   expect(emailError.length).toBe(1);
 });
});
</code></pre>
<p>This never passes.</p>
<p>Any help is appreciated.</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/64558048/jest-unit-testing-for-conditional-elements-with-react-hook-form,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'react-hook-form']",820,False,0,0
I am geeting error in unit testing of django app,"<p>I am geting error &quot;ValueError: Cannot assign &quot;'12A20'&quot;: &quot;Attendance.rollno&quot; must be a &quot;Student&quot; instance.&quot;
how to solve it ??
Is another way for testing when foreign key is present in Django?
model.py</p>
<pre><code> class Student(models.Model):
     classId=models.ForeignKey(Class,on_delete=models.CASCADE)
     name=models.CharField(max_length=20)
     fatherName=models.CharField(max_length=20)
     motherName=models.CharField(max_length=20)
     address=models.TextField(max_length=100)
     section = models.CharField(max_length=2)
     prevClass=models.IntegerField()
     prevClassMark=models.IntegerField()
     prevResult=models.ImageField(upload_to='images/')
     gender=models.CharField(max_length=6)
     image=models.ImageField(upload_to='images/')
     stream=models.CharField(max_length=10,)#choices=Stream)
     department=models.CharField(max_length=15)
     dob=models.CharField(max_length=12)
     rollno = models.CharField(max_length=10)
     password=models.CharField(max_length=30)

  class Attendance(models.Model):
     rollno=models.ForeignKey(Student,on_delete=models.CASCADE)
     class_id=models.ForeignKey(Class,on_delete=models.CASCADE)
     date=models.CharField(max_length=11)
     status=models.CharField(max_length=7)
</code></pre>
<p>tests.py</p>
<pre><code>class AttendanceTest(TestCase):
    def setUp(self):
        Attendance.objects.create(
        rollno='12A20',
        class_id=121,
        date='2020-09-03',
        status='Present'
        )
        Attendance.objects.create(
        rollno='13A20',
        class_id=121,
        date='2020-09-03',
        status='Present'
        )
    def test_Attendance(self):
        qs=Attendance.objects.all()
        self.assertEqual(qs.count(),2)
</code></pre>
",https://stackoverflow.com/questions/63746102/i-am-geeting-error-in-unit-testing-of-django-app,"['python', 'django', 'web']",71,False,0,2
Unit testing Error part of Angular Service which Returns Observable,"<p>I am trying to test a very simple piece of code:</p>

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

<pre><code>createSet(dataSetPayload: SetPayload): void {
    this.setsService.addSet(dataSetPayload).subscribe(
      (set: Set) =&gt; {
        this.hideCreateSetForm();
        this.setsDomainModel.updateSets(Set);
      },
      (error: HttpErrorResponse) =&gt; {
        this.createSetError = error;
      }
    );
  }
</code></pre>

<p>What I need to cover in my coverage is the error part of the function which has <strong>this.createSetError = error;</strong> line.</p>

<p><strong>service.ts</strong></p>

<pre><code>addSet(setPayload: SetPayload): Observable&lt;Set&gt; {
    return this.httpService
      .post(`${API_PATHS.SETS.ADD_SET}`, setPayload)
      .pipe(
        map((set: Set) =&gt; {
          return set;
        })
      );
  }
</code></pre>

<p>I am out of ideas to mock the <strong>addSet</strong> functions using <strong>jest.spyOn</strong> method so that it directly enters the error block of the subscription. Is there anything I can try?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/61332142/unit-testing-error-part-of-angular-service-which-returns-observable,"['angular', 'typescript', 'unit-testing', 'jestjs', 'observable']",27,False,0,0
Unit testing supposed to be &quot;passed&quot;? Why is it failing?,"<pre><code>  function renderInventory(inventory) {
  //create a flat list
  var flatList = '';
  //iterate over the inventory
  for (var i = 0; i &lt; inventory.length; i++) {
    var designerObject = inventory[i];
    var shoes = designerObject.shoes;
    //iterate over the each shoe in the array
    for (var j = 0; j &lt; shoes.length; j++) {
      var currentShoe = shoes[j];
      //add the designer name, the shoe name, and the shoe price and the new line
      flatList = designerObject.name +"", "" + currentShoe.name +"", "" + currentShoe.price + '\n';
    } 
  }
  //return the flat list
  return flatList;
}
//assertion Function
function assertEqual(actual, expected, testName) {
  if (actual === expected) {
  console.log('passed');
  } else {
  console.log('FAILED [' + testName + '] Expected ""' + expected + '"", but got ""' + actual + ""'"");
  }
}

//test cases

var currentInventory = [{
    name: 'Brunello Cucinelli',
    shoes: [
      {name: 'tasselled black low-top lace-up', price: 1000},
      {name: 'tasselled green low-top lace-up', price: 1100},
      {name: 'plain beige suede moccasin', price: 950},
      {name: 'plain olive suede moccasin', price: 1050}
    ]
  },
  {
    name: 'Gucci',
    shoes: [
      {name: 'red leather laced sneakers', price: 800},
      {name: 'black leather laced sneakers', price: 900}
    ]
  }
];

var actualFlatList = renderInventory(currentInventory);

var expectedFlatList = 'Brunello Cucinelli, tasselled black low-top lace-up, 1000\nBrunello Cucinelli, tasselled green low-top lace-up, 1100\nBrunello Cucinelli, plain beige suede moccasin, 950\nBrunello Cucinelli, plain olive suede moccasin, 1050\nGucci, red leather laced sneakers, 800\nGucci, black leather laced sneakers, 900\n';

assertEqual(actualFlatList, expectedFlatList, ""should render flat list of inventory items"");
</code></pre>

<p><strong>Result:</strong> 
FAILED [should render flat list of inventory items] Expected ""Brunello Cucinelli, tasselled black low-top lace-up, 1000
Brunello Cucinelli, tasselled green low-top lace-up, 1100
Brunello Cucinelli, plain beige suede moccasin, 950
Brunello Cucinelli, plain olive suede moccasin, 1050
Gucci, red leather laced sneakers, 800
Gucci, black leather laced sneakers, 900
"", but got ""Gucci, black leather laced sneakers, 900
'</p>

<p>I tried to add my code properly. Hopefully, I did it right. I'm a newbee in coding. My question is, this unit testing code block supposed to give <strong>'passed'</strong>. Where did I do wrong? Can someone clarify it please.</p>
",https://stackoverflow.com/questions/61112183/unit-testing-supposed-to-be-passed-why-is-it-failing,"['javascript', 'unit-testing', 'tdd']",42,True,0,1
AssertionError on unit testing service layer (in Java using Spring),"<p>Trying to unit test my service layer, this is my test code :</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ServiceCreateUserTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserCreateService userCreateService;

    @Test
    public void when_save_user_it_should_return_user() {
        User user = new User();
        user.setName(&quot;Test Name&quot;);

        when(userRepository.save(ArgumentMatchers.any(User.class))).thenReturn(new User());

        User created = userCreateService.create(user);

        assertThat(created.getName()).isSameAs(user.getName());
    }
}
</code></pre>
<p>And this is my service code :</p>
<pre><code>@Service
public class UserCreateService {

    @Autowired
    UserRepository repository;

    public User create(User user) {
        return repository.save(user);
    }
}
</code></pre>
<p>I'm getting the following error when running :</p>
<pre><code>java.lang.AssertionError: 
</code></pre>
<p>Expecting:
&lt;&quot;Test Name&quot;&gt;
and actual:</p>
<pre><code> &lt;null&gt;
</code></pre>
<p>to refer to the same object</p>
<p>Could someone shed some light here? Not sure what is missing in my test code. Perhaps something to do with my method imports?</p>
",https://stackoverflow.com/questions/61961772/assertionerror-on-unit-testing-service-layer-in-java-using-spring,"['java', 'unit-testing', 'mockito']",80,True,-1,1
How to seperate Unit Testing from main program in C++?,"<p>I am currently working on a C++ project and want to test my methods by myself. However, I would like the test them separated from the main loop of the program. </p>

<p>Here is a simplified code. In main.cpp;</p>

<pre><code>int main() {

Numbers A(7.4) ;
Numbers B(6.6) ;

 cout &lt;&lt; A.DoCalc(B);
</code></pre>

<p>}</p>

<p>In the Test.cpp file ; </p>

<pre><code>    void TestDoCalc(Numbers &amp;First, Numbers &amp;Second, float &amp;ExpectedResult){

    assert (First.DoCalc(Second) == ExpectedResult);
}

int main (){

    Numbers TestNumber1(2);
    Numbers TestNumber2(3);
    float ExpectedValue = 5 ;
    TestDoCalc(TestNumber1,TestNumber2,ExpectedValue);

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

<p>Because there are multiple main loops, the compiler gives an error. How can I separately test my method so that the main loop of test.cpp will be run when only it is needed.</p>

<p>Thanks in advance,</p>
",https://stackoverflow.com/questions/61225576/how-to-seperate-unit-testing-from-main-program-in-c,"['c++', 'testing']",431,True,0,1
Why I couldn&#39;t use Microsoft.AspNetCore.Mvc; in my unit testing project?,"<p>I created an asp.net core mvc project and also created a unit testing project
below is the code for the unit testing project:</p>

<pre><code>using System;
using Microsoft.AspNetCore.Mvc;  // error, type or namespace is missing
using Xunit;

namespace Project.Tests
{
    public class UnitTest1
    { 

        [Fact]
        public void Test1()
        {
          ...
        }
    }
}
</code></pre>

<p>I don't quite understand, I used to create unit testing projects without any problem, why I cannot access <code>Microsoft.AspNetCore.Mvc</code> this time?</p>
",https://stackoverflow.com/questions/59726695/why-i-couldnt-use-microsoft-aspnetcore-mvc-in-my-unit-testing-project,"['c#', '.net', 'xunit.net']",2055,True,0,2
Golang Unit Testing Erorr when test function with query db,"<p>i start learning unit test on golang, i have do a simple test than it work, but try on real case, i found some errors, this is my test code:</p>
<ol>
<li>test code</li>
</ol>
<pre><code>func TestGetAllCompetency(t *testing.T) {
    _, err := competencyService.GetAllCompetency()
    if err != nil {
        t.Error(&quot;failed to get competency&quot;)
    }
}
</code></pre>
<ol start=""2"">
<li>GetAllCompetency Code</li>
</ol>
<pre><code>func GetAllCompetency() ([]models.Competency, error) {
    data := []models.Competency{}
    res := database.Conn.
        Table(&quot;competency&quot;).Order(&quot;name&quot;).
        Where(&quot;competency.is_delete = ?&quot;, false).
        Find(&amp;data)
    err := res.Error
    if err != nil {
        log.Println(&quot;[Error] competencyService.GetAllData : &quot;, err)
        return []models.Competency{}, err
    }
    return data, nil
}
</code></pre>
",https://stackoverflow.com/questions/64020516/golang-unit-testing-erorr-when-test-function-with-query-db,"['unit-testing', 'go']",86,False,0,0
undefined is not an object. While Unit Testing on Angular,"<p>I have been testing my simple component in angular.
I am trying to test a function which returns some data from a service's function. 
I configured the testbed setup the initial boilerplate, not when i try to test the function it says</p>

<blockquote>
  <p>TypeError: undefined is not an object (evaluating 'this.siAuthenticationService.getCustomerList') in http:/
  /localhost:9876/_karma_webpack_/main.js</p>
</blockquote>

<p>This is my 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 { Component } from '@angular/core';

import { SiAuthenticationService } from '@strategic-insights/ng-authentication-fr';

declare var $: any;

@Component({
  selector: 'si-customer-access',
  templateUrl: './si-customer-access.component.html',
  styleUrls: ['./si-customer-access.component.scss']
})
export class SiCustomerAccessComponent {
  customerList: any;
  selectedCustomer: any;

  constructor (private siAuthenticationService: SiAuthenticationService) {
    this.customerList = this.fetchCustomerList()
    $('#siCustomerAccessModal').modal({
      backdrop: 'static',
      keyboard: false,
      focus: true,
      show: true
    });

  }

  fetchCustomerList(){
    return this.siAuthenticationService.getCustomerList();
  }
  
  submit () {
   this.siAuthenticationService.setActiveCustomer(this.selectedCustomer);
  }

  setSelectedCustomer (selectedCustomer: string) {
    this.selectedCustomer = selectedCustomer;
  }

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

<p>This is my spec 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 { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SiCustomerAccessComponent } from './si-customer-access.component';
import { SiAuthenticationService } from '@strategic-insights/ng-authentication-fr';
import { HttpClientModule } from '@angular/common/http';

describe('SiCustomerAccessComponent', () =&gt; {
  let component: SiCustomerAccessComponent;
  let fixture: ComponentFixture&lt;SiCustomerAccessComponent&gt;;
  let service: SiAuthenticationService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ SiCustomerAccessComponent],
      providers : [{provide: SiAuthenticationService}],
      imports: [HttpClientModule],
    })
    fixture = TestBed.createComponent(SiCustomerAccessComponent);
    component = fixture.componentInstance;
    service = TestBed.get(SiAuthenticationService);
  });


  beforeEach(() =&gt; {

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

  it('fetchCustomerList to be called',()=&gt;{
    component.fetchCustomerList()
    expect(component.fetchCustomerList).toHaveBeenCalled()
    service.getCustomerList()
    expect(service.getCustomerList).toHaveBeenCalled()
  })
});</code></pre>
</div>
</div>
</p>

<p>Can anyone help me where I am going wrong?</p>
",https://stackoverflow.com/questions/60144505/undefined-is-not-an-object-while-unit-testing-on-angular,"['angular', 'unit-testing', 'jasmine']",1072,False,0,1
Stenciljs unit testing getting error : ReferenceError XMLHttpRequest is not defined,"<p>I'm trying to create units test for my stencil js component, in the compnentWillLoad() method it will do an HTTP request (using rxjs).when I'm run the test getting error  <strong>ReferenceError: XMLHttpRequest is not defined</strong>.But when removing the HTTP request from the componentWillLoad() method test passed.
My test as below,</p>

<pre><code>it('should render my component', async () =&gt; {
    const page = await newSpecPage({
      components: [MyComponent],
      html: `&lt;my-component&gt;&lt;/my-component&gt;`,
    });
    expect(page.root).toEqualHtml(`&lt;my-component&gt;&lt;/my-component&gt;`);
  });
</code></pre>

<p>I'm getting error  <strong>ReferenceError: XMLHttpRequest is not defined</strong></p>
",https://stackoverflow.com/questions/61929598/stenciljs-unit-testing-getting-error-referenceerror-xmlhttprequest-is-not-defi,"['unit-testing', 'jestjs', 'stenciljs']",900,True,0,2
Methods in Default Protocol extension executed on unit testing always,"<p>I have a protocol with the default implementation in the extension of that protocol. When I try to create a concrete mock object of that protocol to unit test, the default implementation always gets executed. I am not able to figure why. Any help would be appreciated. I am on xcode 11.3</p>

<pre><code>protocol ABC: AnyObject {
 func doSomething()
}

extension ABC {
 func doSomething() {
   print(""Did Something"")
 }

}


final class ClassToBeTested {

    var abc: ABC?

    func methodToBeTested() {
       abc?.doSomething()
    }
}
</code></pre>

<p><strong>In Test Target</strong></p>

<pre><code>final class MockABC: ABC {
   func doSomething() {
     print(""Did Something in Test Target"")
  }
}

final class Tests: XCTestCase {

   func testMethod() {
     let obj = ClassTobeTested()
     // abc property is of type protocol ABC
     obj.abc = MockABC()

    *This line calls the default implementation of the protocol of ABC and not the 
     implementation in MockABC class - verifiable by breakpoints and print statements*

     obj.methodToBeTested()

  }

}
</code></pre>

<p>I have read the <code>static</code> dispatch which happens in such cases, but could not find any particular reason to this. Kindly help.</p>
",https://stackoverflow.com/questions/60814846/methods-in-default-protocol-extension-executed-on-unit-testing-always,"['ios', 'swift', 'unit-testing']",470,False,0,1
How to convert int to byte in unit testing DataRow?,"<p>I started making tests where i check bytes but i noticed that I can't write byte in DataRow, because I get a message: System.ArgumentException: Object of type 'System.Int32' cannot be converted to type 'System.Byte'.</p>
<p>How can I convert int to byte in DataRow?</p>
<pre><code>[DataRow(12, 12)]
    [DataRow(23, 23)]
    public void Consturcot_1param(byte h, byte expectedH)
    {
        Time t = new Time(h);

        AssertTime(t, expectedH, expectedM: 0, expectedS: 0);
    }
</code></pre>
",https://stackoverflow.com/questions/65092549/how-to-convert-int-to-byte-in-unit-testing-datarow,"['unit-testing', 'vs-unit-testing-framework']",199,True,0,1
Unit testing the creation of an entry in the database,"<p>I'm wanted to write a simple unit test for a service.
This is the method in my service which I want to unitest.</p>

<pre><code>@Log4j
@Service
public class Service {

     @Autowired
     private Repository repository;

    public JpaRecord create(JpaRecord jpaRecord) {
        return repository.save(jpaRecord);
    }
}
</code></pre>

<p>This method just creates a new entry in the Database.</p>

<p>This is the JpaRecord: </p>

<pre><code>@Data
@Entity
@Table(name = ""TEST"", schema = ""TEST"")
public class JpaRecord implements Serializable {
    private static final long serialVersionUID = 1L;

    JpaRecord() {
        // default constructor
    }

    public JpaRecord(
            String name,
            Date createdAt,
            Blob file
    ) {
        this.name = name;
        this.createdAt = createdAt;
        this.file = file;
    }

    @Id
    @Column(name = ""ID"", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = ""TEST_SEQx"")
    @SequenceGenerator(
            sequenceName = ""TEST_SEQ"", allocationSize = 1,
            name = ""TEST_SEQx"")
    private Long id;

    @Column(name = ""NAME"")
    private String name;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = ""CREATED_AT"")
    private Date createdAt;

    @Lob
    @Column(name = ""FILE"")
    private Blob file;
}
</code></pre>

<p>The <strong>id</strong> should not be null, all the other entries can be null.
I wrote this test to check if the DB entry is not null, which means it is created.</p>

<pre><code>public class ServiceTest {

    @Autowired
    private Service Service;

    @Autowired
    private JpaRecord JpaRecord;

    @Before
    public void setUp(){

    }

    @Test
    public void testCreateWhenNull(){
        // prepare data
        JpaRecord = new JpaRecord(""testProject"", new Date(),null);
        // run

        // test with assert
        Assert.assertNotNull(Service.create(JpaRecord));
    }

}
</code></pre>

<p>I then get a java.lang.NullPointerException!
I would really appreciate any suggestion on how I should approach a problem to unit test it. 
It is my first time unit testing and I wanted to start with a simple null check.</p>
",https://stackoverflow.com/questions/60192135/unit-testing-the-creation-of-an-entry-in-the-database,"['java', 'spring-boot', 'unit-testing']",194,True,0,1
Unit testing Django model with an image - Not quite understanding SimpleUploadedFile,"<p>I'm a testing noob and I'm trying to figure out how to write a test to confirm that a model form is valid and will generate a new instance of <code>Post</code>, which is a model that has an image field.</p>
<p>I looked <a href=""https://stackoverflow.com/questions/26298821/django-testing-model-with-imagefield"">some other</a> SO posts, and it looks like I should be using SimpleUploadedFile to mock the image field. I'm having a hard time understanding how SimpleUploadedFile works (haven't found any straightforward documentation for this application), and different SO posts use some different looking syntax.</p>
<p>Am I supposed to point to a real file path to an actual image that is held somewhere in my Django app, or does this create a fake file to be used?</p>
<p>tests.py</p>
<pre><code>class CreatePost(TestCase):
    def test_create_post(self):
        data = {
            &quot;content&quot;: &quot;This is a post, I'm testing it out&quot;
        }
        files_data = {
            &quot;image&quot;: SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg') 
        }
        response = self.client.post(&quot;/new&quot;, data=data, files=files_data)
        self.assertEqual(Post.objects.count(),1)
        self.assertRedirects(response, 'index')
</code></pre>
<p>models.py</p>
<pre><code>class Post(models.Model):
    content = models.CharField(max_length=260)
    timestamp = models.DateTimeField(auto_now_add=True)
    posted_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name=&quot;posts&quot;)
    liked_by = models.ManyToManyField(User, blank=True, related_name=&quot;liked_posts&quot;)
    image = models.ImageField(upload_to='uploads/', verbose_name='image')
    def __str__(self):
        return f&quot;{self.posted_by} posted {self.content} at {self.timestamp}&quot;
    def is_valid_post(self):
        return len(self.content) &lt;= 260 and len(self.content) &gt;= 0
     

class Post_form(ModelForm):
    class Meta: 
        model = Post
        fields = ['content', 'image']
</code></pre>
",https://stackoverflow.com/questions/63476979/unit-testing-django-model-with-an-image-not-quite-understanding-simpleuploaded,"['django', 'unit-testing', 'django-models', 'django-testing']",3256,True,5,1
Django unit testing form with field assigned from request object,"<p>I have this form</p>
<pre><code>class PostCreationForm(forms.ModelForm):
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)
</code></pre>
<p>and I'm trying to unit test it with this test</p>
<pre><code>class PostCreationByFormTestCase(TestCase):
    def __init__(self, *args, **kwargs):
        super(PostCreationByFormTestCase, self).__init__(*args, **kwargs)
        self.CustomUser = get_user_model()

    def setUp(self):
        self.credentials = {
            'username': 'john_smith',
            'password': 'St0ngPassw0rd'
        }
        self.user = self.CustomUser.objects.create(
            username=self.credentials['username'],
            email='john_smith@mail.com',
            password=self.credentials['password'],
            first_name='John',
            last_name='Smith'
        )

    def test_simple_form(self):
        form_data = {
            'author': self.user,
            'title': 'Simple Post',
            'description': 'very good description',
        }
        form = PostCreationForm(form_data)
        self.assertTrue(form.is_valid)
        post = form.save()
</code></pre>
<p>the assert passes, but the <code>form.save()</code> produces
django.db.utils.IntegrityError: null value in column &quot;author_id&quot; violates not-null constraint</p>
<p>I tried changing the form to</p>
<pre><code>class PostCreationForm(forms.ModelForm):
    def form_valid(self, form):
        if not form.instance.author:
            form.instance.author = self.request.user
        return super().form_valid(form)
</code></pre>
<p>but it still does not work. I saw this as a recommended way to assign field to object if I don't want to take it as an input from the user as in this case where I want the author of the post to be the current user.
How should I fix that in order to be able to test the form?</p>
",https://stackoverflow.com/questions/64361286/django-unit-testing-form-with-field-assigned-from-request-object,"['django', 'django-testing', 'django-tests']",122,True,0,1
Undefined layerGroup() when unit testing leaflet with jest and enzyme,"<p>I'm trying to test if my <code>MyCustomMap</code> is calling my <code>MapController</code> and creating a new leaflet map component.</p>

<p>However <code>MapController</code> is setting <code>_mapGroup</code> as <code>undefined</code> on <code>MyCustomMap</code> component and it should be <code>L.layerGroup()</code> (not <code>undefined</code>).</p>

<p>I already tried to mock <code>MapController</code> and <code>leaflet</code> in different ways, but <code>_mapGroup</code> still being <code>undefined</code>. What is wrong? How can I solve this?</p>

<p><strong>My MyCustomMap test file (custom-map.test.js):</strong></p>

<pre><code>import MyCustomMap from './custom-map';
import initialMapOptions from './map-options';
import MapController from './map-controller';

const mapCreateGroupMock = jest.fn(),
  mapAddGroupToMap = jest.fn();

let myMap = null,
  mapController = null;

beforeAll(() =&gt; {
  const mapOptions = initialMapOptions();
  mapController = {
    createGroup: mapCreateGroupMock,
    addGroupToMap: mapAddGroupToMap
  };
  myMap = new MyCustomMap(mapController, mapOptions);
});

describe('My custom map', () =&gt; {
  it(`should call MapController and create a new leaflet map component`, () =&gt; {
    expect(mapCreateGroupMock).toBeCalledTimes(1);
    expect(mapAddGroupToMap).toBeCalledTimes(1);    
    expect(myMap._mapGroup).not.toBeNull();     // -&gt; here is failing because myMap._mapGroup is undefined and shouldn't be
  });
});
</code></pre>

<p><strong>My MapController (map-controller.js):</strong></p>

<pre><code>import L from 'leaflet';

class MapController {
  constructor(container, configuration) {
    this._map = new L.Map(container, { zoomControl: false, minZoom: this._minZoom });
    this._container = document.getElementById(container);

    //more code here ...
  }

  createGroup() {
    return L.layerGroup();
  }


  addGroupToMap(group) {
    this._map.addLayer(group);
  }

  //more code here ...
}

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

<p><strong>My MyCustomMap component (custom-map.js):</strong></p>

<pre><code>class MyCustomMap {
  constructor(mapController, configuration) {
    this._mapController = mapController;
    this._configuration = configuration;

    this._mapGroup = this._mapController.createGroup();
    this._mapController.addGroupToMap(this._mapGroup);

    //more code here ...
  }
}
</code></pre>
",https://stackoverflow.com/questions/61329832/undefined-layergroup-when-unit-testing-leaflet-with-jest-and-enzyme,"['reactjs', 'unit-testing', 'mocking', 'jestjs', 'leaflet']",364,True,0,1
How to write Unit testing for Jooq Select Query in junit,"<pre><code> public &lt;Class&gt; getClassbyName(String name) {
     private DSLContext context;
    
     return context.selectFrom(Table)
                   .where(Table.NAME.equal(name))
                   .fetchOneInto(Class.class);
} 
</code></pre>
<p>I have this kind of function. I need to write a unit test for this Select Query in JOOQ. does anyone have any idea?</p>
",https://stackoverflow.com/questions/64910410/how-to-write-unit-testing-for-jooq-select-query-in-junit,"['java', 'jdbc', 'junit', 'junit4', 'jooq']",1135,True,4,1
How to do a simple unit testing with RabbitMQ in python?,"<p>In my unit test, I want to simply start consuming, publish a message, and receive a response back and assert if the response is what I expect it to be. However, I have been trying to do this for hours and don't find a solution. </p>

<p>The problem is that I cannot define a method in a class that stops the consuming. I have tried defining a method like this:</p>

<pre><code>def stop(self):
    self.channel.basic_cancel()
</code></pre>

<pre><code>def stop(self):
    self.channel.stop_consuming()
</code></pre>

<pre><code>def stop(self):
    self.connection.close()
</code></pre>

<p>But nothing seems to work. I have read that this is because once you execute <code>start_consuming()</code>, the only way to stop the consuming is to cancel it after a message is sent. But if I do this, then I would be modifying the original <code>on_request</code> and that wouldn't be useful for my application, because the connection will close after the first message. I have found <a href=""https://github.com/ClearcodeHQ/pytest-rabbitmq"" rel=""nofollow noreferrer"">pytest-rabbitmq</a> but the documentation isn't clear for me and thus don't know if I can use this plugin to achieve what I want.</p>

<p>By the way, what is the difference between <code>basic_cancel</code>, <code>stop_consuming</code> and <code>close</code>?</p>
",https://stackoverflow.com/questions/61420518/how-to-do-a-simple-unit-testing-with-rabbitmq-in-python,"['rabbitmq', 'pika']",5202,True,4,2
Mocha Unit Testing: Uncaught TypeError: Cannot read property &#39;apply&#39; of undefined,"<p>I want to write unit testing for Restful Endpoint, but whenever I run npm test. I get the error  Uncaught TypeError: Cannot read property 'apply' of undefined .</p>
<pre><code>let chai = require('chai')
let chaiHttp = require('chai-http')
let home = require('../routes/home')
let user = require('../routes/users')
//Assertion Style
chai.should()

chai.use(chaiHttp)

describe('chow Api', () =&gt; {
  //  users
    describe(&quot;GET /api/chow/home&quot;, () =&gt; {
        it('it should render Welcome to Homepage', (done) =&gt;{
            chai.request(home)
            .get(&quot;/api/chow/home&quot;)
            .end((err, response) =&gt;{
                response.should.have.status(200)
                response.body.should.be('string')
                done()
            })
        })
    })

    describe('GET /api/chow/users', () =&gt; {
        it('it should GET all the users', (done) =&gt; {
            chai.request(user)
            .get(&quot;/api/chow/users&quot;)
            .end((err, response) =&gt;{
                response.should.have.status(200)
                response.should.be.a('array')
                done()
            })
        })
    })
})
</code></pre>
",https://stackoverflow.com/questions/65419488/mocha-unit-testing-uncaught-typeerror-cannot-read-property-apply-of-undefine,"['javascript', 'node.js', 'testing']",3432,True,4,3
Pre loading data from .sql before unit testing throws syntax error,"<p>I'm performing unit testing on spring boot app using JPA and SpringJUnit4ClassRunner. for that I have created a configuration file as - </p>

<pre><code>
@Configuration
@EnableJpaRepositories(basePackages = ""base_package_name"")
@EnableTransactionManagement
public class JPAConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(""org.postgresql.Driver"");
        dataSource.setUrl(""jdbc:postgresql://localhost:5432/employeedb_test"");
        dataSource.setUsername(""postgres"");
        dataSource.setPassword(""postgres"");

        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put(""hibernate.dialect"", ""org.hibernate.dialect.PostgreSQL9Dialect"");        
        properties.put(""hibernate.hbm2ddl.auto"", ""create"");
        properties.put(""hibernate.show_sql"", ""true"");
        properties.put(""hibernate.format_sql"", ""false"");
        return properties;
    }

    @Bean(name=""entityManagerFactory"")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setDataSource(this.dataSource());
        lcemfb.setPackagesToScan(new String[] {""Package_to_scan""});

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        lcemfb.setJpaVendorAdapter(va);

        lcemfb.setJpaProperties(this.hibernateProperties());

        lcemfb.afterPropertiesSet();

        return lcemfb;

    }


    @Bean
    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();

        tm.setEntityManagerFactory(
            this.entityManagerFactoryBean().getObject() );

        return tm;

    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }
}


</code></pre>

<p>My test class looks like this - </p>

<pre><code>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={
        JPAConfig.class,
        TestConfig.class
        })
@SqlGroup({
    @Sql(executionPhase=ExecutionPhase.BEFORE_TEST_METHOD,scripts=""classpath:beforeTestRun.sql"")
})
public class ExampleTest {
     ...
}

</code></pre>

<p>now I want to insert data from script file beforeTestRun.sql into entity before running any test. so I added following annotation above my test class(i.e. ExampleTest) - </p>

<pre><code>@SqlGroup({
    @Sql(executionPhase=ExecutionPhase.BEFORE_TEST_METHOD,scripts=""classpath:beforeTestRun.sql"")
})
</code></pre>

<p>my beforeTestRun.sql contains insert query - </p>

<pre><code>INSERT INTO employee(emp_name)
    VALUES ('Jhon Dave');
</code></pre>

<p>my model class is - </p>

<pre><code>
@Entity
@Table(name = ""employee"")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name=""emp_id"")
    Integer id;

    @Column(name=""emp_name"")
    String empName;


    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }


}

</code></pre>

<p>now after running test class, it trying to insert from .sql file but eventhough the syntax is correct it throwing an error says - </p>

<pre><code>org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of class path resource [beforeTestRun.sql]: INSERT INTO employee(emp_name) VALUES ('Jhon Dave'); nested exception is org.postgresql.util.PSQLException: ERROR: syntax error at or near ""INSERT""
  Position: 1
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:626)
    at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254)
    at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:49)
    at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.execute(ResourceDatabasePopulator.java:269)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$4(SqlScriptsTestExecutionListener.java:263)
    at org.springframework.transaction.support.TransactionOperations.lambda$executeWithoutResult$0(TransactionOperations.java:68)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
    at org.springframework.transaction.support.TransactionOperations.executeWithoutResult(TransactionOperations.java:67)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:263)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$0(SqlScriptsTestExecutionListener.java:185)
    at java.lang.Iterable.forEach(Unknown Source)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:185)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:147)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.beforeTestMethod(SqlScriptsTestExecutionListener.java:117)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near ""INSERT""
  Position: 1
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2497)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2233)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:311)
    at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:297)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:274)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:269)
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:605)
    ... 35 more
</code></pre>

<p>Can you please suggest me on this??</p>
",https://stackoverflow.com/questions/60370765/pre-loading-data-from-sql-before-unit-testing-throws-syntax-error,"['java', 'postgresql', 'spring-boot', 'unit-testing', 'springjunit4classrunner']",877,True,3,1
Sinon how to stub method for unit testing a Async function,"<p>I am trying to write a unit test for an async function using mocha and sinon.js</p>

<p>Below is my test case</p>

<pre><code>  describe('getOperations', function () {
    let customObj, store, someObj
    beforeEach(function () {
      someObj = {
        id: '-2462813529277062688'
      }
      store = {
        peekRecord: sandbox.stub().returns(someObj)
      }
    })
    it('should be contain obj and its ID', function () {
      const obj = getOperations(customObj, store)
      expect(obj).to.eql(someObj)
    })
  })
</code></pre>

<p>Below is the definition of the async function I am testing.</p>

<pre><code>async function getOperations (customObj, store) {
  const obj = foo(topLevelcustomObj, store)
  return obj
}

function foo (topLevelcustomObj, store) {
    return store.peekRecord('obj', 12345)
}
</code></pre>

<p>The test case fails as the promise being return is rejected with a message </p>

<blockquote>
  <p>TypeError: store.query is not a function at Object._callee$.</p>
</blockquote>

<p>The code I am testing is not calling <code>store.query</code> anywhere and also I have stubbed <code>store.peekRecord</code> also so not sure how it is getting called.</p>
",https://stackoverflow.com/questions/59639661/sinon-how-to-stub-method-for-unit-testing-a-async-function,"['javascript', 'unit-testing', 'ember.js', 'sinon', 'sinon-chai']",8606,True,3,1
How to mock repository livedata &amp; ViewModel methods for unit testing,"<p>What is the proper way to test verify <code>viewModel.getMoviesByReleaseDate()</code> gets a <code>List&lt;DiscoverMovie&gt;</code> when <code>repository.getMoviesByReleaseDate()</code> is called on <code>viewModel.init()</code>.</p>

<p>My method <code>testRepoFetchDataSuccess()</code> doesn't achieve the above mentioned.
Kindly provide code example if possible as I'm new to unit testing.</p>

<pre><code>public class TMDbRepository {

    private static final String TAG = ""TMDbRepository"";

    private static final String RELEASE_DATE_LTE = ""2020-02-02"";
    private static final String RELEASE_DATE_DESC = ""release_date.desc"";
    private static final int PAGES_NO = 1;

    private final TMDbWebService webService;

    @Inject
    public TMDbRepository(TMDbWebService webService) {
        this.webService = webService;
    }

    public Single&lt;DiscoverMovieResponse&gt; getMoviesByReleaseDate() {
        return webService
                .getMoviesByReleaseDate(RELEASE_DATE_LTE, RELEASE_DATE_DESC, PAGES_NO);
    }

    public Single&lt;MovieDetails&gt; getMovieDetails(int id) {
        return webService.getMovieDetails(id);
    }
}
</code></pre>

<pre><code>public class MasterFragmentViewModel extends ViewModel {
    private static final String TAG = ""MasterFragmentViewModel"";

    private final RxSingleSchedulers rxSingleSchedulers;
    private final TMDbRepository repository;
    private CompositeDisposable disposable;

    private final MutableLiveData&lt;List&lt;DiscoverMovie&gt;&gt; movies = new MutableLiveData&lt;&gt;();
    private final MutableLiveData&lt;Boolean&gt; error = new MutableLiveData&lt;&gt;();
    private final MutableLiveData&lt;Boolean&gt; loading = new MutableLiveData&lt;&gt;();

    @Inject
    public MasterFragmentViewModel(TMDbRepository repository, RxSingleSchedulers rxSingleSchedulers) {
        this.repository = repository;
        this.rxSingleSchedulers = rxSingleSchedulers;
        disposable = new CompositeDisposable();
    }

    public void init() {
        fetchMoviesByReleaseDate();
    }

    private void fetchMoviesByReleaseDate() {
        loading.setValue(true);

        disposable.add(
                repository.getMoviesByReleaseDate()
                        .compose(rxSingleSchedulers.applySchedulers())
                        .subscribeWith(new DisposableSingleObserver&lt;DiscoverMovieResponse&gt;() {
                            @Override
                            public void onSuccess(DiscoverMovieResponse discoverMovieResponse) {
                                error.setValue(false);
                                movies.setValue(discoverMovieResponse.getMovieList());
                                loading.setValue(false);
//                                Log.d(TAG, ""onSuccess: "" + discoverMovieResponse.getTotalResults());
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.d(TAG, ""onError: "" + e);
                                error.setValue(true);
                                loading.setValue(false);
                            }
                        })
        );
    }

    public LiveData&lt;List&lt;DiscoverMovie&gt;&gt; getMoviesByReleaseDate() {
        return movies;
    }

    public LiveData&lt;Boolean&gt; getError() {
        return error;
    }

    public LiveData&lt;Boolean&gt; getLoading() {
        return loading;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        disposable.clear();
        Log.d(TAG, ""onCleared: disposable cleared!"");
    }
}
</code></pre>

<pre><code>public class MasterFragmentTest {

    @Rule
    public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();
    @Mock
    TMDbRepository repository;
    @Mock
    LifecycleOwner lifecycleOwner;
    @Mock
    Observer&lt;List&lt;DiscoverMovie&gt;&gt; moviesObserver;
    Lifecycle lifecycle;
    private MasterFragmentViewModel viewModel;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        lifecycle = new LifecycleRegistry(lifecycleOwner);
        viewModel = new MasterFragmentViewModel(repository, RxSingleSchedulers.TEST_SCHEDULER);
        viewModel.getMoviesByReleaseDate().observeForever(moviesObserver);
    }

    @Test
    public void testNull() {
        when(repository.getMoviesByReleaseDate()).thenReturn(null);
        assertNotNull(viewModel.getMoviesByReleaseDate());
        assertTrue(viewModel.getMoviesByReleaseDate().hasObservers());
    }

    @Test
    public void testRepoFetchDataSuccess() {
        List&lt;DiscoverMovie&gt; mockList = new ArrayList&lt;&gt;();
        DiscoverMovie discoverMovie = Mockito.mock(DiscoverMovie.class);
        mockList.add(discoverMovie);

        when(repository.getMoviesByReleaseDate()).thenReturn(Single.just(new DiscoverMovieResponse()));
        viewModel.init();
        verify(moviesObserver).onChanged(mockList);
    }

    @After
    public void tearDown() throws Exception {
        repository = null;
        viewModel = null;
    }
}
</code></pre>

<p>Test Result:</p>

<pre><code>Argument(s) are different! Wanted:
moviesObserver.onChanged(
    [Mock for DiscoverMovie, hashCode: 990897274]
);
-&gt; at com.sulaz.tmdb.MasterViewModelTest.testRepoFetchDataSuccess(MasterViewModelTest.java:72)
Actual invocation has different arguments:
moviesObserver.onChanged(
    null
);
-&gt; at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)
</code></pre>
",https://stackoverflow.com/questions/60062395/how-to-mock-repository-livedata-viewmodel-methods-for-unit-testing,"['android', 'junit', 'mockito', 'rx-java2', 'android-livedata']",1823,False,3,0
Create &quot;In Memory Database&quot; in mysql with NodeJs for Jasmine unit testing,"<p>I have a ExpressJs application and unit testing with was done using Jasmine. Currently I'm using real database to run unit tests as well. But I want to do unit testing without using the real database. When I'm searching for a solution I came a cross with the concept of 'In Memory Database'. I read the <a href=""https://dev.mysql.com/doc/refman/8.0/en/memory-storage-engine.html"" rel=""noreferrer"">mysql documentation</a>. And it says we can create a table in memory by giving the engine as Memory </p>

<pre><code>CREATE TABLE t (i INT) ENGINE = MEMORY;
</code></pre>

<p>Is there any possibility that I can create a Memory database and run my all unit tests by staring from creating the memory database, creating all tables and inserting data into that database in runtime by using a backedup .sql file?</p>
",https://stackoverflow.com/questions/60181391/create-in-memory-database-in-mysql-with-nodejs-for-jasmine-unit-testing,"['mysql', 'node.js', 'unit-testing', 'express', 'jasmine']",3495,False,8,2
Unit Testing Angular 9 Component with @Host parameter can&#39;t resolve parameters,"<p>This spec gives me a</p>
<blockquote>
<p>&quot;Error: Can't resolve all parameters for FooComponent: (?).&quot;</p>
</blockquote>
<p>error and I can't see why. Any help on this would be appreciated.</p>
<h3>foo.component.ts</h3>
<pre class=""lang-js prettyprint-override""><code>import {Component, Host } from '@angular/core';
import {BarComponent} from './bar.component';

@Component({
    selector: 'foo',
    template: `&lt;div&gt;foo&lt;/div&gt;`
})
export class FooComponent {
    constructor(@Host() private barComponent: BarComponent) {
        // do something with bar
    }
}
</code></pre>
<h3>bar.comonent.ts</h3>
<pre class=""lang-js prettyprint-override""><code>import {Component, Injectable} from '@angular/core';

@Component({
    selector: 'bar',
    template: `&lt;div&gt;bar&lt;foo/&gt;&lt;/div&gt;`
})
@Injectable()
export class BarComponent { }
</code></pre>
<h3>foo.component.spec.ts</h3>
<pre class=""lang-js prettyprint-override""><code>import {TestBed, async, ComponentFixture} from '@angular/core/testing';
import {FooComponent} from './foo.component';
import {BarComponent} from './bar.component';

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

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [
                FooComponent,
            ],
            providers: [
                BarComponent
            ],
        });
    }));

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

    it('should compile', () =&gt; {
        expect(component).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/63341528/unit-testing-angular-9-component-with-host-parameter-cant-resolve-parameters,"['angular', 'unit-testing', 'testing']",641,True,2,1
How to solve the InvalidPipeArgument &#39;AsyncPipe&#39; error in Angular unit testing?,"<p>I get an <code>InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'</code> error on the unit test when I use the <code>| async</code> pipe in the template.</p>
<p>Tried to solve this with <code>tick, fakeAsync and whenStable</code> but that did not work.</p>
<p>When I remove the <code>| async</code> part in the template, the error disappears and the unit test works but this time the code doesn't work. I need to use the <code>| async</code> in the template to let the code work.</p>
<p>How can I solve this <code>InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'</code> error?</p>
<p>Template:</p>
<pre><code>&lt;ngb-accordion  
    [closeOthers]=&quot;true&quot;  
    [activeIds]=&quot;setActiveAcc()&quot;&gt;
    &lt;div *ngFor=&quot;let child of el?.children | async; let i = index&quot;&gt;
        &lt;ngb-panel id=&quot;{{(child?.value?.properties | async)?.style.includes('OpenAcc')}}-{{i}}&quot;&gt;
            &lt;ng-template ngbPanelHeader&gt;
                &lt;div class=&quot;d-flex align-items-center justify-content-between&quot;&gt;
                    &lt;button ngbPanelToggle class=&quot;btn btn-link container-fluid text-left&quot;&gt;
                        {{ (child?.value?.properties | async)?.content}}
                    &lt;/button&gt;
                &lt;/div&gt;
            &lt;/ng-template&gt;
            &lt;ng-template ngbPanelContent&gt;
                &lt;tst-element [item]=&quot;child&quot;&gt;&lt;/tst-element&gt;
            &lt;/ng-template&gt;
        &lt;/ngb-panel&gt;
    &lt;/div&gt;
&lt;/ngb-accordion&gt;
</code></pre>
<p>Component:</p>
<pre><code>export class AccComponent implements OnInit {
    constructor(
      public el: ItemModelTree
    ) {}

    @Input() childrens: Array&lt;any&gt; = [];

    ngOnInit() {
        this.el.children.pipe(
          mapObservableArray((children: ObservableTree&lt;ItemModel&gt;) =&gt; children.value.properties))
            .subscribe((props: Properties[]) =&gt; {
            this.childrens = props as any;
        });
    }

    setActiveAcc() {
        if (this.childrens.find((child: any) =&gt; child.style.includes('OpenAcc'))) {
          const activeAcc = this.childrens.findIndex((child: any) =&gt; child.style.includes('OpenAcc'));
          return 'true-' + activeAcc;
        } else {
            return 'false'
        }
    }
}
</code></pre>
<p>Unit test:</p>
<pre><code>import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ItemModelTree } from './core';
import { AccComponent } from './accordion.component';
import { of } from 'rxjs';

describe('accardion component', () =&gt; {
  const itemModel = {
    value: {
      name: 'accordion'
    },
    children: [
      {
        id: 'acc-1',
        value: {
          properties: [
            {
              content: 'test',
              style: ['OpenAcc']
            }
          ]
        }
      }
    ],
  };
  const mockTree = jasmine.createSpyObj('el', itemModel);
  mockTree.children = of(itemModel.children);
  
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [AccComponent],
      providers: [
        { provide: ItemModelTree, useValue: mockTree }
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  it('should set the activeAccordion to true', async () =&gt; {
    const fixture = TestBed.createComponent(AccComponent);
    const componentInst = fixture.componentInstance;

    (componentInst as any).tree = {
      children: of([
        {
          id: 'acc-1',
          value: {
            properties: [
              {
                label: 'test',
                styles: ['OpenAcc']
              }
            ]
          }
        }
      ])
    };

    fixture.detectChanges();
    
    
    expect(componentInst).toBeDefined();
    expect(componentInst.setActiveAcc()).toEqual('true-0');
  });
});
</code></pre>
<p>How to solve the <code>InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'</code> error by using the <code>| async</code> pipe?</p>
",https://stackoverflow.com/questions/63229091/how-to-solve-the-invalidpipeargument-asyncpipe-error-in-angular-unit-testing,"['angular', 'jasmine', 'karma-jasmine', 'angular-test']",1939,False,2,1
Angular Unit Testing with Jasmine - Error: Please add an @NgModule annotation,"<p>I'm trying to write a Jasmine Unit Test (with Karma) for an Angular component that uses two services and one form. The tutorials on testing (<a href=""https://angular.io/guide/testing-components-scenarios#component-with-a-dependency"" rel=""nofollow noreferrer"">like this one from the Angular Docs</a>) show only how to test a component with one service and somehow I can't make it work with a bit more complex component:</p>
<p><strong>My component: user-login.component.ts:</strong></p>
<p>The component has a login form, where the user can put in his credentials. <code>OnSubmit</code> I send the provided credentials to an Authentication Service, which handles the http request to my API. If the http response from the API has status 200 it will contain a login token (JWT), which I store with another service that I called TokenStorageService:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { TokenStorageService } from '../../../_services/token-storage.service';
import { AuthenticationService } from '../../../_services/authentication.service';
import { AuthRequest } from '../../../_models/authRequest';

@Component({
  selector: 'app-user-login',
  templateUrl: './user-login.component.html',
  styleUrls: ['./user-login.component.scss']
})
export class UserLoginComponent implements OnInit {

  loginForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
    private tokenStorage: TokenStorageService,
    private authService: AuthenticationService) { }

   ngOnInit() {
     this.loginForm = this.formBuilder.group({
       username: ['', Validators.compose([Validators.required])],
       password: ['', Validators.required]
     });
   }

  onSubmit() {
    this.authService.login({ 
      userName: this.loginForm.controls.username.value, 
      password: this.loginForm.controls.password.value
    })
    .subscribe(data =&gt; {  
      if (data.status === 200) {
        this.tokenStorage.saveToken(data.body)
        console.log(&quot;SUCCESS: logged in&quot;)
      } 
    }
    });
  }
}
</code></pre>
<p><strong>My test: user-login.component.spec.ts:</strong></p>
<p>So I understood that the three things I provide in the constructor (<code>FormBuilder</code>, <code>TokenStorageService</code> and <code>AuthenticationService</code>) I also have to provide in my <code>TestBed</code>. And since I don't really want to inject the services for the Unit test I'm using Stub Services instead. So I did this:</p>
<pre><code>TestBed.configureTestingModule({
      imports: [{HttpClientTestingModule}],
      providers: [{provide: FormBuilder}, { provide: TokenStorageService, useValue: tokenStorageServiceStub }, { provide: AuthenticationService, useValue: authenticationServiceStub }
</code></pre>
<p>The whole test then looks like this:</p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UserLoginComponent } from './user-login.component';
import { FormBuilder } from '@angular/forms';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TokenStorageService } from 'src/app/_services/token-storage.service';
import { AuthenticationService } from 'src/app/_services/authentication.service';

describe('UserLoginComponent', () =&gt; {
  let component: UserLoginComponent;
  let fixture: ComponentFixture&lt;UserLoginComponent&gt;;
  let tokenStorageServiceStub: Partial&lt;TokenStorageService&gt;;
  let authenticationServiceStub: Partial&lt;AuthenticationService&gt;;
  // let tokenStorageService;
  // let authenticationService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [{HttpClientTestingModule}],
      providers: [{provide: FormBuilder}, { provide: TokenStorageService, useValue: tokenStorageServiceStub }, { provide: AuthenticationService, useValue: authenticationServiceStub } ],
      declarations: [ UserLoginComponent ]
    })
    fixture = TestBed.createComponent(UserLoginComponent);
    component = fixture.componentInstance;
    // tokenStorageService = TestBed.inject(TokenStorageService);
    // authenticationService = TestBed.inject(AuthenticationService);
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p>I commented 4 lines out since I think they are wrong, but in the <a href=""https://angular.io/guide/testing-components-scenarios#component-with-a-dependency"" rel=""nofollow noreferrer"">the Angular Docs example</a> they are also injecting the real services, even tough they say they don't want to use the real services in the test. I don't understand that part in the Docs example?</p>
<p>But either way I keep getting this Error message:</p>
<p><a href=""https://i.stack.imgur.com/FCLd6.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/FCLd6.png"" alt=""enter image description here"" /></a></p>
<p>Since the error says something about <code>@NgModule</code> I think it may has to do with my <code>app.module.ts</code> file? Here is my <code>app.module.ts</code>:</p>
<pre><code>@NgModule({
 declarations: [
   AppComponent,
   SidebarComponent,
   UsersComponent,
   DetailsComponent,
   ProductsComponent,
   UploadFileComponent,
   GoogleMapsComponent,
   AddUserComponent,
   ProductFormComponent,
   UserLoginComponent,
   EditUserComponent,
   ProductDetailsComponent,
   MessagesComponent,
   MessageDetailsComponent,
   ChatComponent,
   UploadMultipleFilesComponent,
   InfoWindowProductOverviewComponent,
   AddDormComponent,
   AddProductComponent
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   HttpClientModule, 
   BrowserAnimationsModule,
   FormsModule,
   ReactiveFormsModule,
   ImageCropperModule,
   DeferLoadModule,
   //Angular Material inputs (spezielle UI Elemente)
   MatDatepickerModule,
   MatInputModule,
   MatNativeDateModule,
   MatSliderModule,
   MatSnackBarModule,
   MatSelectModule,
   MatCardModule,
   MatTooltipModule,
   MatChipsModule,
   MatIconModule,
   MatExpansionModule,
   MDBBootstrapModule,
   AgmCoreModule.forRoot({
     apiKey: gmaps_environment.GMAPS_API_KEY 
   })
  ],
  providers: [
   UploadFileService, 
   {provide: MAT_DATE_LOCALE, useValue: 'de-DE'},   
   {provide:HTTP_INTERCEPTORS, useClass:BasicAuthHttpInterceptorService, multi:true},
 ],   
 bootstrap: [AppComponent],
})
export class AppModule { }
</code></pre>
",https://stackoverflow.com/questions/63533754/angular-unit-testing-with-jasmine-error-please-add-an-ngmodule-annotation,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",2288,True,2,5
Unit testing Spring-WS SOAP endpoint fails in MockFilterChain returning 404,"<p>I have used Spring-WS to write a SOAP endpoint, and am now in the process of writing some tests.  However, when I try to send my request, I am getting a 404 occurring in <code>doFilter()</code> of the <code>MockFilterChain</code> class of Spring and I can't figure out why.  Is there something else I need to mock?</p>

<p>My endpoint is a SOAP simulator, which pulls in the WSDL-generated source files it uses from another package in my project to avoid unnecessary duplication.  So I do not have direct access to the WSDL files as a classpath resource.</p>

<p>My project looks like this:</p>

<p><strong>Endpoint</strong></p>

<pre><code>import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

@Endpoint
public class MockSoapEndpoint {

    private final ObjectFactory objectFactory = new ObjectFactory();

    ...
    ...

    @PayloadRoot(namespace = NAMESPACE, localPart = ""soapEndpoint"")
    @ResponsePayload
    public JAXBElement&lt;MySoapResponse&gt; chargeVolume(@RequestPayload JAXBElement&lt;MySoapRequest&gt; request) {
        ...
        ...
    }
</code></pre>

<p><strong>Config</strong></p>

<pre><code>@EnableWs
@Configuration
public class MockSoapConfig extends WsConfigurerAdapter {

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(final ApplicationContext applicationContext) {
        MessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet();
        messageDispatcherServlet.setApplicationContext(applicationContext);
        messageDispatcherServlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(messageDispatcherServlet, ""/ws/*"");
    }
}
</code></pre>

<p><strong>Test</strong></p>

<pre><code>@WebMvcTest
@ContextConfiguration(classes = { MockSoapConfig.class, MockSoapEndpoint.class })
@ExtendWith(SpringExtension.class)
class MockSoapEndpointTest {

    private static final String SOAP_REQUEST = """"
                    + ""&lt;soapenv:Envelope xmlns:soapenv=\""http://schemas.xmlsoap.org/soap/envelope/\""\n""
                    + ""&lt;soapenv:Header/&gt;...""&lt;/soapenv:Envelope&gt;\n"";

    @Autowired
    private MockMvc mockMvc;

    @Test
    void givenNonRejectedMdnReturnChargingInformationWithCorrectMinMajCodes() throws Exception {

        final String endpoint = ""http://localhost:8080/ws"";

        mockMvc.perform(post(endpoint).contentType(MediaType.TEXT_XML)
                                  .content(SOAP_REQUEST)
                                  .accept(MediaType.TEXT_XML))
               .andExpect(status().isOk());
    }
}
</code></pre>

<p>This test returns the <code>404</code> response code, rather than the <code>200</code> I'm expecting.  When I manually test the endpoint, using <code>http://localhost:8080/ws</code> and the same XML chunk, it works fine.</p>
",https://stackoverflow.com/questions/60043767/unit-testing-spring-ws-soap-endpoint-fails-in-mockfilterchain-returning-404,"['java', 'spring', 'soap', 'junit5', 'spring-ws']",1189,True,2,1
Moq object returning another Moq object (unit testing the strategy pattern),"<p>I have a class that is a consumer of the strategy pattern that I would like to unit test. It has a dependency on an IResolver type class that returns some instance of an ICalculator type class. So I need a Moq object that represents the resolver &amp; when called, returns another Moq object that represents the calculator. I have this test below:</p>

<pre><code>public void UpperScoreManager_AddScoring_UpdatesScoreCorrectly()
{
   var expectedScore = 10;
   var mockCaluclator = new Mock &lt; IScoreCategoryCalculator &gt; ();
   mockCaluclator.Setup(c =&gt; c.CalculateScore(It.IsAny &lt; DiceSet &gt; ()))
    .Returns(expectedScore);

   var mockResolver = new Mock &lt; IScoreCategoryCalculatorResolver &gt; ();
   mockResolver.Setup(r =&gt; r.Resolve(It.IsAny &lt; ScoreCategories &gt; ()))
    .Returns(mockCaluclator.Object);

   var manager = new Managers.ScoreManager.UpperScoreManager.UpperScoreManager(mockResolver.Object);

   manager.AddScoring(ScoreCategories.Aces, DiceSet.Create(new int[] { 1, 2, 3, 4, 5 }));

   Assert.Equal(expectedScore, manager.Score);
}
</code></pre>

<p>And here is the function being tested</p>

<pre><code>public void AddScoring(ScoreCategories category, DiceSet diceSet)
{
    IScoreCategoryCalculator scoreCalculator = _scoreCalculatorResolver.Resolve(category);
    Score += scoreCalculator.CalculateScore(diceSet);
}
</code></pre>

<p>The unit test fails due to some error with the Moq setup:</p>

<blockquote>
  <p>System.ArgumentException : Object of type 'Yahtzee.Core.Enums.ScoreCategories' cannot be converted to type 'Yahtzee.Core.Interfaces.IScoreCategoryCalculator'</p>
</blockquote>

<p>I don't understand this error (I don't receive this until I actually run the unit test). When I debug the test, the first line of my function under test works correctly </p>

<pre><code>IScoreCategoryCalculator scoreCalculator = _scoreCalculatorResolver.Resolve(category);
</code></pre>

<p>So my mock resolver is resolving some <code>IScoreCategoryCalculator</code>. The next line, however, is where the failure occurs. If I do a <code>QuickWatch</code> on that line in Visual Studio I can see this:</p>

<p><a href=""https://i.stack.imgur.com/QfkX7.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QfkX7.png"" alt=""Visual Studio Error Message""></a></p>

<p>Any idea what I'm doing incorrectly here? Can Moq return another Moq object?</p>

<p><strong>EDIT</strong> The interfaces being mocked look as so:</p>

<pre class=""lang-cs prettyprint-override""><code>public interface IScoreCategoryCalculator
{
    ScoreCategories Type { get; }
    int CalculateScore(DiceSet diceSet);
}

public interface IScoreCategoryCalculatorResolver
{
    IScoreCategoryCalculator Resolve(ScoreCategories scoreCategory);
}
</code></pre>

<p><strong>EDIT 2</strong> Showing full stack </p>

<blockquote>
  <p>Stack Trace: 
      RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
      RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
      MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
      RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
      RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
      Delegate.DynamicInvokeImpl(Object[] args)
      Delegate.DynamicInvoke(Object[] args)
      Extensions.InvokePreserveStack(Delegate del, Object[] args)
      ReturnLazyValueResponse.RespondTo(Invocation invocation)
      MethodCall.Execute(Invocation invocation)
      FindAndExecuteMatchingSetup.Handle(Invocation invocation, Mock mock)
      IInterceptor.Intercept(Invocation invocation)
      Interceptor.Intercept(IInvocation invocation)
      AbstractInvocation.Proceed()
      IScoreCategoryCalculatorResolverProxy.Resolve(ScoreCategories scoreCategory)
      UpperScoreManager.AddScoring(ScoreCategories category, DiceSet diceSet) line 32
      UpperScoreManagerTests.UpperScoreManager_AddScoring_UpdatesScoreCorrectly() line 18</p>
</blockquote>
",https://stackoverflow.com/questions/60932646/moq-object-returning-another-moq-object-unit-testing-the-strategy-pattern,"['c#', 'unit-testing', 'moq', 'xunit']",191,False,2,0
Unit Testing Static Methods with ILogger in C# ILoggerFactory is Null,"<p>everyone,</p>
<p>I'm trying to do unit tests of my code, however I'm not able to get the ILoggerFactory to work</p>
<p><strong>This is my unit test code (it may not be correct):</strong></p>
<pre><code>using NUnit.Framework;
using Microsoft.Extensions.Logging;
using System.Reflection;
using Moq;
using System;
using MyProgramVIP.Bots.Presenter;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Utils;

namespace MyProgramVIPTest
{
    public class TestsExample
    {
        [SetUp]
        public void Setup() {
            
        }

        [Test]
        public void TestExample1()
        {
            //Mocks
            var mockLogger = new Mock&lt;ILogger&lt;TicketPresenter&gt;&gt;();
            mockLogger.Setup(
                m =&gt; m.Log(
                    LogLevel.Information,
                    It.IsAny&lt;EventId&gt;(),
                    It.IsAny&lt;object&gt;(),
                    It.IsAny&lt;Exception&gt;(),
                    It.IsAny&lt;Func&lt;object, Exception, string&gt;&gt;()));

            var mockLoggerFactory = new Mock&lt;ILoggerFactory&gt;();
            mockLoggerFactory.Setup(x =&gt; x.CreateLogger(It.IsAny&lt;string&gt;())).Returns(() =&gt; mockLogger.Object);

            //Construción del modelo necesario para la prueba
            ConversationData conversationData = new ConversationData();
            conversationData.ticket = new Ticket();
            conversationData.response = new Response();

            //Invocación del método a probar
            TicketPresenter.getPutTicketMessage(conversationData);

            //Comprobación del funcionamineto
            Assert.AreEqual(&quot;ticketType&quot;, conversationData.response.cardIdResponse);
        }
    }
}
</code></pre>
<p><strong>This is the code of the class I want to test (I've only left the lines of code that fail)</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using MyProgramVIP.Bots.Interactor.Services;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Utils;

namespace MyProgramVIP.Bots.Presenter
{
    public class TicketPresenter
    {
        private static ILogger _logger = UtilsVIP.ApplicationLogging.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

        /// &lt;summary&gt;
        /// Función getPutTicketMessage: encargada de comenzar con el flujo de poner un ticket.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;conversationData&quot;&gt;&lt;/param&gt;
        public static void getPutTicketMessage(ConversationData conversationData)
        {
            try
            {
                //Here it crash.
                _logger.LogInformation(&quot;INIT getPutTicketMessage&quot;);

                //Code..........

                //Never gets here.
                _logger.LogInformation(&quot;ENDED getPutTicketMessage&quot;);
            }
            catch (Exception ex)
            {
                //Here it crash too.
                _logger.LogError(&quot;EXCEPTION getPutTicketMessage&quot; + ex.ToString());
            }
        }
}
</code></pre>
<p><strong>This is the code for the help class that's right where the error is:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using MyProgramVIP.Bots.Model;
using MyProgramVIP.Bots.Model.Elements;

namespace MyProgramVIP.Bots.Utils
{
    public class UtilsVIP
    {
        private static ILogger _logger = ApplicationLogging.CreateLogger(&quot;ILogger&quot;);

        //Other funtions...

        public static class ApplicationLogging
        {
            public static ILoggerFactory LoggerFactory { get; set; }
            public static ILogger CreateLogger&lt;T&gt;() =&gt; LoggerFactory.CreateLogger&lt;T&gt;();
            //Here LoggerFactory is null.
            public static ILogger CreateLogger(string categoryName) =&gt; LoggerFactory.CreateLogger(&quot;VIPLog: &quot; + categoryName);

        }

        //Other funtions...
    }
}
</code></pre>
<p>Right on the line where it runs:</p>
<pre><code>LoggerFactory.CreateLogger(&quot;VIPLog: &quot; + categoryName);
</code></pre>
<p><em><strong>LoggerFactory is null.</strong></em></p>
<p>I've done a lot of research on the internet, however it all leads to non-static class information.</p>
<p>In case it's important, it's a Botframework project.</p>
<p>Any help would be appreciated.</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/63574805/unit-testing-static-methods-with-ilogger-in-c-iloggerfactory-is-null,"['c#', 'unit-testing', 'botframework', 'ilogger', 'iloggerfactory']",1275,True,2,2
"Unit Testing Using Jest and AWS-SDK-Mock, Mock DynamoDB Scan","<p>Jumping into Jest and unit testing lambda functions.  I'm trying to mock the aws dynamodb-document client scan in my unit test.  I'm getting back the actual scan from the real db though so i know something with my mock isn't working.  This is my .test.js:</p>
<pre><code>var AWS = require('aws-sdk-mock');
const sinon = require('sinon');
let index = require('./index.js');


beforeEach(()=&gt; {
    AWS.mock('DynamoDB.DocumentClient', 'scan', function(params, callback) {
        callback(null, {test: &quot;value&quot;});
    })
  });

  afterEach(()=&gt; {
      AWS.restore();
  });

    it( 'test invocation', async() =&gt; {
        console.log(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;)
      const result = await index.handler({}, {}, (err, result) =&gt; {
          expect(result).toEqual({test: &quot;value&quot;});
  });
  });
</code></pre>
<p>My actual lambda function code looks like this:</p>
<pre><code>'use strict';

var AWS = require(&quot;aws-sdk&quot;);
var DOC = require(&quot;dynamodb-doc&quot;);
AWS.config.update({region: &quot;us-east-1&quot;//,
    });
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
    TableName: &quot;table-name&quot;,
    FilterExpression: &quot;#PK = :cat_val&quot;,
    ExpressionAttributeNames: {&quot;#PK&quot;: &quot;PK&quot;,},
    ExpressionAttributeValues: { &quot;:cat_val&quot;: &quot;Value&quot;}
};

exports.handler = (event, context, callback) =&gt; {
    var response; 
    
    docClient.scan(params, onScan);
    function onScan(err, data) {
        if (err) {
            response = {
                statusCode: 500,
                body: &quot;Unable to complete scan.  Error JSON: &quot; + JSON.stringify(err,null,2)
            }
        } else {
            data.Items.sort(compare);
            response = {
                statusCode: 200,
                body: data.Items
            }
        }

        callback(null, response);
        console.log(response);
    }
}
</code></pre>
<p>Any direction you guys can point me in.  The test fails on the equal compare because it has the actual response from the Dynamo scan.</p>
<p>Thanks,
Tim</p>
",https://stackoverflow.com/questions/62604392/unit-testing-using-jest-and-aws-sdk-mock-mock-dynamodb-scan,"['node.js', 'jestjs', 'aws-sdk', 'aws-sdk-mock']",1668,False,1,1
Unit testing automapper to return count of users in a role,"<p>I would like to <code>unit test</code> this <code>Controller</code>. It returns the name of the <code>role</code> and the <code>count</code> of <code>users</code> that belong to that <code>role</code>:</p>

<pre><code>    [HttpGet]
    [EnableQuery]
    public IEnumerable&lt;RoleDto&gt; Get()
    {
        var roles = dbContext.Roles.ToList();

        return roles.Select(r =&gt;
        {
            var dto = mapper.Map&lt;RoleDto&gt;(r);
            dto.UserCount = dbContext.UserRoles.Count(x =&gt; x.RoleId == r.Id); 
            return dto;
        }).ToList();
    }
</code></pre>

<p>And here is my test - The <code>DTO</code> is always <code>null</code> and later throws an <code>exception</code>. I am unable to <code>map</code> this properly.</p>

<p>It is a simple <code>unit test</code> that creates a <code>user</code>, creates <code>roles</code> and add the <code>user</code> to those <code>roles</code>.  </p>

<p>It then checks if a <code>user</code> has been added to that <code>role</code>.</p>

<pre><code>    [Test]
    public async Task Get_Should_Return_List_OfRoles()
    {
        TestSetup();
        var mapperMock = new Mock&lt;IMapper&gt;();
        IdentityRole role = null;

        mapperMock.Setup(u =&gt; u.Map&lt;RoleDto&gt;(It.IsAny&lt;IdentityRole&gt;()))
            .Callback&lt;object&gt;(inputargs =&gt; role = inputargs as IdentityRole);
        var roleManagerWrapperMock = new Mock&lt;IRoleManagerWrapper&gt;();

        var admin = new IntentUser
        {
            UserName = ""Administrator2"",
            Email = ""admin2@intent2.app"",
            EmailConfirmed = true,
            IsEnabled = true,
            IsSystemUser = true
        };

        var adminRole = new IdentityRole()
        {
            Name = ""Admin""
        };

        var managerRole = new IdentityRole()
        {
            Name = ""Manager""
        };
        ApplicationDbContext.Users.Add(admin);
        ApplicationDbContext.Roles.Add(managerRole);
        ApplicationDbContext.Roles.Add(adminRole);

        ApplicationDbContext.SaveChanges();

        var adminRoleAdded = new IdentityUserRole&lt;string&gt;()
        {
            RoleId = adminRole.Id,
            UserId = admin.Id
        };

        var managerRoleAdded = new IdentityUserRole&lt;string&gt;()
        {
            RoleId = managerRole.Id,
            UserId = admin.Id
        };

        ApplicationDbContext.UserRoles.Add(adminRoleAdded);
        ApplicationDbContext.UserRoles.Add(managerRoleAdded);
        ApplicationDbContext.SaveChanges();

            var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, mapperMock.Object);
            var result = sut.Get();
            foreach (var roleDto in result)
            {
                Assert.AreEqual(roleDto.UserCount, 1);
            }
    }

    protected void TestSetup(string databaseName = null)
    {
        if (databaseName == null)
        {
            databaseName = GetTestName();
        }

        TestCleanup();
        ServiceProvider = new ServiceCollection()
            .AddEntityFrameworkInMemoryDatabase()
            .BuildServiceProvider();

        dbContextOptions = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()
            .UseInMemoryDatabase(databaseName)
            .UseInternalServiceProvider(ServiceProvider)
            .Options;

        ApplicationDbContext = new ApplicationDbContext(dbContextOptions);
    }
</code></pre>
",https://stackoverflow.com/questions/59789386/unit-testing-automapper-to-return-count-of-users-in-a-role,"['c#', 'unit-testing']",100,True,2,1
how to pass an event object to triggerEventHandler in unit testing?,"<p>I have an event defined in the HTML file as :</p>

<pre><code>(keyup)=""onKeySearch($event)""
</code></pre>

<p>Now i am stimulating this event using triggerEventHandler as follows in my spec file:</p>

<pre><code> const input = fixture.debugElement.query(By.css('input'));
  input.triggerEventHandler('keyup', {});
</code></pre>

<p>My query is that do we need to supply anyother parameter to the triggerEventHandler ,as the keyup event is calling the method with $event.
Thanks in advance.</p>
",https://stackoverflow.com/questions/62282027/how-to-pass-an-event-object-to-triggereventhandler-in-unit-testing,"['angular', 'unit-testing', 'karma-jasmine']",2304,True,2,1
Why should we use Jasmine Spy Object in Angular Unit Testing?,"<p>I have a query regarding Angular unit testing using Jasmin/Karma.</p>
<p>I have 3 services as below: EmployeeService, SalaryService and TaxationService.</p>
<p>EmployeeService depends on SalaryService which is injected in it's constructor.</p>
<p>SalaryService depends on Taxation service which is again injected in it's constructor.</p>
<p>In my employee.component.spec.ts, I have the below code:</p>
<pre><code>let employeeService: EmployeeService;
let salaryServiceSpy: jasmine.SpyObj&lt;SalaryService&gt;;

TestBed.configureTestingModule({
 providers: [EmployeeService],
 declarations: [ EmployeeComponent ]
})
.compileComponents();
  employeeService = TestBed.inject(EmployeeService);
  salaryServiceSpy = TestBed.inject(SalaryService) as jasmine.SpyObj&lt;SalaryService&gt;;
}));

it('should return Name and Salary', () =&gt; {
  expect(employeeService.getEmployeeNameAndSalary(1)).toBe(&quot;John Smith receives: $12345 and tax value of 15%&quot;);
});
</code></pre>
<p>The code works fine, my question is why do we need to use Jasmine Spy - the code works fine without the spy service as well?</p>
<pre><code> salaryServiceSpy = TestBed.inject(SalaryService) as jasmine.SpyObj&lt;SalaryService&gt;;
</code></pre>
<p>I have used the below as reference: <a href=""https://angular.io/guide/testing-services"" rel=""nofollow noreferrer"">https://angular.io/guide/testing-services</a>.</p>
<p>If below example is more clear, what is the need to create the ValueServiceSpy? Does the TestBed.inject not already inject all dependencies and the 'dependencies of the other dependencies'?</p>
<p><a href=""https://i.stack.imgur.com/bGeWP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/bGeWP.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63578246/why-should-we-use-jasmine-spy-object-in-angular-unit-testing,"['angular', 'typescript', 'unit-testing', 'dependency-injection', 'karma-jasmine']",2769,True,2,1
Unit testing suspend function fails for LiveData but pass for Flow,"<p>I am trying to write unit test for suspend function that emits 2 values, first is something like Loading, second is actual data. There is some inconsistency and I don't understand why it's happening. To keep it simple, here is small example with emitting few numbers (emitted type should not matter).</p>
<pre><code>class Foo(private val dispatcher: CoroutineDispatcher) {

    suspend fun barLiveData(count: Int): LiveData&lt;Int&gt; = liveData(dispatcher) {
        (1..count).forEach {
            emit(it)
            //delay(500)
        }
    }

    suspend fun barFlow(count: Int): Flow&lt;Int&gt; = flow {
        (1..count).forEach {
            emit(it)
            //delay(500) 
        }
    }

}
</code></pre>
<p>Two suspend functions, first returns LiveData, second returns Flow. Otherwise those functions are same. If there is no delay, results of unit tests are different. If there is at least 1 ms delay in <code>barLiveData</code> function, unit test pass.</p>
<p>I have these unit tests.</p>
<pre><code>class FooTest {

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    val mainCoroutineRule = MainCoroutineRule()

    val foo = Foo(mainCoroutineRule.testDispatcher)

    @Test
    fun `test barLiveData`() = runBlockingTest {
        val values = foo.barLiveData(count).asFlow().take(count).toList()
        println(&quot;test barLiveData result is ${values}&quot;)
    }

    @Test
    fun `test barFlow`() = runBlockingTest {
        val values = foo.barFlow(count).take(count).toList()
        println(&quot;test barFlow result is ${values}&quot;)
    }

    companion object {
        const val count = 5
    }

}
</code></pre>
<p>TestCoroutineDispatcher is used as Dispatcher for Foo class, MainCoroutineRule sets Dispatchers Main, resets it and calls cleanupTestCoroutines.</p>
<p>When I run these tests, <code>test barFlow</code> pass, <code>test barLiveData</code> fails with <code>java.lang.IllegalStateException: This job has not completed yet</code>.</p>
<p>If there is at least 1 ms delay in <code>barLiveData </code> function, <code>test barLiveData</code> pass. Test <code>test barFlow</code> pass always.</p>
<p>Am I doing something wrong? Should test be written differently?</p>
<p>Thank you.</p>
<p><em>Edit: Suggested solution.</em>
I still don't understand, why there is different result, but I have a solution for my problem.
When I use observerForever, I can get all values that are added to LiveData.</p>
<pre><code>val values = mutableListOf&lt;T&gt;()
observeForever{
  values.add(it)
}
</code></pre>
<p>From this list it is possible to check if data states are correct and in correct order.</p>
<p>I am not sure, if observeForever in Unit Test is a problem or not. But in any case, here is some LiveData extension function that removes observer</p>
<pre><code>    fun &lt;T&gt; LiveData&lt;T&gt;.getAllValues(): List&lt;T&gt; {
        val values = mutableListOf&lt;T&gt;()
        val observer = object: Observer&lt;T&gt; {
            override fun onChanged(t: T) {
                values.add(t)
            }
        }
        this.observeForever(observer)
        removeObserver(observer)
        return values
    }
</code></pre>
<p>This works if there is no delay in function under test. I think that should not be a problem, if production code is under test.</p>
",https://stackoverflow.com/questions/64827863/unit-testing-suspend-function-fails-for-livedata-but-pass-for-flow,"['android', 'unit-testing', 'junit', 'android-livedata', 'kotlin-coroutines']",535,False,1,0
react useEffect is not being executed when unit testing with enzyme,"<p>I have a component that uses <code>useEffect</code> its making an api call to redux action called   <code>props.getPostsInit();</code></p>

<p>How would i test this, as of now im getting an error, its not calling the getPostsInit prop</p>

<pre><code>  ● &lt;Dashboard/&gt; › Should execute getPostsInit

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: &gt;= 1
    Received number of calls:    0
</code></pre>

<p><strong>Dashboard</strong></p>

<pre><code>function Dashboard(props: dashboardProps) {
    // const [title, setTitle] = useState&lt;string&gt;("""");
    // const [content, setContent] = useState&lt;string&gt;("""");
    // const [value, setValue] = useState&lt;number&gt;(0);
    const didMountRef = useRef&lt;Object&gt;();
    useEffect(() =&gt; {
        if (!didMountRef.current) {
            props.getPostsInit();
            props.initCommentUpdates();
        } else {
            console.log(""this is component didupdate"");
        }
    }, []); // array prevents an infinite loop
   ......
</code></pre>

<p><strong>Dashboard.test</strong></p>

<pre><code>import React from ""react"";
import { DashboardComponent as Dashboard } from ""./dashboard"";
import { shallow, mount, render } from ""enzyme"";
import PostForm from ""../../components/forms/createPost/createPost"";
describe(""&lt;Dashboard/&gt;"", () =&gt; {
    let wrapper;
    let useEffect;
    const mockUseEffect = () =&gt; {
        useEffect.mockImplementationOnce((f) =&gt; f());
    };
    const props = {
        getPostsInit: jest.fn(),
        getPopPostsInit: jest.fn(),
        deletePostInit: jest.fn(),
        postCommentInit: jest.fn(),
        titleError: Boolean,
        bodyError: Boolean,
        posts: [],
        error: [],
        title: ""Test"",
        postContent: ""Another test"",
        addTitle: jest.fn(),
        addContent: jest.fn(),
        popPosts: [],
        createPostInit: jest.fn(),
        likePost: jest.fn(),
        dislikePost: jest.fn(),
        initCommentUpdates: jest.fn(),
    };
    beforeEach(() =&gt; {
        useEffect = jest.spyOn(React, ""useEffect"");
        mockUseEffect();
        wrapper = shallow(&lt;Dashboard {...props} /&gt;);
    });

    it(""Should render dashboard component"", () =&gt; {
        expect(wrapper).toHaveLength(1);
    });

    it(""Should execute getPostsInit"", () =&gt; {
        expect(props.getPostsInit).toHaveBeenCalled();
    });

});
</code></pre>
",https://stackoverflow.com/questions/60160516/react-useeffect-is-not-being-executed-when-unit-testing-with-enzyme,"['reactjs', 'jestjs', 'enzyme']",2389,True,1,2
Looker Unit Testing value in developmentg against a value in development,"<p>I would like to write a unit test that checks whether a value in the development environment matched the value in production in Looker. At the moment I can check values against a static hardcoded value, but not able to check dynamically</p>

<pre><code>test: 5_test_impacted_engineers_with_new_eng_levels{
  explore_source: fellow{
    column:impacted_engineers{
      field:fellow.count
    }

    filters: {
      field: fellow.eng_level
      value: ""Eng1, Eng2, Eng3, Eng4, Eng5, Eng6, Eng7""


    }
    filters: {
      field:fellow_promotion_dates.impacted_engineers
      value: ""yes""
    }

  }
##impacted engineers should not have had eng levels, yes?
  assert: expected_impacted_new_levels {
    expression: ${fellow.count}=0;;

  }
}
</code></pre>
",https://stackoverflow.com/questions/59580198/looker-unit-testing-value-in-developmentg-against-a-value-in-development,['looker'],58,False,1,0
Mapper function in Web API Controller returns null during unit testing,"<p>I am making a ASP.NET core web api and I have used Entity Framework Core. I am trying to unit test the controllers using N-Unit
I am mocking the mapper and the repository. The APIs work fine and I have even created the front end or the API but I am having issues with the unit testing.</p>
<p>Controller Code-</p>
<pre><code>[AllowAnonymous]
    [HttpGet(&quot;{id}&quot;)]
    public async Task&lt;IActionResult&gt; GetMovie(int id)
    {
        var movie = await _repo.GetMovie(id);
        if (movie == null)
        {
            return BadRequest(&quot;Object with Id not found&quot;);
        }
        var movieToReturn = _mapper.Map&lt;MovieForDetailedDto&gt;(movie);
        return Ok(movieToReturn);
    }

    [AllowAnonymous]
    [HttpPost()]
    public async Task&lt;IActionResult&gt; AddMovie(MovieForDetailedDto movieForDetailedDto)
    { 
        if (await _repo.MovieExists(movieForDetailedDto.ATitle))
            return BadRequest(&quot;movie already exists&quot;);

        else if(!ModelState.IsValid || movieForDetailedDto.ATitle == null || movieForDetailedDto.APrice == null || movieForDetailedDto.AMovieDescription ==null)
        {
            return BadRequest(&quot;movie details not valid&quot;);
        }

        var movieToCreate = _mapper.Map&lt;TblMovie&gt;(movieForDetailedDto);

        var createdMovie = await _repo.AddMovie(movieToCreate);

        return Ok(createdMovie);
    }
</code></pre>
<p>In all my functions, in the line where I map the DTO to the Model, the Line returns a null object during unit testing but the they work fine outside of unit testing.</p>
<p>My Unit Test Code for the controller-</p>
<pre><code>[TestFixture]
public class MoviesControllerTests
{
    private Mock&lt;IMovieRepository&gt; _mockMovieRepository;
    private Mock&lt;IMapper&gt; _mockMovieMapper;
    private MoviesController _moviesController;
    [Test]
    public async Task CallGetRequest_WhenCalledWithId_ReturnsTheMovieWithTheSameId()
    {
        getMoviesHelper getMoviesHelper = new getMoviesHelper();
        List&lt;TblMovie&gt; movieList = getMoviesHelper.getMovieFromList();
        var movie = getMoviesHelper.movieById(3);
        _mockMovieRepository = new Mock&lt;IMovieRepository&gt;();
        _mockMovieMapper = new Mock&lt;IMapper&gt;();
        _mockMovieMapper.Setup(mapper =&gt; mapper.Map&lt;TblMovie&gt;(It.IsAny&lt;MovieForDetailedDto&gt;()))
            .Returns(getMoviesHelper.movieById(3));
        _mockMovieRepository.Setup(repo =&gt; repo.GetMovie(3))
                .ReturnsAsync(getMoviesHelper.movieById(3));
        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.GetMovie(3);
        var okResult = tblMovie as OkObjectResult;
        //Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(tblMovie);
        Assert.IsAssignableFrom&lt;OkObjectResult&gt;(tblMovie);
        var result = ((OkObjectResult)tblMovie).Value;
        var resultValue = ((OkObjectResult)tblMovie).Value as TblMovie;
        Assert.AreEqual(resultValue.ATitle,&quot;Raging Bull&quot;);
        Assert.NotNull(result);
        Assert.IsAssignableFrom&lt;TblOrder&gt;(result);
    }

    [Test]
    public async Task GivenAValidMovie_WhenIPostANewMovie_ThenItReturnsOkWithResponse()
    {
        _mockMovieRepository = new Mock&lt;IMovieRepository&gt;();
        _mockMovieMapper = new Mock&lt;IMapper&gt;();
        _mockMovieMapper.Setup(mapper =&gt; mapper.Map&lt;TblMovie&gt;(It.IsAny&lt;MovieForDetailedDto&gt;()))
            .Returns(new TblMovie());
        _mockMovieRepository.Setup(repo =&gt; repo.AddMovie(It.IsAny&lt;TblMovie&gt;()))
            .ReturnsAsync((TblMovie movie) =&gt; movie);

        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.AddMovie(new MovieForDetailedDto
        {
            AMovieId = 55,
            ATitle = &quot;redemption&quot;,
            AMovieDescription = &quot;An action comedy adventure about brilliant robotics prodigy Hiro Hamada, who finds himself in the grips of a criminal plot that threatens to destroy the fast-paced, high-tech city of San Fransokyo. With the help of his closest companion-a robot named Baymax-Hiro joins forces with a reluctant team of first-time crime fighters on a mission to save their city.&quot;,
            ADuration = &quot;105 min&quot;,
            APrice = &quot;10&quot;,
            APurchasePrice = &quot;25&quot;,
            ARating = 5,
            AImageLink = &quot;http://upload.wikimedia.org/wikipedia/en/4/4b/Big_Hero_6_%28film%29_poster.jpg&quot;,
            ATrailerLink = &quot;//www.youtube.com/embed/z3biFxZIJOQ&quot;,
            AGenre = &quot;Comedy&quot;,
            AWideImage = &quot;https://github.com/tushar23091998/MovieRentalApp-FrontEnd/blob/master/src/app/images/bighero6.jpg?raw=true&quot;
        });
        var okResult = tblMovie as OkObjectResult;
        Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(okResult);
        Assert.IsAssignableFrom&lt;OkObjectResult&gt;(tblMovie);
        var result = ((OkObjectResult)tblMovie).Value;
        Assert.NotNull(result);
        Assert.IsAssignableFrom&lt;TblMovie&gt;(result);
    }
</code></pre>
<p>In both the test cases and even in other test cases, the repo setup works fine but after defining the controller and when I call the controller function to get the value, I found in debugging that the mapper line in controller code returns null.</p>
<p>I am not sure how go about setting up the mockmapper now and how should I pass the value.</p>
<p>Debugging Output -
<a href=""https://i.stack.imgur.com/9gsTf.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9gsTf.png"" alt=""Mapper return object value during debugging"" /></a></p>
",https://stackoverflow.com/questions/64329254/mapper-function-in-web-api-controller-returns-null-during-unit-testing,"['c#', 'unit-testing', 'nunit', 'automapper', 'asp.net-core-webapi']",863,True,1,1
How to switch between different types of R in unit testing,"<p>I want to create unit testing for different versions of R e.g. 3.6.3, 4.0 etc. I know that I can install older versions of R and try unit testing for each of them, but is there any possibility how can I do it in easier way ? For example artificially provide other R versions and loop them ?</p>
",https://stackoverflow.com/questions/64928848/how-to-switch-between-different-types-of-r-in-unit-testing,"['r', 'unit-testing', 'version']",23,False,1,0
Unit Testing One Method Calls Another Method in the Same Class,"<p>I have two public methods on a class, both are called from external code, but one of the methods also calls the other. I want to unit test the one method and just verify it calls the other public method in the same class, and then I would have separate tests to test the other second method. The structure would look something like this:</p>

<pre><code>public CalculatedResult GetCalculatedDetailsById(Guid id)
{
  var entity = _entityRepository.GetEntity(id);
  if(entity == null)
  {
    throw new NotFoundException();
  }

  return GetCalculatedDetailsForEntity(entity);
}

public CalculatedResult GetCalculatedDetailsForEntity(Entity entity)
{
  var supplementalData = _someDependency.GetSupplementalData(entity.Property);
  var calculatedData = _someOtherDependency.ProcessEntity(entity, supplementalData);

  _cache.Set(calculatedData, expiry);

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

<p>For <code>GetCalculatedDetailsForEntity</code>, I would mock the dependencies, verify they get called appropriately, verify the cache gets set properly, verify the return value is what is expected given the input provided and the mocked values.</p>

<p>For <code>GetCalculatedDetailsById</code> I would mock the repository dependency, test that it called the <code>GetEntity</code> as expected, and that it throws an exception when necessary. Then I want to verify it calls <code>GetCalculatedDetailsForEntity</code> with the expected entity object, but I don't want to verify it does all the logic in <code>GetCalculatedDetailsForEntity</code>, as I'm already testing that elsewhere.</p>

<p>Is it possible to mock <code>GetCalculatedDetailsForEntity</code> for the <code>GetCalculatedDetailsById</code> tests just so that I can verify it's getting called as expected?</p>

<p>My tech stack is .NET Core, XUnit, and Moq.</p>
",https://stackoverflow.com/questions/60199216/unit-testing-one-method-calls-another-method-in-the-same-class,"['unit-testing', '.net-core', 'mocking', 'moq', 'xunit.net']",1625,True,1,2
How to do a Mockito Unit Testing on ViewModel in Kotlin,"<p>I am so clueless of my submission with is the Mockito Unit Testing for the Live Data from the ViewModels in Kotlin language. Here are some codes. I hope that I could test the live data from inside of the viewmodel using verify on change with observers.</p>

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

val nextMatchList = MutableLiveData&lt;ArrayList&lt;Events&gt;&gt;()

fun setNextMatchList(id: Int) {
    val retrofit = Retrofit.Builder()
        .baseUrl(""https://www.thesportsdb.com/"")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val api = retrofit.create(ApiService::class.java)

    api.getNextMatch(id).enqueue(object : Callback&lt;EventsArray&gt; {
        override fun onResponse(call: Call&lt;EventsArray&gt;, response: Response&lt;EventsArray&gt;) {

            val results = response.body()
            val eventsList: ArrayList&lt;Events&gt;?
            eventsList = results!!.events as ArrayList&lt;Events&gt;?

            nextMatchList.postValue(eventsList)
        }

        override fun onFailure(call: Call&lt;EventsArray&gt;, t: Throwable) {
            Log.d(""ysuf"", ""onFailure "" + t.message)
        }

    })
}

fun getLiveData(): MutableLiveData&lt;ArrayList&lt;Events&gt;&gt; {
    return nextMatchList
 }
}
</code></pre>

<p>Thank you very much for the answer !</p>
",https://stackoverflow.com/questions/59773391/how-to-do-a-mockito-unit-testing-on-viewmodel-in-kotlin,"['unit-testing', 'kotlin', 'mvvm', 'mockito', 'viewmodel']",81,False,1,0
NetsJs Controller Unit Testing returning TypeError: Cannot read property of undefined,"<p>Trying to write unit test's on NetsJs Controller But getting <strong>Returning TypeError: Cannot read property 'getGroup' of undefined</strong></p>

<p>groups.controller.spec.ts</p>

<pre><code>describe(""GroupsController"", () =&gt; {
    let groupsController: GroupsController;
    let groupsService: GroupService;

    beforeEach(async () =&gt; {
        const module: TestingModule = await Test.createTestingModule({
            controllers: [GroupsController],
            providers: [
                {
                    provide: getRepositoryToken(Groups),
                    useFactory: GroupModelMockFactory
                },
                {
                    provide: getRepositoryToken(Roles),
                    useFactory: roleModelMockFactory
                },
                RSTLogger,
                RolesService,
                GroupService,
                CommonService,
                DatabaseService,
                GroupsController
            ]
        }).compile();

        groupsService = module.get&lt;GroupService&gt;(GroupService);
        groupsController = module.get&lt;GroupsController&gt;(GroupsController);
    });


    it(""should be defined"", () =&gt; {
        expect(groupsController).toBeDefined();
    });

    describe(""Find Group"", () =&gt; {
        it(""Get group"", async () =&gt; {
            try {
                const expectedResult = {
                    groupName: ""group123"",
                    description: ""Group Description"",
                    roleId: 1
                };
                 expect(
                    await groupsController.getGroup(1, 'no')
                 ).toEqual({ data: expectedResult });
            } catch (e) {
                console.log(e);
            }
        });
    });
});
</code></pre>

<p>unitTestingMocks.ts</p>

<pre><code>export const roleModelMockFactory = () =&gt; ({
    findOne: id =&gt; ({
      id: ""1"",
      name: ""Name"",
      description: ""Description"",
      resource: []
    }),
    create: RoleDto =&gt; ({
      name: ""Role1"",
      description: ""Role Description"",
      resource: []
    }),
    save: RoleDto =&gt; ({
      name: ""Role1"",
      description: ""Role Description"",
      resource: []
    }),
    update: RoleDto =&gt; ({
      exec: async () =&gt; ({
        name: ""Updated Role"",
        description: ""Role Description"",
        resource: []
      })
    }),
    findByIdAndRemove: id =&gt; ({
      exec: async () =&gt; ({
        name: ""Deleted Role"",
        description: ""Description"",
        resource: []
      })
    }),
  });

  export const GroupModelMockFactory = () =&gt; ({

    findByRoleId: id =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    }),
    findOne: dto =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    }),
    create: groupDto =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    }),
    save: groupDto =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    }),
    findOneOrFail: id =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    }),
    update: groupDto =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    }),
    delete: id =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    }),
    getGroup: id =&gt; ({
      groupName: ""group123"",
      description: ""Group Description"",
      roleId: 1
    })
  });
</code></pre>

<p>groups.controller.ts</p>

<pre><code>@ApiTags('groups')
@ApiBearerAuth()
@Controller('groups')
@Injectable({ scope: Scope.REQUEST })
export class GroupsController {
    constructor(private readonly groupsService: GroupService,
        private rstLogger: RSTLogger,
        private commonService: CommonService,
        @Inject(REQUEST) private readonly request: Request) {
        this.rstLogger.setContext('GroupController');
    }

    @Get(':groupId')
    @ApiQuery({ name: 'groupId' })
    @ApiQuery({ name: 'relatinalData' , enum: ['yes', 'no']})
    @UseGuards(JWTTokenAuthGuard, RolesGuard)
    async gerGroup(@Query('groupId') groupId, @Query('relatinalData') relatinalFlag) {
        const group = await this.groupsService.getGroup(groupId, relatinalFlag);
        if (!group) throw new NotFoundException('Group does not exist!');
        return { data: group };
    }

}
</code></pre>

<p>group.service.ts</p>

<pre><code>export class GroupService {
    constructor(
        @InjectRepository(Groups) private readonly groupModel: Repository&lt;Groups&gt;,
        private rstLogger: RSTLogger,
        private readonly databaseService: DatabaseService,
        private readonly rolesService: RolesService) {
        this.rstLogger.setContext('GroupServices');
    }

    async getGroup(ID, relatinalFlag = 'no'): Promise&lt;Groups&gt; {
        if (relatinalFlag &amp;&amp; relatinalData.yes === relatinalFlag) {
            return await this.databaseService.findOneWithRelation(this.groupModel, { id: ID }, { relations: ['role'] });
        } else {
            return await this.databaseService.findOne(this.groupModel, { id: ID });
        }
    }
}
</code></pre>

<p>I am getting below error while trying to getGroup from controller</p>

<blockquote>
<pre><code>  TypeError: Cannot read property 'getGroup' of undefined
</code></pre>
</blockquote>

<p>Can anyone guide me what needs to be correct here.</p>
",https://stackoverflow.com/questions/61751673/netsjs-controller-unit-testing-returning-typeerror-cannot-read-property-of-unde,"['unit-testing', 'jestjs', 'nestjs', 'typeorm', 'nestjs-config']",1638,True,1,1
TypeError: Falsy value found in plugins - Vue Unit Testing with Jest,"<p>I have just started to write <strong>test cases</strong> for my already existing <code>Vue.js</code> project through <strong><em>Jest</em></strong>. </p>

<p>The only test case that worked was Hello World in which it only checks for if the data is being rendered or not. </p>

<p>This is a custom spec which doesn't seem to be working.</p>

<p>I have created a <strong>FancyHeading.spec.js</strong> file</p>

<pre><code>import { shallowMount } from '@vue/test-utils'
import FancyHeading from '@/components/FancyHeading'

describe('FancyHeading', () =&gt; {
  test('if logged in is false, do not show logout button', () =&gt; {
    const wrapper = shallowMount(FancyHeading)
    expect(wrapper.find('button').isVisible()).toBe(false)
  })

  test('if logged in, show logout button', () =&gt; {
    expect(true).toBe(true)
    expect(1 + 1).toBe(2)
  })
})
</code></pre>

<p>For the below Component:</p>

<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;button class=""btn"" v-show=""loggedIn""&gt;Logout&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

    &lt;script&gt;
export default {
  name: 'fancy-heading',
  data () {
    return {
      loggedIn: false
    }
  }
}
&lt;/script&gt;
</code></pre>

<p>The test case fails to run due to the following reason:</p>

<pre><code>FAIL  tests/unit/FancyHeading.spec.js
  ● Test suite failed to run

    TypeError: Falsy value found in plugins

      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:168:15
          at Array.map (&lt;anonymous&gt;)
      at Function.normalisePlugins (node_modules/babel-core/lib/transformation/file/options/option-manager.js:162:20)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:239:36)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:373:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)
      at compileBabel (node_modules/vue-jest/lib/compilers/babel-compiler.js:23:21)
      at processScript (node_modules/vue-jest/lib/process.js:30:10)
</code></pre>

<p>What am I missing here?</p>
",https://stackoverflow.com/questions/59927032/typeerror-falsy-value-found-in-plugins-vue-unit-testing-with-jest,"['javascript', 'unit-testing', 'vue.js', 'testing', 'jestjs']",222,False,1,0
Unit Testing a Method that Interacts with the Excel Interop Library,"<p>I'm trying to become better at writing cleaner code and developing automated tests for methods in applications so as to test the application quicker and write more flexible and extensible code. While I think I understand the basics of Unit Testing, I'm having trouble developing a test for a specific method. I've recently taken an online course on Unit Testing and I learned that in order to write Unit Tests for methods that touch external resources, you should create a class that implements the code that interacts with that external resource and extract an interface for that class so the a Mock instance can be created from the extracted interface. I think using the Excel Interop library qualifies as touching an external resource and the method I'm working on right now is meant to save an Excel file to the user's computer. The code for this method can be seen below.</p>

<pre><code>    public void Save()
    {
        if (DoesFileExistInDirectory())
        {
            semesterGradeInformationWorkbook.Save();
        }
        else
        {
            semesterGradeInformationWorkbook.SaveAs(LocationAsURL);
        }
    }

    private bool DoesFileExistInDirectory()
    {
        return File.Exists(LocationAsURL);
    }
</code></pre>

<p>in this case, if the file exists already the save function can just be called on the workbook. However, if the file doesn't exist the SaveAs operation is called on the workbook to save the file to that location. The code for the whole class can be seen here.</p>

<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace GradeCalculator
{
    public class ExcelWorksheet
    {
        private Excel.Application excelApplication;
        private Excel.Workbook semesterGradeInformationWorkbook;
        private Excel.Worksheet classInformationWorksheet;

        public string Name { get; private set; }
        public string LocationAsURL { get; private set; }
        public int UsedRows
        {
            get { return this.classInformationWorksheet.UsedRange.Rows.Count; }
        }

        public int UsedColumns
        {
            get { return this.classInformationWorksheet.UsedRange.Columns.Count; }
        }

        public ExcelWorksheet(string name)
        {
            InitializeExcel();

            Name = name;

            LocationAsURL = Path.Combine(Properties.Settings.Default.DefaultDirectory, Name + "".xlsx"");

        }

        private void InitializeExcel()
        {
            excelApplication = new Excel.Application();

            semesterGradeInformationWorkbook = excelApplication.Workbooks.Add();

            classInformationWorksheet = semesterGradeInformationWorkbook.ActiveSheet;

            excelApplication.Visible = true;
        }

        public void Save()
        {
            if (DoesFileExistInDirectory())
            {
                semesterGradeInformationWorkbook.Save();
            }
            else
            {
                semesterGradeInformationWorkbook.SaveAs(LocationAsURL);
            }
        }

        private bool DoesFileExistInDirectory()
        {
            return File.Exists(LocationAsURL);
        }
    }
}
</code></pre>

<p>Any tips on how to refactor the code so that it is more extensible and I can write a unit test for it? Any other tips on how to improve the class and methods to better implement a better object oriented design would be much appreciated as well.</p>
",https://stackoverflow.com/questions/60953843/unit-testing-a-method-that-interacts-with-the-excel-interop-library,"['c#', 'unit-testing', 'object-oriented-analysis']",704,False,1,0
Why does RedirectToAction give a NullReferenceException when unit testing controller method?,"<p>I'm writing a unit test for a controller in .Net Framework 4.5.2 but I'm getting a NullReferenceException when this line is hit:</p>

<pre><code>return RedirectToAction&lt;MyController&gt;(action =&gt; action.Edit(itemId), ""Something"");
</code></pre>

<p>However, when I change it (and nothing else) to </p>

<pre><code>return RedirectToAction(""Edit"", ""Something"", new { myId = itemId });
</code></pre>

<p>it works perfectly.</p>

<p>Any ideas why this would be?</p>
",https://stackoverflow.com/questions/61320068/why-does-redirecttoaction-give-a-nullreferenceexception-when-unit-testing-contro,"['c#', '.net', 'asp.net-mvc', 'unit-testing', 'nunit']",110,True,1,1
TypeError: Is not a function error in Unit testing with Jasmine,"<p>I am getting 2 Errors everytime I run my test :</p>
<p>Error 1... &gt;&gt;&gt;TypeError: this.part.list().subscribe is not a function</p>
<p>Error 2... &gt;&gt;&gt;Error:  : could not find an object to spy upon for list()
&gt;&gt;&gt;Usage: spyOn(,)</p>
<p>The part.service.ts contains the following code :</p>
<pre><code>*export class PartService {
    constructor(private http: HttpClient, private configuration: Configuration) {
    }
    list(): Observable&lt;Part[]&gt; {
        console.log(this.configuration);
        const link = this.configuration.partApi + '/list';
        return this.http.get(link).pipe(
            map((result:Part[]) =&gt; {
                return result.map((element:Part)=&gt;{
                    return &lt;Part&gt; Object.assign(new Part(), element);
                });
            })
        );
    }
}*
</code></pre>
<p>In my .spec.ts file I have the following code : -</p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatFormField,MatTableModule, MatFormFieldModule} from '@angular/material';
import { PartViewComponent } from './partview.component';
import {PartService} from 'src/app/service/part.service';
import {DebugElement} from '@angular/core';
import { UuidPipe } from 'src/app/uuid.pipe';
import { of, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Configuration } from 'src/app/app.configuration';
import { BreakpointObserver } from '@angular/cdk/layout';
import { Part } from 'src/app/model';



class MockPartservice {

    list():Part {
     let part1:Part;
      part1=new Part();
      part1.description=&quot;This is a test data&quot;;
      part1.name=&quot;Hello&quot;;
      part1.uuid=&quot;ABCD1234&quot;;
        return part1;
    }

};

describe('PartviewComponent', () =&gt; {
  //let component: PartViewComponent;
  let fixture: ComponentFixture&lt;PartViewComponent&gt;;
  let partservice:PartService;
  let debugElement:DebugElement;
      partservice=null;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({

      imports:[MatFormFieldModule,MatTableModule],
      declarations:[UuidPipe,PartViewComponent],
      providers: [ PartViewComponent, {provide: PartService, useClass: MockPartservice}]

})
    .compileComponents();

  }));


  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(PartViewComponent);
    
    debugElement=fixture.debugElement;
    partservice=fixture.debugElement.injector.get(PartService);
    
  });

 it('#list should return stubbed value from a spy', ()=&gt;{

    
    const partServiceSpy = jasmine.createSpyObj('PartService',['list']);
    spyOn(partservice,'list').and.returnValue(Part);
    
    
 });


 })
</code></pre>
",https://stackoverflow.com/questions/60508164/typeerror-is-not-a-function-error-in-unit-testing-with-jasmine,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",19537,True,1,2
[karma-server]: TypeError: Cannot read property &#39;range&#39; of undefined - Angular Unit Testing in CI environment,"<p>Our CI/CD pipelines stopped working on the &quot;ng test&quot; job and fails with the following error message:</p>
<pre><code>[karma-server]: TypeError: Cannot read property 'range' of undefined
    at handleRangeHeaders (/builds/......../node_modules/webpack-dev-middleware/lib/util.js:131:21)
    at processRequest (/builds/......../node_modules/webpack-dev-middleware/lib/middleware.js:98:19)
    at ready (/builds/......./node_modules/webpack-dev-middleware/lib/util.js:53:12)
    at handleRequest (/builds/........../node_modules/webpack-dev-middleware/lib/util.js:182:5)
    at /builds/............/node_modules/webpack-dev-middleware/lib/middleware.js:64:7
    at new Promise (&lt;anonymous&gt;)
    at middleware (/builds/........../node_modules/webpack-dev-middleware/lib/middleware.js:63:12)
</code></pre>
<p><em>Added periods to sub out some specific repo names</em></p>
<p>We've never had this error before and it worked fine previously. Also oddly enough, it works perfectly when I run it locally. But when the GitLab runners execute it, it fails. Any help would be appreciated. Thanks!</p>
",https://stackoverflow.com/questions/64752689/karma-server-typeerror-cannot-read-property-range-of-undefined-angular-u,"['angular', 'karma-jasmine', 'typeerror', 'gitlab-ci-runner']",28276,True,23,7
How to properly test pcollection length when unit testing Apache Beam,"<p>I am wondering which is the best way to test check the lenght of the output produced by a beam pipeline.</p>
<p>I have some testcode like this:</p>
<pre class=""lang-py prettyprint-override""><code>test_data = [
    {'kind': 'storage#object', 'name': 'file1.doc', 'contentType': 'application/octet-stream', 'bucket': 'bucket123' },
    {'kind': 'storage#object', 'name': 'file2.pdf', 'contentType': 'application/pdf','bucket': 'bucket234'},
    {'kind': 'storage#object', 'name': 'file3.msg', 'contentType': 'message/rfc822', 'bucket': 'bucket345'}
]

with TestPipeline() as p:
   output = (p 
             | beam.Create(test_data)
             | beam.ParDo(DoFn_To_Test()).with_outputs('ok','error')
   )

</code></pre>
<p>I want to test sure that all elements in the test_data list go to 'output.ok'.
I think way to do it is to count them like this:</p>
<pre class=""lang-py prettyprint-override""><code>with TestPipeline() as p:
   output = (p 
             | beam.Create(testdata) 
             | beam.ParDo(DoFn_To_Test()).with_outputs('ok','error')
   )

   okay_count = (output.ok | beam.Map(lambda x: ('dummy_key',x)) 
                 | beam.GroupByKey()  # This gets ('dumm_key',[element1,element2....])
                 | beam.Map(lambda x: len(x[1]) )  # Drop the key and get the lengh of the list
   )

   # And finally check^H^H^H^H^H^H assert the count is correct:
   assert_that(okay_count, equal_to([len(test_data)])

</code></pre>
<p>This works; but I don't feel this is the best way to do it, and I am sure there are more ways to do it.</p>
<h2>Best option (by now)</h2>
<p>This is the best option suggested up to date: using beam.combiners.Count.Globally()</p>
<pre class=""lang-py prettyprint-override""><code>with TestPipeline() as p:
   output = (p 
             | beam.Create(testdata) 
             | beam.ParDo(DoFn_To_Test()).with_outputs('ok','error')
   )

   okay_count = output | beam.combiners.Count.Globally()
   assert_that(okay_count, equal_to([len(test_data)])
</code></pre>
",https://stackoverflow.com/questions/64017676/how-to-properly-test-pcollection-length-when-unit-testing-apache-beam,"['python', 'unit-testing', 'apache-beam']",827,True,0,1
Trying to compare Home Object to String Object in unit testing,"<p>I'm trying to test whether a method works or not in my unit testing. As seen in the code below in my error, I'm trying to compare my Home Object to my String Object and when printing out both of them, they are certainly equal to each other. My question is how do I change my Home Object to be a String Object or my String Object to be a Home Object so the test passes. Also if it helps this is in-memory database testing too. Thanks!</p>

<p><strong>Unit testing code</strong></p>

<pre><code>from unittest import TestCase
from main import ContactApp
from database import CombinedDatabase, Home, Person, Location, Contact

     class TestContactApp(TestCase):
         def test_commit_data(self):
         url = CombinedDatabase.construct_in_memory_url()
         contact_database = CombinedDatabase(url)
         contact_database.ensure_tables_exist()
         session = contact_database.create_session()
         home_address = Home(address='3069 U St.')
         patient1 = Person(patient_name='Mike Piazza')
         ContactApp.commit_data(session, str(patient1), str(home_address), '456324A', 96.4, 'USA',  'Nebraska', 'Omaha', '54229')
         actual = session.query(Home).one()
         actual2 = session.query(Person).one()
         print(home_address, actual.address)
         self.assertEqual(home_address, actual.address)
         self.assertEqual(patient1, actual2.patient_name)
</code></pre>

<p><strong>Error</strong></p>

<pre><code>&lt;database.Home object at 0x7fe4ae20ce48&gt; &lt;database.Home object at 0x7fe4ae20ce48&gt;
#printed out objects

&lt;database.Home object at 0x7fe4ae20ce48&gt; != &lt;database.Home object at 0x7fe4ae20ce48&gt;

&lt;database.Home object at 0x7fe4ae20ce48&gt;
&lt;database.Home object at 0x7fe4ae20ce48&gt;
&lt;Click to see difference&gt;

Traceback (most recent call last):
  File ""/home/cse/Pycharmedu2019.1.1/pycharm-edu-2019.1.1/helpers/pycharm/teamcity/diff_tools.py"", line 32, in _patched_equals
old(self, first, second, msg)
  File ""/usr/lib64/python3.6/unittest/case.py"", line 829, in assertEqual
assertion_func(first, second, msg=msg)
  File ""/usr/lib64/python3.6/unittest/case.py"", line 822, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: &lt;database.Home object at 0x7fe4ae20ce48&gt; != '&lt;database.Home object at 0x7fe4ae20ce48&gt;'
</code></pre>
",https://stackoverflow.com/questions/61451152/trying-to-compare-home-object-to-string-object-in-unit-testing,"['python', 'unit-testing', 'in-memory-database']",141,True,0,1
Android unit testing : calling a method from fragment which uses context,"<p>I am trying to call a method that is defined in a fragment from a unit test class. The method uses 'getString()' method to access a string resource, because of this I'm getting below exception :</p>

<pre><code>java.lang.IllegalStateException: Fragment MyFragment{5474c6c} not attached to a context.
</code></pre>

<p>Unit test snippet</p>

<pre><code>class Test {

lateinit var mfragment: MyActivity.MyFragment

@Before
fun setupFragment(){
    minorWorksElectricalFragment1 = MyActivity.MyFragment()
}

@Test
fun extraInstrumentValidationStatus_withMultifunction_allOtherNA(){
    val status = mfragment!!.getExtraInstrumentValidationStatus(""Testvalue"",
            ""NA"",
            ""NA"",
            ""NA"",
            ""NA"",
            ""NA"")
    Assert.assertThat(status,`is`(true))
}
</code></pre>

<p>}</p>

<p>Method definition</p>

<pre><code>public boolean getExtraInstrumentValidationStatus(String multiFunctionalValue,
                                                      String insulationResisValue,
                                                      String continuityValue,
                                                      String earthElectrodeValue,
                                                      String earthFaultValue,
                                                      String rcdValue) {

        String[] nonMultiFunctionalValues = new String[]{insulationResisValue,
                continuityValue,
                earthElectrodeValue,
                earthFaultValue,
                rcdValue};

        if (!multiFunctionalValue.equalsIgnoreCase(getString(R.string.NA)) &amp;&amp;
                !StringUtils.isEmpty(multiFunctionalValue.trim())) {
            for (String value : nonMultiFunctionalValues) {
                if (value.equalsIgnoreCase(getString(R.string.NA)) ||
                        StringUtils.isEmpty(value.trim())) return false;
            }
        } else {
            for (String value : nonMultiFunctionalValues) {
                if (!value.equalsIgnoreCase(getString(R.string.NA))) return false;
            }
        }
        return true;
    }
</code></pre>

<p>Can anyone please suggest the best option to initialize the fragment with the context in a unit test?</p>
",https://stackoverflow.com/questions/60410027/android-unit-testing-calling-a-method-from-fragment-which-uses-context,"['java', 'android', 'unit-testing', 'kotlin', 'junit4']",851,True,1,2
Is EasyMock&#39;s .times(x) method an issue for unit testing robustness?,"<p>I'm currently working on some unit tests for my application using JUnit and EasyMock for mocking complex objects, and I'm facing a <strong>dilemma</strong>. 
For instance, I'm testing each function with the following test template:</p>

<pre><code>public static int foo(Object a){
// my function that needs to be tested

  int quantity = 0;
  if(a != null &amp;&amp; a.getInt() != null ){
    quantity = a.getInt();
  }
  return quantity;

}

public void testFoo(){
// my unit test for the function foo
  int expectedValue = 0;
  int output = 0;

//Setting up my mocks
  Object a_mock = EasyMock.create(Object.class)
  EasyMock.expect(a_mock.getInt()).andReturn(null).times(1);
  EasyMock.expect(a_mock.getInt()).andReturn(1).times(2);

//Executing
  // Case 1: a is null
  expectedValue = 0;
  output = foo(null);
  assertEquals(expectedValue, output);

  // Case 2: a.getIn() is null
  expectedValue = 0;
  output = foo(a_mock);
  assertEquals(expectedValue, output);

  //Case 3: nominal case
  expectedValue = 1;
  output = foo(a_mock);
  assertEquals(expectedValue, output);

}
</code></pre>

<p>This structure works pretty well, but here is my point: unit testing is a testing process that allows you to validate if each unit (here a function) gives you the wanted output, knowing the input. This means that if I need to modify my function foo, but without modifying what it does, my unit tests still have to pass.
Theoretically, if foo is changed like this:</p>

<pre><code>public static int foo(Object a){

  int quantity = 0;
  if(a != null &amp;&amp; a.getInt() != null &amp;&amp; a.getInt() != 5){ //modification here
    quantity = a.getInt();
  }
  return quantity;

}
</code></pre>

<p>Then testFoo still has to pass.
<strong>But it doesn't</strong>, because the <code>.times(2)</code> must be changed in <code>.times(3)</code>.</p>

<p>So here is my question : is the .times(x) method of EasyMock an issue for the robustness of unit tests ? And if no, then what is the minimal level of robustness a unit test must have ?</p>
",https://stackoverflow.com/questions/60439102/is-easymocks-timesx-method-an-issue-for-unit-testing-robustness,"['unit-testing', 'automated-tests', 'easymock']",43,False,0,1
How do I properly mock Amplify for Unit Testing in Jasmine?,"<p>I'm quite new to Unit testing so bear with me</p>

<p>I'm trying to unit test a service that is used to log the user with Amplify in an Angular application.</p>

<p>Right now in the spec file I'm doing:</p>

<pre><code> beforeEach(async () =&gt; {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
            ],
            providers: [
                MyService, Amplify
            ]
        }
      myService = TestBed.get(MyService)
      amplify = TestBed.get(Amplify)
    })

   it('should login', async () =&gt; {
      const objToBeReturned = { signInUserSession: { idToken: { jwtToken: 'tokenValue' } } }
      spyOn(Amplify.Auth, 'signIn').and.returnValue(objToBeReturned)

      await myService.login('username', 'password')
   })

</code></pre>

<p>While in <em>MyService</em> :</p>

<pre><code>  public async login(username: string, password: string) {
    const authUser = await Amplify.Auth.signIn(username.toLowerCase(), password)
    if (authUser.signInUserSession != null) {
      const idToken = authUser.signInUserSession.idToken.jwtToken
      return this.patientLogin(idToken)
    }
   }

  private async patientLogin(idToken?: string): Promise&lt;boolean&gt; {
    await this.sendRequest&lt;LoginResponse&gt;(url, data).pipe(
      tap(response =&gt; {
        if (!isLoginResponse(response)) {
          throw throwErr({ code: 'Generic' })
        }
        this.token = response.token
      })
    ).toPromise()
    return true
  }

</code></pre>

<p>This gives me the error <strong>Async function did not complete within 5000ms</strong></p>

<p>I'm pretty sure it depends on the way I'm mocking Amplify</p>

<p>How do i properly mock it?</p>
",https://stackoverflow.com/questions/60454057/how-do-i-properly-mock-amplify-for-unit-testing-in-jasmine,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1132,True,0,2
Java Unit Testing - Mock all class methods to return one result,"<p>I would like to mock ALL methods on a class to return one result, instead of mocking each separately, something like:</p>

<pre><code>mock(Foo.class, allMethodsWithAnyArgs).thenReturn('abc');
</code></pre>

<p>I'm very new to Java testing so please forgive the dumb question. This giant project has Mockito, PowerMockito, PowerMock, EasyMock, and probably other stuff so I can use anything recommended.</p>

<p>An extended example would be something like this, where I need to test Foo:</p>

<pre><code>public class Foo {
    doSomething(){
        Bar bar = new bar();

        // some code

        bar.x(a);

        // some code

        bar.x(a, b, c);

        // some more code

        bar.y(...);

        // even more code

        bar.z(...);
    }
}
</code></pre>

<p>I need to stub all the bar calls but don't care about the return, or I want the same return, say 1 or 'ok' from all of them, etc.</p>

<p>UPDATE:
I agree this isn't the best code to test, here is an updated example of what I am trying to test in this case, so I need to stub MyUtil and the bar methods, these are static, so how do you suggest I refactor them? It doesn't make sense to me to put MyUtil as a required argument, and I would prefer to keep Foo as static if possible. A working test file would be super appreciated as I have been struggling with this kind of thing for a few days now.</p>

<pre><code>public class Foo {
    public static Object doSomething(Long id){
        Bar bar = new Bar();
        Object obj;

        if(somecondition) {
            Long vnumber = MyUtil.getVNumber(id);

            obj = bar.getCurrentObj(id, vnumber);            
        } else {
            obj = bar.getPreviousObj(id);
        }

        bar.z(obj);
        ....
    }
}
</code></pre>

<p>Also, one of the points of this class was to make it a black box, I don't want the called to worry about creating instances and passing them in, or even knowing how things work, I just want to pass an ID and get a result for it. Some of the calling functions don't even HAVE access to Bar for example so I can't make it a required parameter.</p>
",https://stackoverflow.com/questions/61017531/java-unit-testing-mock-all-class-methods-to-return-one-result,"['java', 'unit-testing', 'testing']",278,True,-1,1
"doing unit testing of image upload and getting image size, angular","<p>I am trying to write UT for getting image dimension on upload, my function in angular is like this:</p>
<pre><code>onFileSelected(event: FileList) {
    const file: File = event[0];
    const uploadSuccess: boolean = this.validateFile(file);
    if (uploadSuccess) {
      this.selectedFile.emit(file);
    }
  }

getImageDimensions(chosenFile): void {
    const CHOSEN_URL = window.URL || window.webkitURL;
    const Img = new Image();
 
    Img.src = CHOSEN_URL.createObjectURL(chosenFile);
    console.log(Img, CHOSEN_URL.createObjectURL(chosenFile));
    Img.onload = (e: any) =&gt; {
      const height = e.path[0].height;
      const width = e.path[0].width;
      if (width &gt; this.uploaderParams.extras['maxImgWidth'] || height &gt; this.uploaderParams.extras['maxImgHeight']) {
        this.showError(
          'Error',
          `Max file size is width: ${this.uploaderParams.extras['maxImgWidth']} height: ${this.uploaderParams.extras['maxImgHeight']}`,
          3000
        );
        return false;
      } else {
        this.selectedFile.emit(chosenFile);
      }
    };
    
  }
</code></pre>
<p>In unit test i doing like this:</p>
<pre><code>  import { async, ComponentFixture, fakeAsync, flush, flushMicrotasks, TestBed, tick } from '@angular/core/testing';

{more import..}

function MockFile() { };

MockFile.prototype.create = function (name, size, mimeType) {
    name = name || &quot;mock.txt&quot;;
    size = size || 1024;
    mimeType = mimeType || 'plain/txt';

    function range(count) {
        let output = &quot;&quot;;
        for (let i = 0; i &lt; count; i++) {
            output += &quot;a&quot;;
        }
        return output;
    }

    const blob = new Blob([range(size)], { type: mimeType });
    blob['lastModifiedDate'] = new Date();
    blob['name'] = name;

    return blob;
};

fdescribe('FileUploadComponent', () =&gt; {
  let component: FileUploadComponent;
  let fixture: ComponentFixture&lt;FileUploadComponent&gt;;

  window.URL.createObjectURL = jest.fn(() =&gt; {
    return &quot;blob:http://localhost:4200/eadb7d52-51bf-47ce-9eee-b9abaadb86f4&quot;;
  });


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [FileUploadComponent],
      imports: [
        ToastrModule.forRoot(),
        NoopAnimationsModule
      ],
      providers: [
        { provide: ToastService, useValue: toastrService },
        { provide: ToastPackage, useValue: toastPackageMock }
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  }));

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

  afterEach(() =&gt; {
    fixture.destroy();
    // window.URL.createObjectURL.mockReset();
  });

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

  it('should trigger onFileSelected', fakeAsync(() =&gt; {
    const prev_value = {};
    const new_value = uploaderParams;
    const is_first_change = false;

    const size = 1024 * 1024 * .8;
    const mock = new MockFile();
    const file = mock.create(&quot;pic.jpg&quot;, size, &quot;image/jpeg&quot;);
    expect(file).not.toBeNull();
    const fileList = {
      0: file,
      1: file,
      length: 2,
      item: (index: number) =&gt; file
    };
    component.uploaderParams = uploaderParams;
    component.ngOnChanges({ prop1: new SimpleChange(prev_value, new_value, is_first_change) });

    fixture.detectChanges();
    fixture.whenStable();
    component.onFileSelected(fileList);

  }));

});
</code></pre>
<p>The problem is the unit test is not going inside  <code>Img.onload</code> method.  Please help.</p>
",https://stackoverflow.com/questions/63900116/doing-unit-testing-of-image-upload-and-getting-image-size-angular,"['angular', 'jestjs']",480,False,0,0
How to send array in JSON object for ChaiHttp Unit Testing?,"<p>I have an API in node.js, where I can send payloads for multiple DeviceIds, to update their settings. For instance, a sample payload that I would send is:</p>
<pre><code>{&quot;DeviceId&quot;:[&quot;1&quot;,&quot;2&quot;,&quot;3&quot;],&quot;Settings&quot;:[{&quot;Key&quot;:&quot;OnSwitch&quot;,&quot;Value&quot;:&quot;true&quot;}]}
</code></pre>
<p>After sending it, I would say that the DeviceId 1,2,3 all will have updated their settings. This is working correctly and I've tested it locally in Postman. I now want to write a unit test to check the behaviour. My unit test is the following:</p>
<pre><code>context('POST With Multiple IDs', () =&gt; {
  describe('1,2,3 IDs POST', () =&gt; {
    it.only('It should post a full payload with Value True', (done) =&gt;{
        chai.request('http://localhost:3999')
        .post('/api/v2/settings/')
        .set('Authorization', authToken)
        .set('Content-Type', 'application/json')
        .type('Form')
        .send({&quot;DeviceId&quot;: [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;],
            &quot;Settings&quot;: [
              {
                &quot;Key&quot;: &quot;OnSwitch&quot;,
                &quot;Value&quot;: &quot;true&quot;
              }
            ]
          })
        .then(res =&gt; {
        console.log(res.body);
        res.should.have.status(200);
        res.body.should.be.a('object');
        res.body.should.have.property('message');
        res.body.should.have.property('message').eql('All of the Ids Settings sent for processing.');
        res.body.should.have.property('payload');
        done();
        });
    });
});
</code></pre>
<p>In the code, where I make the post, I check that the DeviceIds appear in an array. If they are not in an array a message is returned saying that the DeviceIds must be in an array. Here is the code for that:</p>
<pre><code>if (!Array.isArray(req.body.DeviceId)) {
                logInfo({message: 'DeviceId must be an array.', data: req.body}, 'API');
                return res.status(400).send({
                    message: 'DeviceId must be an array.',
                });
            }
</code></pre>
<p>When I run the unit test above, I get caught in this if statement and I get the message back that the <code>req.body.DeviceId</code> is not an array. If I log the <code>typeof req.body.DeviceId</code>, I get undefined logged. Why would that be? It's working fine when I do a post locally from postman. That is when I send a post locally, the post request goes through without error. But using <code>chaiHttp</code> for the unit test now, I'm having a bit of trouble. Might anyone know why this is happening in the unit test and to make it so that it wouldn't be happening I wouldn't be getting caught in this Array Check. Any advice would be much appreciated!</p>
",https://stackoverflow.com/questions/65239249/how-to-send-array-in-json-object-for-chaihttp-unit-testing,"['node.js', 'api', 'post', 'chai', 'chai-http']",498,False,0,1
Getting TypeError: control.get is not a function in Angular Unit Testing,"<p>I'm writing angular unit test case for password and confirm password validation.</p>

<p>validation.ts file</p>

<pre><code>export function matchPasswords(
passwordFieldName: string,
confirmPasswordFieldName: string
): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null =&gt; {
const password = control.get(passwordFieldName).value;
const confirmPassword = control.get(confirmPasswordFieldName).value;
if (password !== confirmPassword) {
  control
    .get(confirmPasswordFieldName)
    .setErrors({ passwordsDoNotMatch: true });
  return { passwordsDoNotMatch: true };
} else {
  return null;
}
};
}
</code></pre>

<p>validation.spec.ts code</p>

<pre><code>it('should match both password fields and return null if both matches', () =&gt; {
  var passwordField1: string = ""Admins@123"";
  var confirmPasswordField1: string = ""Admins@123"";
  const validate = formValidators.matchPasswords(passwordField1, confirmPasswordField1);
   const validate = formValidators.matchPasswords(passwordField1, confirmPasswordField1);
   expect(
     validate({value:{
         'passwordFieldName':passwordField1,
         'confirmPasswordFieldName':confirmPasswordField1}} as AbstractControl)
       .toEqual(null));
 });
</code></pre>

<p>At the line control.get(passwordFieldName).value I'm getting the error control.get is not a function.</p>
",https://stackoverflow.com/questions/60741495/getting-typeerror-control-get-is-not-a-function-in-angular-unit-testing,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'angular-test']",833,False,0,1
Unit testing in browser for NativeScript fails because of .tns. files,"<p>I have an Angular flavoured Nativescript project, which must be tested with ""vanila"" Jasmine, in a browser (so not in mobile) with <code>ng test</code>.</p>

<p>By default, with ""naked"" tests, it works. But the problem is, if I try to test/import anything, that has a "".tns"" alternative, in some cases it loads that, and the build fails. </p>

<p>My problem is similar to <a href=""https://stackoverflow.com/questions/55458902/unit-testing-nativescript-application-logic-on-a-browser"">this thread</a> but there were no good solution described there. </p>

<p>So for instance:
I have two files:</p>

<pre><code>app.component.tns.ts
app.component.ts
</code></pre>

<p>and I try to import it for testing in <code>app.component.spec.ts</code>:</p>

<pre><code>import {AppComponent} from ""@src/app/app.component"";
</code></pre>

<p>it loads the <code>.tns.</code> file, and the build fails, as it cannot load the mobile-specific libraries. </p>

<pre><code>     ERROR in ./src/app/app.component.tns.ts
Module not found: Error: Can't resolve 'nativescript-ui-sidedrawer' in '/home/..../src/app'
resolve 'nativescript-ui-sidedrawer' in '/home/...../src/app'
  Parsed request is a module
  using description file: /home/...../src/package.json (relative path: ./app)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module

    ...
     @ ./src/app/app.component.tns.ts 25:35-72
     @ ./src/app/app.module.spec.ts
     @ ./src sync \.spec\.ts$
     @ ./src/test.ts
</code></pre>

<p>is there any solution to ""remove"" the .tns. files, just as if I were running a simple ng serve?</p>

<p><strong>update</strong>: My <code>tsconfig.spec.json</code> should exclude these files, but it does not work either ...</p>

<pre><code>  ""exclude"": [
    ""**/*.tns.ts"",
    ""**/*.android.ts"",
    ""**/*.ios.ts""
  ]
}
</code></pre>
",https://stackoverflow.com/questions/59664995/unit-testing-in-browser-for-nativescript-fails-because-of-tns-files,"['unit-testing', 'jasmine', 'nativescript']",80,True,0,1
Angular unit testing with RxJs: Introducing a delay in observable response,"<p>I am trying to unit test a function X. X calls another function,Y, which returns an observable. X calls Y several times. Code in X makes use of forkJoin to ensure that all the observables returned from Y are first completed. So I have to test that part too. I have mocked the call to Y as:</p>
<pre><code>spyOn(anotherService, &quot;Y&quot;).and.returnValues(of(data1), of(data2));
</code></pre>
<p>To make things a bit more realistic I want to introduce a delay in Y's response so that there is noticeable time gap between completion of first observable  and second observable, so that forkJoin code in X is tested properly.</p>
<p>How can I introduce a delay here?</p>
",https://stackoverflow.com/questions/64933941/angular-unit-testing-with-rxjs-introducing-a-delay-in-observable-response,"['javascript', 'angular', 'unit-testing', 'rxjs']",826,False,-1,1
Invalid React hook when unit testing components using withStyles (material-ui),"<p>I'm trying to unit test a component that is using withStyles from material-ui.  I have am defining the style below. </p>

<pre><code>import { makeStyles, Theme, createStyles } from ""@material-ui/core"";

const myStyle = (theme: Theme) =&gt; createStyles({
    root: {
        display: 'flex'
    },
    content: {
        flexGrow: 1,
        backgroundColor: theme.palette.background.default,
        padding: theme.spacing(3)
    },
    drawer: {
        width: 240
    }
});

export function useStyles() {
    return makeStyles(myStyle);
}
</code></pre>

<p>it is being consumed by a component called MainPage as follows</p>

<pre><code>export const MainPage = () =&gt; {
    const classes = useStyles();

    return (
        &lt;ErrorBoundary&gt;
            &lt;DynamicFormWrapper
                baseUrl={'https://.......'}
                classes={classes()}
            /&gt;
        &lt;/ErrorBoundary&gt;
    );
};
</code></pre>

<p>I have a component further down the tree that relies on that style that looks like this</p>

<pre><code>type FormProps = {
    names: string[];
} &amp; WithStyles;

export class SideMenu extends React.Component&lt;FormProps&gt; {
    private names: string[];

    constructor(props) {
        super(props);

        this.names= props.names;
    }

    render() {
        //omitted
    }
}
</code></pre>

<p>When trying to test that component, i need to pass in the style as a prop, and am trying to do that like this</p>

<pre><code>import * as React from 'react';
import { configure, shallow } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import { SideMenu } from '../src/components/SideMenu';
import { useStyles } from '../src/js/styles'

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

describe('SideMenu', () =&gt; {
    let wrapper;

    beforeEach(() =&gt; {
        const style = useStyles();
        wrapper = shallow(&lt;SideMenu names={['test1', 'test2', 'test3']} classes={style()} /&gt;);
    });

    it('Should render', () =&gt; {
        expect(wrapper)
    });
});
</code></pre>

<p>when running the tests, this will throw an Invalid Hook error</p>

<pre><code> Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following yada yada

      16 |     beforeEach(() =&gt; {
      17 |         const style = useStyles();
    &gt; 18 |         wrapper = shallow(&lt;SideMenu names={['test1', 'test2', 'test3']} classes={style()} /&gt;);
         |                                                                                  ^ 
      19 |     });
      20 |
      21 |      it('Should render', () =&gt; {

</code></pre>

<p>I'm able to fix these when I run into them with normal components, but can't seem to get around it in a unit test like this.  Any ideas?</p>
",https://stackoverflow.com/questions/60438441/invalid-react-hook-when-unit-testing-components-using-withstyles-material-ui,"['reactjs', 'jestjs', 'material-ui', 'enzyme']",375,False,0,0
Unit testing a void method that returns a value using pytest,"<p>For example, how could I go about unit testing the following method?</p>

<pre><code>def list_append():
    data = []
    for file in files_list:
        with open(file) as f:
            data.append(json.load(f))
    return data
</code></pre>

<p>From my knowledge, there's no way to individually test the values of a local variable in a method, but please correct me if I'm wrong. Thanks in advance</p>
",https://stackoverflow.com/questions/60554768/unit-testing-a-void-method-that-returns-a-value-using-pytest,"['python', 'json', 'unit-testing', 'testing', 'pytest']",375,False,0,0
how to generate a jwt token for rest controller unit testing?,"<p>I am working on the unit testing for securied restful endpoints. To test it, I need to add the 'Authorization' token in the header. </p>

<p>How can I generate a token for each mockMvc http call? An easier way I can come up with is to call ""api/authentication"" everytime before each test functions. Then the unit testing will depend on ""api/authentication"".</p>

<p>Currently, I am using <code>@WebMvcTest(restController.class)</code>. Then it only loads the restController, and ""api/authentication"" won't be available. </p>

<p>How should I handle unit testing for JWT securied rest APIs? </p>
",https://stackoverflow.com/questions/60085101/how-to-generate-a-jwt-token-for-rest-controller-unit-testing,"['rest', 'spring-boot', 'unit-testing', 'mockito', 'jwt']",2541,True,0,2
How to write unit testing checking null input values using wicket,"<p>I am busy with a wicket application and need to do unit testing, and I have a login page that validates inputs from a <code>List&lt;Customer&gt;</code> but I have no idea where to start, I did try something but it gave me errors and just have no clue what I am doing any help is appreciated </p>

<p>Homepage.java</p>

<pre><code>     form.add(new AjaxButton(""error"") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target)
            {
                for (Customer item: lstCustomer){

                    if (item.name.equals(username.getInput()) &amp;&amp; item.password.equals(password.getInput())){

                        final String usernameValue = username.getModelObject();

                        PageParameters pp = new PageParameters();
                        pp.add(""username"", usernameValue);
                        setResponsePage(SuccessPage.class, pp);
                        valid[0] = true;
                        break;

                    }else {
                        logger.error(""In the else"");
                        valid[0] = false ;
                    }
                }

                if ( valid[0] == false){

                    errorDialog.open(target);

                }


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

<p>TestPage</p>

<pre><code>private WicketTester tester;

    @Before
    public void setUp()
    {
        tester = new WicketTester(new WicketApplication());
    }

    @Test
    public void homepageRendersSuccessfully()
    {
        //start and render the test page
        tester.startPage(HomePage.class);

        //assert rendered page class
        tester.assertRenderedPage(HomePage.class);


    }

    @Test
    public void validLogin(){
        FormTester form = tester.newFormTester(""userForm"");
        form.setValue(""username"", ""emile"");
        form.setValue(""password"", ""123"");
        form.submit();
        tester.assertRenderedPage(SuccessPage.class);

    }
</code></pre>

<p>And then I get this error :</p>

<pre><code>[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket extensions initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket jQuery UI initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket jQuery UI initializer (theme-uilightness)

java.lang.NullPointerException
    at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1593)
    at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1516)
    at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1625)
    at org.apache.wicket.util.tester.BaseWicketTester.newFormTester(BaseWicketTester.java:1311)
    at org.apache.wicket.util.tester.BaseWicketTester.newFormTester(BaseWicketTester.java:1295)
    at com.mycompany.TestHomePage.validLogin(TestHomePage.java:35)
    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.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
",https://stackoverflow.com/questions/60541445/how-to-write-unit-testing-checking-null-input-values-using-wicket,"['wicket', 'wicket-tester']",256,True,0,2
NSubstitute.Exceptions.ReceivedCallsException: Expected to receive a call matching error while unit testing,"<p>I am getting a below error while unit testing the piece of code</p>

<blockquote>
  <p>NSubstitute.Exceptions.ReceivedCallsException: Expected to receive a call matching error while unit testing
  NSubstitute.Exceptions.ReceivedCallsException
    HResult=0x80131500
    Message=Expected to receive a call matching:
      enrollWithHelper("""", """")
  Actually received no matching calls.</p>
  
  <p>Source=NSubstitute
    StackTrace:
     at NSubstitute.Core.ReceivedCallsExceptionThrower.Throw(ICallSpecification callSpecification, IEnumerable<code>1 matchingCalls, IEnumerable</code>1 nonMatchingCalls, Quantity requiredQuantity)
     at NSubstitute.Routing.Handlers.CheckReceivedCallsHandler.Handle(ICall call)
     at NSubstitute.Routing.Route.Handle(ICall call)
     at NSubstitute.Proxies.CastleDynamicProxy.CastleForwardingInterceptor.Intercept(IInvocation invocation)
     at Castle.DynamicProxy.AbstractInvocation.Proceed()
     at Castle.DynamicProxy.AbstractInvocation.Proceed()
     at Castle.Proxies.ObjectProxy_1.enrollWithHelper(String name, String type)
     at MyProject.MyTest.processing_test_pass() in C:\MyProject\MyTest.cs:line 75</p>
</blockquote>

<p><strong>Framework</strong>: .NET Core</p>

<p><strong>Unit Testing</strong>: NSubstitute</p>

<p>Here is my class under test</p>

<pre><code> public class MyService: IMysService
 {
   private readonly IRepository _repository;
   Private readonly IIoTHelper _iotHelper;  
   Private readonly HttpClient _httpClient;
   private Configuration _configuration; 

   public MyService(IRepository repository, IIoTHelper iotHelper, HttpClient httpClient )
   {
        _repository = repository;
        _iotHelper =iotHelper;
        _httpClient = httpClient ;
   }

   public bool CallService(JObject reqObj, out Status status)
   {
        bool provisioningSuccess = false;
        return PreProcessing(reqObj,out Status status); //private method
   }
}
</code></pre>

<p>Here is my private method</p>

<pre><code>    private PreProcessing(JObject JosnObj, out Status status)
    {
        if (_configuration== null)
        {
            _configuration= _repository.GetConfigurations()                 
        }

       using (var client = this._httpClient)
       {
            var request = new {_configuration.Number,_configuration.Type};
            var response = client.PostAsJsonAsync(""api/preprocess"", request).Result;

            if (response.IsSuccessStatusCode)
            {
                  _iotHelper.enrollWithHelper(_configuration.Number,_configuration.Type);
            }
       }
    }
</code></pre>

<p>Here is my Configuration class</p>

<pre><code>   public class Configuration 
   {
     public Configuration (string number, string type)
     {
        Number= number;
        Type= type;
     }      
     public string Number { get;}

     public string Type { get; }

   }
</code></pre>

<p>Here is my unit test code, where I want to make sure it reaches the <code>private</code> method </p>

<pre><code>    protected override void InitializeTest()
    {
        this._repository = Substitute.For&lt;IRepository&gt;();
        this._iotHelper = Substitute.For&lt;IIotHelper&gt;();
    }

    [TestMethod]
    public void processing_test_pass()
    {
          //Arrange
        var messageHandler = new MockHttpMessageHandler(""TEST VALUE"", HttpStatusCode.OK);
        var httpClient = new HttpClient(messageHandler);


          JObject reqobj= new JObject(
          new JProperty(""user"", ""username""),
          new JProperty(""pass"", ""password""));

        Status status = new Status();

        //act
        var t = new MyService(this._repository,this._iotHelper, httpClient );
        bool success = t.CallService(reqobj, out status);
        //assert
        this._iotHelper.Received().enrollWithHelper("""","""");

    }
</code></pre>

<p>How would I test <code>enrollWithHelper</code> is called?</p>

<p>Also I am stuck due to error!</p>
",https://stackoverflow.com/questions/59773418/nsubstitute-exceptions-receivedcallsexception-expected-to-receive-a-call-matchi,"['c#', 'unit-testing', 'nsubstitute']",3204,False,0,0
Why i get `ReferenceError: jQuery is not defined` on unit testing,"<p>I use <code>react-testing-library</code> to test some of my components that they use jquery.<br>
The application runs fine, but when i go to test them, i get that <code>jQuery</code> is not defined.<br>
That is called inside <code>node_modules/jqueryui/jquery-ui.js</code> where is calls <code>factory(jQuery)</code>  </p>

<hr>

<p>**Yarn test gives: **. </p>

<p>ReferenceError: jQuery is not defined</p>

<pre><code>  2 | import { video } from '../player';
  3 |
&gt; 4 | import 'jqueryui';
    | ^
  5 | require('./jquery-ui-touch-punch');
  6 |
  7 | export default function() {
</code></pre>

<hr>

<p>The error happening on a js file, that is used by the component:</p>

<p><a href=""https://i.stack.imgur.com/UDifX.png"" rel=""nofollow noreferrer"">https://i.stack.imgur.com/UDifX.png</a> // i dont know why, it does not display the image.</p>

<p>Where does jquery need to be imported, so not to get that error ?</p>

<hr>

<p>The jquery modules that i use in <code>package.json</code> are:</p>

<pre><code>    ""@types/jquery"": ""^3.3.33"",
    ""@types/jqueryui"": ""^1.12.10"",
    ""jquery"": ""2.2.0"",
    ""jqueryui"": ""^1.11.1"",```

</code></pre>
",https://stackoverflow.com/questions/60991871/why-i-get-referenceerror-jquery-is-not-defined-on-unit-testing,"['javascript', 'jquery', 'reactjs', 'unit-testing', 'jquery-ui']",271,False,0,1
CI with google cloud build and unit testing Jest in NodeJS,"<p>I'm setting up a CI/CD pipeline using Google cloud build, I'm doing 3 simple steps : install, test and deploy, here is my CloudBuild.yaml file :</p>
<pre><code>steps:
  - name: &quot;gcr.io/cloud-builders/npm&quot;
    args: [&quot;install&quot;]

  - name: &quot;gcr.io/cloud-builders/npm&quot;
    args: [&quot;run&quot;, &quot;test&quot;]

  - name: &quot;gcr.io/cloud-builders/gcloud&quot;
    args: [&quot;app&quot;, &quot;deploy&quot;]
</code></pre>
<p>And here is my package.json where I need to specify the hole path of the jest so it can identify it, otherwise I set it : <strong>&quot;test&quot;: &quot;jest&quot;</strong> the step 2 of the build will fail and it will not recognize it.</p>
<pre><code>  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;node index.js&quot;,
    &quot;test&quot;: &quot;sh node_modules/.bin/jest&quot;,
    &quot;test:watch&quot;: &quot;jest --watch&quot;
  },
</code></pre>
<p>In this case I need to always push the node_modules to the github repo to find the module jest, but it's not a good practise.</p>
<p>Any ideas how can I fix this ?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/62835054/ci-with-google-cloud-build-and-unit-testing-jest-in-nodejs,"['node.js', 'unit-testing', 'jestjs', 'continuous-integration', 'google-cloud-build']",1218,False,0,0
"unit testing the output of a form in React.js, Jest, Enzyme","<p>I am building a simple todo application in react, I am also testing using enzyme. I have just extracted the reder list into its own react component which works fine. I am attempting to mock a test for the output of this component but I am struggling.</p>
<p>The current result when I run the tests is</p>
<pre><code>Expected: &quot;New Note&quot;
Received: &lt;p&gt;&lt;button onClick={[Function onClick]}&gt;X&lt;/button&gt;&lt;/p&gt;
</code></pre>
<p>the test currently looks like this...</p>
<pre><code>describe('ListItems', () =&gt; {

  let wrapper;

  beforeEach(() =&gt; {
    const items = ['New Note', 'efefre', 'efqeecec'];
    wrapper = shallow(&lt;ListItems list={[items]} /&gt;);
  });

  it('renders title of application', () =&gt; {
    expect(wrapper.find(&quot;h1&quot;).text()).toContain(&quot;This is the list&quot;)
  });

    it('renders the new note on the page', () =&gt; {
      const items = ['New Note']
      const wrapper = shallow(&lt;ListItems list={items} /&gt;)
      const textOutput = wrapper.find(&quot;#text-output&quot;)
      expect(textOutput.props().children).toEqual(&quot;New Note&quot;)
  })
});

</code></pre>
<p>As you can see Im trying to mock a new array with a &quot;New Note&quot;, an object is being passed through in my tests but just not the actual message. Where am I going wrong?</p>
<p>Just incase it helps this is the file that I am trying to test..</p>
<pre><code>import React from 'react';

function ListItems(props) {
   const list = props.list
    const displayItems = list.map((item, index) =&gt; 
    {
      return &lt;div id='text-output' key={index}&gt;
            &lt;p&gt;
              {item.body}
              &lt;button
              onClick={ () =&gt; props.deleteItem(item.id)}&gt;
                X
              &lt;/button&gt;
            &lt;/p&gt;
        &lt;/div&gt;
    })
  return(
  &lt;div&gt;
    &lt;h1&gt;This is the list&lt;/h1&gt;
    {displayItems}
  &lt;/div&gt;
  )
}
</code></pre>
<p>If anyone could help that would be great.</p>
",https://stackoverflow.com/questions/63888084/unit-testing-the-output-of-a-form-in-react-js-jest-enzyme,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",256,True,0,2
How to test Test Multiple classes objects Doubles in Unit testing,"<p>What i need</p>
<ul>
<li>Need to access other classes function from base class.</li>
</ul>
<p>Problem</p>
<ul>
<li>cannot access $this-&gt;service-&gt;getDataAll another class service function.</li>
<li>Error: Call to a member function getDataAll() on null</li>
</ul>
<p>Class A</p>
<p>function Abc(){
$records = $this-&gt;getData($arg1, $arg2, $arg3);
}</p>
<p>function getData($arg1, $arg2, $arg3)
{
$this-&gt;service-&gt;getDataAll($arg1, $arg2, $arg3);
}</p>
<blockquote>
<p>Unit testing code</p>
</blockquote>
<pre><code>     $services = $this-&gt;getMockBuilder(ClassA::class)
        //-&gt;setMethods(array('Abc'))            
        -&gt;disableOriginalConstructor()
        -&gt;getMock();
    
   
    
    $data = array('name' =&gt;'name');
    $indexVal = '';
    $returnVal = UnitTesting::callMethod(
        $services,
        'Abc',
        array($data)
    );
     private static function callMethod($obj, $name, array $args)
    {
                
                $class = new \ReflectionClass($obj);
                $method = $class-&gt;getMethod($name);
                $method-&gt;setAccessible(true);
                return $method-&gt;invokeArgs($obj, $args);
    }

            
 
</code></pre>
<p>So by accessing function Abc  unit testing  halts in function getData  which was accessing
service func getDataAll.</p>
<p>Accessing service getDataAll works</p>
<pre><code>    $stub = $this-&gt;getMockBuilder(\App\Service::class)
                 -&gt;setMethods(array('getDataAll'))
                 -&gt;disableOriginalConstructor()
                 -&gt;disableOriginalClone()
                 -&gt;disableArgumentCloning()
                 -&gt;disallowMockingUnknownTypes()
                 -&gt;getMock();

    // Configure the stub.
    $stub-&gt;expects($this-&gt;any())
        -&gt;method('getDataAll')
        -&gt;willReturn(true);

    $this-&gt;assertTrue($stub-&gt;getDataAll($arg1, $arg2, $arg3));
</code></pre>
<ul>
<li><p>I need to access service class from Class A.</p>
</li>
<li><p>service function must return some data.</p>
</li>
<li><p>any solution is most welcome.</p>
</li>
</ul>
<p>Reference</p>
<p><a href=""https://phpunit.readthedocs.io/en/9.3/test-doubles.html"" rel=""nofollow noreferrer"">https://phpunit.readthedocs.io/en/9.3/test-doubles.html</a></p>
<p><a href=""https://stackoverflow.com/questions/46192311/phpunit-test-doubles"">PHPUnit test doubles</a></p>
",https://stackoverflow.com/questions/64870925/how-to-test-test-multiple-classes-objects-doubles-in-unit-testing,"['php', 'unit-testing', 'phpunit']",40,False,0,0
Apache Ignite: best practice for starting Ignite server for Unit Testing,"<p>I have a maven/Java 8 project using JUnit4. The code under test creates and manipulates a Cache using the Java thin client. In order to run my unit tests from the command line (mvn test) or from an IDE like Eclipse, I'd like to be able to programatically start an Ignite server. </p>

<p>If I start the server like: </p>

<pre><code>        Runnable runnable = () -&gt; { 
            Ignite ignite = Ignition.getOrStart(cfg);
        };
        Thread t = new Thread(runnable);
        t.start();
</code></pre>

<p>in a @BeforeClass (using Runnable to avoid blocking on getOrStart()), the server dies gracefully after a few Seconds. </p>

<pre><code>[15:34:16] Ignite node started OK (id=33cb95c5)
[15:34:22] Ignite node stopped OK [uptime=00:00:05.378]
</code></pre>

<p>Sadly too soon for my unit tests to run. So is there a best practice for unit testing application code with the ad hoc start of Ignite? Seems to be not an uncommon question but I've yet to find a good answer (""use this framework"", ""extend this class"" etc).</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/61767552/apache-ignite-best-practice-for-starting-ignite-server-for-unit-testing,"['unit-testing', 'junit', 'ignite']",1634,True,0,1
Angular - Unit Testing a promise in the construction of a component,"<p>Assume the following component's constructor and function call:</p>

<pre><code>constructor(private fooService: FooService){
    this.getBarFromService()
}

getBarFromService = () =&gt; fooService.getBar().then(bar =&gt; this.bar = bar)
</code></pre>

<p>And the service's crudely made <code>getBar()</code> function that should wait for an API result:</p>

<pre><code>getBar() {
    let bar = null;
    await new Promise((resolve, reject) =&gt; {
        this.barBuilder.get('/bar').then(
            data =&gt; resolve(bar = data),             // data = baz
            error =&gt; reject(error)
        )
    return bar;
}
</code></pre>

<p>I now want to try and write a unit/integration test to determine that the component can request and display data without calling the API.
And from what I have read, I would need to mock the service so that it would not call <code>barBuilder</code> in reality and instead return a value right away. This resulted in the following test file:</p>

<pre><code>beforeEach(() =&gt;{
    let mockFooService = jasmine.createSpyObj('FooService', ['getBar']);
    mockFooService.getBar.and.returnValue(Promise.resolve(baz))

    TestBed.configureTestingModule({
        providers: [{provide: FooService, useValue: mockFooService}],
    }).compileComponents();
});

describe('get bar should return baz', () =&gt; {
    expect(component).toBeTruthy();
    component.getBar();
    fixture.detectChanges();
    expect(component.bar).toBe(baz)
}
</code></pre>

<p>As the original <code>getBar()</code> function returns the data in a resolved promise object, instead of the data itself, I have to recreate said resolve, otherwise the test would fail saying that it cannot process the <code>then()</code> block of the call. Upon doing so, it gave me the idea that the test works on a functional level, as the test proceeds and I would assume the action in the <code>then()</code> block has been executed.</p>

<p>However, the value <code>baz</code> hasn't been applied to the component after the construction and a manual call, and there are no pointers to see where the mistake lies. Haphazardly throwing <code>console.log()</code> between each expectation shows that <code>component.bar</code> remains null on every point. I haven't found a plausible answer either, as using <code>fakeAsync</code> et cetera. does not apply, as the <code>getBarFromService()</code> function is not asynchronous itself.</p>

<p>Thus, I am at a loss, and the documentation of both Angular (v8) and Jasmine were followed down to the letter (the best I could, at that.)</p>

<p>The question rings; How would I be able to find why and where the variable <code>baz</code> is not applied to <code>component.bar</code> in the mock and/or the unit test itself, and how would I be able to solve it?</p>
",https://stackoverflow.com/questions/61056522/angular-unit-testing-a-promise-in-the-construction-of-a-component,"['angular', 'unit-testing']",63,True,0,1
query selector value is not getting in jasmine unit testing angular,"<p>I have two input fields like below</p>
<pre><code>&lt;input type=&quot;number&quot; [value]=&quot;celsius&quot; class=&quot;large&quot; data-test-id=&quot;celsius-input&quot; (keyup)=&quot;getCelsius($event)&quot;&gt;

&lt;input type=&quot;number&quot; [value]=&quot;fahren&quot; class=&quot;large&quot; (keyup)=&quot;getFahren($event)&quot; data-test-id=&quot;fahrenheit-input&quot;/&gt;
  
</code></pre>
<p>now I'm trying testing this using jasmine unit testing. for this I have written code like below</p>
<pre><code>let component: TemperatureConverter;
  let fixture: ComponentFixture&lt;TemperatureConverter&gt;;
  let compiled;
  let celsiusInput;
  let fahrenheitInput;

  const pushCelsiusValue = async (value) =&gt; {
    celsiusInput.value = value;
    celsiusInput.dispatchEvent(new Event('change'));
    celsiusInput.dispatchEvent(new Event('input'));
    await fixture.whenStable();
    await fixture.detectChanges();
  };

  const pushFahrenheitValue = async (value) =&gt; {
    fahrenheitInput.value = value;
    fahrenheitInput.dispatchEvent(new Event('change'));
    fahrenheitInput.dispatchEvent(new Event('input'));
    await fixture.whenStable();
    await fixture.detectChanges();
  }

  const getByTestId = (testId: string) =&gt; {
    return compiled.querySelector(`[data-test-id=&quot;${testId}&quot;]`);
  };

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TemperatureConverter);
    fixture.autoDetectChanges(true);
    compiled = fixture.debugElement.nativeElement;
    component = fixture.componentInstance;
    celsiusInput = getByTestId('celsius-input');
    fahrenheitInput = getByTestId('fahrenheit-input');
    fixture.detectChanges();
  });

  it('Typing value in Celsius field gets correct Fahrenheit value', async() =&gt; {
    await pushCelsiusValue(500);
    fahrenheitInput = getByTestId('fahrenheit-input');
    expect(Number(fahrenheitInput.value)).toEqual(932);
  });
</code></pre>
<p>but I'm not able to get any value  <code>fahrenheitInput = getByTestId('fahrenheit-input');</code> and I'm not to match anything in     <code>expect(Number(fahrenheitInput.value)).toEqual(932);</code></p>
<p>I'm not able to figure out what is the error.</p>
",https://stackoverflow.com/questions/63856377/query-selector-value-is-not-getting-in-jasmine-unit-testing-angular,"['angular', 'unit-testing', 'jasmine']",1605,False,0,1
How to mock a dependency&#39;s response when unit-testing in Python,"<p>I am trying to write unit test for some of Python classes I have created. I have created a class for wrapping s3 functionalities, and in that class I'm initializing boto3 s3 client.</p>
<pre><code>class S3_Client:

    def __init__(self, bucket_name):
        self.s3 = boto3.client(&quot;s3&quot;, aws_access_key_id=e_config[&quot;aws_access_key&quot;], aws_secret_access_key=e_config[&quot;aws_secret_key&quot;])
        self.bucket_name = bucket_name

    def fetch(self, key):
        response = self.s3.get_object(Bucket=self.bucket_name, Key=key)

        return self.__prepare_file_info(response, key) # return formatted response 
</code></pre>
<p>I would like to test method fetch with mocked response from self.s3.get_object. This is my test class:</p>
<pre><code>import unittest
from .aws_s3_service import S3_Client # class I want to test
import boto3
from botocore.stub import Stubber

class TestS3_Client(unittest.TestCase):

    def setUp(self):
        self.client = boto3.client('s3')
        self.stubber = Stubber(self.client)

    def test_fetch(self):
        get_object_response = {...} # hardcoded response
        self.stubber.add_response('get_object', get_object_response, {&quot;Bucket&quot;: &quot;test_bucket&quot;, &quot;Key&quot;: &quot;path/to/file/test_file.txt&quot;})

        with self.stubber:
            client = S3_Client(&quot;test_bucket&quot;)
            result = client.fetch(&quot;path/to/file/test_file.txt&quot;)

</code></pre>
<p>The stubber is not actually injected into S3_Client, a real call to S3 is made. How do I inject the stubber? Any help is appreciated, thanks.</p>
",https://stackoverflow.com/questions/64576628/how-to-mock-a-dependencys-response-when-unit-testing-in-python,"['python', 'amazon-s3', 'python-unittest']",308,False,0,1
Unit Testing image.onload and image.onerror Inside React.useEffect() With Jest and Enzyme,"<p>I have the following component which displays an image when it is fully loaded:</p>
<pre><code>export default function ImageDisplay(props: OwnPropsInterface): JSX.Element {
    const { src, alt, height, width } = props;

    const [image, setImage] = React.useState&lt;string&gt;('');
    const [showImage, setShowImage] = React.useState&lt;boolean&gt;(false);
    const [imageHeight, setImageHeight] = React.useState&lt;string&gt;('');
    const [imageWidth, setImageWidth] = React.useState&lt;string&gt;('');

    const setImageDimensions = () =&gt; {
        setImageHeight(
            typeof height === 'string' ? height : `${convertPixelsToRem(height)}rem`
        );
        setImageWidth(
            typeof width === 'string' ? width : `${convertPixelsToRem(width)}rem`
        );
    };

    const loadImageAsync = async () =&gt; {
        const image: HTMLImageElement = new Image();

        image.onload = () =&gt; {
            setImage(image.src);
            setShowImage(true);
        };
        image.onerror = (error) =&gt; {
            setShowImage(true);
        };

        image.src = src;
    };

    React.useEffect(() =&gt; {
        setImageDimensions();
        loadImageAsync();
    }, [src]);

    return (
        &lt;&gt;
            {showImage &amp;&amp; (
                &lt;img
                    src={image}
                    alt={alt}
                    style={{ height: imageHeight, width: imageWidth }}
                /&gt;
            )}
        &lt;/&gt;
    );
}
</code></pre>
<p>I need to test <code>image.onload</code> and <code>image.onerror</code> and the subsequent behaviour of the component.</p>
<p>Currently I have the below test written:</p>
<pre><code>    describe('ImageDisplay', () =&gt; {
        let useEffect: jest.SpyInstance;
        let wrapper: ShallowWrapper;

        const mockUseEffect = () =&gt; {
            useEffect.mockImplementationOnce((f) =&gt; f());
        };

        beforeEach(() =&gt; {
            useEffect = jest.spyOn(React, 'useEffect').mockImplementation(() =&gt; {});

            mockUseEffect();
            mockUseEffect();
            wrapper = shallow(&lt;ImageDisplay {...imageDisplayProps} /&gt;);
        });

        describe('on load', () =&gt; {
            it('should set image props', () =&gt; {
                expect(wrapper.find('img').props()).toEqual({
                    alt: 'test_alt',
                    src: '/test/src',
                    style: {
                        height: '100%',
                        width: '100%',
                    },
                });
            });
        });
    });
</code></pre>
<p>The <code>expect</code> call fails with the below error:</p>
<pre><code>Method “props” is meant to be run on 1 node. 0 found instead.

      115 |         describe('on load', () =&gt; {
      116 |             it('should set image props', () =&gt; {
    &gt; 117 |                 expect(wrapper.find('img').props()).toEqual({
          |                                            ^
      118 |                     alt: 'test_alt',
      119 |                     src: '/test/src',
      120 |                     style: {

      at ShallowWrapper.single (node_modules/enzyme/src/ShallowWrapper.js:1652:13)
      at ShallowWrapper.props (node_modules/enzyme/src/ShallowWrapper.js:1175:17)
      at Object.&lt;anonymous&gt; (test/unit-tests/components/ImageDisplay.component.test.tsx:117:44)
</code></pre>
<p>I understand that the <code>expect</code> is failing since it's executing immediately without waiting for the <code>image.onload</code> to finish and hence it's unable to find the <code>img</code> element.</p>
<p>Is there a way to test the image events and the component behaviour? Really appreciate all the help. Thanks.</p>
",https://stackoverflow.com/questions/62570722/unit-testing-image-onload-and-image-onerror-inside-react-useeffect-with-jest-a,"['reactjs', 'unit-testing', 'promise', 'jestjs', 'enzyme']",946,False,0,1
"Invalid JSON was returned from the route , Laravel 8 Unit Testing","<p>I am very new to testing in Laravel, I'm working in laravel 8, the function that I want to test is :</p>
<p>When I run my test I get this error:</p>
<pre><code>1) Tests\Unit\appTest\HttpTest\ControllersTest\OrderControllerTest::testStore
Invalid JSON was returned from the route.
</code></pre>
<p>Thank you for any help!</p>
",https://stackoverflow.com/questions/64697593/invalid-json-was-returned-from-the-route-laravel-8-unit-testing,"['php', 'laravel', 'api', 'unit-testing']",1007,True,0,1
"Unit testing fundaments question about collections and their Add, Remove, ... methods","<p>I read this <a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices"" rel=""nofollow noreferrer"">article</a> about best practices in unit tests, but I still don't get one thing. When I have a <code>List&lt;T&gt;</code> or another collection and then use <code>.Add</code> or <code>.Remove</code> method to add/remove elements, does it count as an <em>arrange</em> or an <em>act</em>?</p>

<p>For example, this definitely counts as <em>arrange</em>:</p>

<pre class=""lang-cs prettyprint-override""><code>List&lt;decimal&gt; values = new List&lt;decimal&gt;
{
    0.01668m,
    0.01666m
};
</code></pre>

<p>Consider the following examples:</p>

<pre class=""lang-cs prettyprint-override""><code>public class IndicatorTests
{
    [Fact]
    public void SimpleMovingAverage_MultipleCloseValues_ReturnsSMA()
    {
        // Arrange
        SimpleMovingAverage sma = new SimpleMovingAverage(5);

        // Act
        sma.Add(0.01692m);
        sma.Add(0.01685m);
        sma.Add(0.01686m);
        sma.AddRange(new List&lt;decimal&gt;
        {
            0.01668m,
            0.01666m
        });
        decimal actual = sma.GetResult();

        // Assert
        Assert.Equal(0.016794m, actual);
    }

    [Fact]
    public void SimpleMovingAverageBuilder_MultipleCloseValues_ReturnsSMA()
    {
        // Arrange
        SimpleMovingAverage sma = new SimpleMovingAverageBuilder(5)
            .Add(0.01692m)
            .Add(0.01685m)
            .Add(0.01686m)
            .Add(0.01668m)
            .Add(0.01666m)
            .Build();

        // Act
        decimal actual = sma.GetResult();

        // Assert
        Assert.Equal(0.016794m, actual);
    }
}
</code></pre>

<p>I believe the second test is okay convention-wise. What about the first one?</p>

<p>Should I do it like that:</p>

<pre class=""lang-cs prettyprint-override""><code>[Fact]
public void SimpleMovingAverage_MultipleCloseValues_ReturnsSMA()
{
    // Arrange
    SimpleMovingAverage sma = new SimpleMovingAverage(5);
    List&lt;decimal&gt; values = new List&lt;decimal&gt;
    {
        0.01668m,
        0.01666m
    };

    // Act
    sma.Add(0.01692m);
    sma.Add(0.01685m);
    sma.Add(0.01686m);
    sma.AddRange(values);
    decimal actual = sma.GetResult();

    // Assert
    Assert.Equal(0.016794m, actual);
}
</code></pre>

<p>Or so:</p>

<pre class=""lang-cs prettyprint-override""><code>[Fact]
public void SimpleMovingAverage_MultipleCloseValues_ReturnsSMA()
{
    // Arrange
    SimpleMovingAverage sma = new SimpleMovingAverage(5);
    List&lt;decimal&gt; values = new List&lt;decimal&gt;
    {
        0.01668m,
        0.01666m
    };

    sma.Add(0.01692m);
    sma.Add(0.01685m);
    sma.Add(0.01686m);
    sma.AddRange(values);

    // Act
    decimal actual = sma.GetResult();

    // Assert
    Assert.Equal(0.016794m, actual);
}
</code></pre>

<p>Which one is better? Please elaborate your answer.</p>
",https://stackoverflow.com/questions/60435032/unit-testing-fundaments-question-about-collections-and-their-add-remove-me,"['c#', 'unit-testing']",31,True,0,2
Mocking raw String in unit testing for Spring Boot service layer,"<p>I am trying to write unit tests for a service layer method finding <code>Player</code>s by name. The method calls a JPA repository method and returns a Page object.
I want the test to verify that the correct method from repository was indeed called.</p>

<p><strong>The test class</strong></p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {PlayerService.class})
public class PlayerServiceTest {

    @Autowired
    PlayerService playerService;

    @MockBean
    PlayerRepository playerRepository;


    @Test
    public void whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(){
        Pageable pageableStub = Mockito.mock(Pageable.class);
        String name = ""xxx"";
        Mockito.when(playerRepository.findByNameContainingIgnoreCase(any(String.class), any(Pageable.class)))
                .thenReturn(any(Page.class));

        //1st attempt:
        //playerService.listPlayersByName(name, pageableStub);
        playerService.listPlayersByName(eq(name), pageableStub);

        verify(playerRepository).findByNameContainingIgnoreCase(any(String.class), any(Pageable.class));
    }
</code></pre>

<p><strong>My problem</strong></p>

<p>The test fails with a message: </p>

<pre><code>org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-&gt; at com.domin0x.player.PlayerServiceTest.whenListPlayersByName_thenShouldCallFindMethodWithPageableArgAndNameArg(PlayerServiceTest.java:60)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), ""raw String"");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq(""String by matcher""));
</code></pre>

<p>Following the advice I changed the <code>name</code> to <code>eq(name)</code> but that results in a different issue:</p>

<pre><code>Argument(s) are different! Wanted:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
    &lt;any java.lang.String&gt;, &lt;any org.springframework.data.domain.Pageable&gt;);

Actual invocation has different arguments:
com.domin0x.player.PlayerRepository#0 bean.findByNameContainingIgnoreCase(
null,     Mock for Pageable, hashCode: 309271464
;
</code></pre>

<p>Any advice what should I change in the test?</p>

<p><strong>The service class</strong></p>

<pre><code>@Service
public class PlayerService {
    public Page&lt;Player&gt; listPlayersByName(String name, Pageable pageable) {
        return repository.findByNameContainingIgnoreCase(name, pageable);
    }
</code></pre>

<p><strong>The repository interface</strong></p>

<pre><code>@Repository
public interface PlayerRepository extends JpaRepository&lt;Player, Integer&gt; {

    Page&lt;Player&gt; findByNameContainingIgnoreCase(String name, Pageable pageable);
}

</code></pre>
",https://stackoverflow.com/questions/60306567/mocking-raw-string-in-unit-testing-for-spring-boot-service-layer,"['java', 'spring', 'junit', 'mockito']",1054,True,0,1
readonly object for unit testing is being disposed when using &#39;using&#39;,"<p>I have an object that is used a bunch of times within the same unit test, and in other unit tests within the same class, that is defined as follows:</p>

<pre><code>private readonly Task&lt;HttpResponseMessage&gt; successfulResponse = Task.FromResult(
            new HttpResponseMessage()
            {
                StatusCode = System.Net.HttpStatusCode.OK,
                Content = new StringContent(@""{""""EntitySets"""":[{""""ResultSets"""":[{""""Results"""":[{""""Type"""":""""Message""""}],""""Total"""":2}],""""EntityType"""":""""Message""""}]}"")
            });
</code></pre>

<p>Then in each of my relevant unit tests, I'm doing something like this:</p>

<pre><code>mockHttpClient.Setup(m =&gt; m.SendAsync(It.Is&lt;HttpRequestMessage&gt;(v =&gt;
            v.RequestUri.Host.Equals(""example.com"")),
            It.IsAny&lt;CancellationToken&gt;())).Returns(successfulResponse);
</code></pre>

<p>... where <code>mockHttpClient</code> is a mocked <code>HttpClient</code>.</p>

<p>But when I'm unit testing, this sort of logic is executed in a lot of places inside the code being tested:</p>

<pre><code>using (HttpResponseMessage response = await this.client.SendAsync(request, cancellationToken))
{
//...
}
</code></pre>

<p>... where <code>this.client</code> is <code>mockHttpClient</code> from above. As you can tell, <code>Moq</code> provides my pre-prepared <code>successfulResponse</code> object here to simulate a http response.</p>

<p>Problem is, when the <em>very first</em> execution of such a <code>using</code> statement is executed, it disposes <code>successfulResponse</code> when it gets out of the <code>using</code> block, and all following <code>using</code> blocks fail with the following exception:</p>

<pre><code>Test method TestProbe_Success threw exception: 
    System.ObjectDisposedException: Cannot access a disposed object.
    Object name: 'System.Net.Http.StringContent'.
</code></pre>

<p>So my question is, how can I prevent the code being tested from disposing this object, which is used multiple times within the same unit test and in other unit tests ? </p>
",https://stackoverflow.com/questions/60608041/readonly-object-for-unit-testing-is-being-disposed-when-using-using,"['c#', 'unit-testing', 'moq', 'dispose', 'using']",933,True,0,1
"unit testing custom hook for getting data, redux useSelector and dispatch","<p>I have been testing a custom hook for getting data from redux state and all is working nice within the app but I am having some issues with testing coverage, namely with unit testing my custom hook. here is my testing code:</p>
<p>useGetHomes custom hook:</p>
<pre><code>import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { getHomes } from '../pages/Homes/actions';

const useGetHomes = () =&gt; {

   const dispatch = useDispatch();
   const homes = useSelector(state =&gt; state.homes);

   useEffect(() =&gt; {

       dispatch(getHomes()); 

   }, [dispatch]);

   //TO DO - extend more

   return {
      homes
   };

};

export default useGetHomes;
</code></pre>
<p>current test file:</p>
<pre><code>import React from 'react';
import { mount } from 'enzyme';

import useGetHomes from '../useGetHomes';

//for testing
const TestHook = ({callback}) =&gt; {

    callback();
    return null;

};

const testHook = callback =&gt; {
  mount(&lt;TestHook callback={callback}/&gt;);
};
//end for testing

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

    let homes;

    beforeEach(() =&gt; {
        testHook(() =&gt; {
            homes = useGetHomes();
        });
    });

    it('should do first test', () =&gt; {

        console.log('first test')
        console.log(homes)  

    });

});
</code></pre>
<p>my current test gives me the following error:</p>
<blockquote>
<p>could not find react-redux context value; please ensure the component is wrapped in a Provider</p>
</blockquote>
<p>I tried wrapping it in a Provider as error is clear but I get the following error:</p>
<blockquote>
<p>Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.</p>
</blockquote>
<p>I guess this is also clear as custom hook returns an object, so is there anything I could do to unit test my custom hook ? On the other hand my integration tests on the components that use the hook are good and working properly.</p>
",https://stackoverflow.com/questions/64748900/unit-testing-custom-hook-for-getting-data-redux-useselector-and-dispatch,"['reactjs', 'unit-testing', 'testing', 'redux', 'react-hooks']",1744,True,0,1
cannot read property setNumber of undefined getting in Unit testing error,"<p>I am trying to unit testing my code where I am getting the below error</p>
<blockquote>
<p>TypeError: Cannot read property 'setNumber' of undefined</p>
</blockquote>
<p>this is my service method for that</p>
<pre><code> setNumber(number) {
   this.number = number;
 }
</code></pre>
<p>This code is there in ts</p>
<pre><code>this.dataService.setNumber(null);
</code></pre>
<p>This is my spec code.</p>
<pre><code>  beforeEach(async(() =&gt; {
   const spyDataService = jasmine.createSpyObj('DataService', ['setNumber'])
  TestBed.configureTestingModule({
  imports: [HttpClientTestingModule, MatDialogModule, BrowserAnimationsModule, RouterTestingModule, MatMenuModule, MatFormFieldModule, MatInputModule, MatPaginatorModule, MatTableModule, MatSortModule, MatIconModule, MatCardModule,],
  declarations: [DashboardComponent],
  providers: [

    { provide: DataService, useValue: spyDataService },
    { provide: MAT_DIALOG_DATA, useValue: {} },
    { provide: MatDialogRef, useValue: {} },
    { provide: LayoutUtilsService, useValue: {} }

  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
  .compileComponents();
</code></pre>
<p>}));</p>
<pre><code>  it('should be create data service', () =&gt; {
   expect(service.setNumber).toHaveBeenCalledWith(null);
 });
</code></pre>
<p>What is wrong here why I am getting this error</p>
<blockquote>
<p>TypeError: Cannot read property 'setNumber' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/63971355/cannot-read-property-setnumber-of-undefined-getting-in-unit-testing-error,"['angular', 'jasmine', 'karma-jasmine']",91,True,0,1
"Flutter Unit Testing: Some tests pass, while other similar tests fail","<p>I have a firestore database class, which I am trying to test. I have multiple objects which can be saved to different collections depending on the path provided. While testing the creation of an Item document and a Review object document - the Item object test passes and the Review object test fails, despite being almost identical tests. Here is some sample code:</p>

<pre><code>///FirestoreService class - setData method
///I have an updated version of this method with a .catchError((e) =&gt; false);
///I have added it below, but I may be wrong on the syntax, I am adding this 
///from memory as I am not at my regular workspace at the moment

Future&lt;bool&gt; setData(

  {bool isAdd = false, String path, Map&lt;String, dynamic&gt; data}) async {

if (isAdd) {

  await Firestore.instance.collection(path).add(data).catchError((e) =&gt; false);

  print('$path: $data');

} else {

  final reference = Firestore.instance.document(path);

  print('$path: $data');

  await reference.setData(data).catchError((e) =&gt; false);

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

<p>}</p>

<pre><code>
///FirestoreDatabase class

/// Paths.items() = ""items""; references collection 'items'
/// Paths.reviews() = ""reviews""; references collection 'reviews'

final _service = FirestoreService.instance;

FirestoreService set(FirestoreService service) =&gt; _service = service;


  @override

  Future&lt;bool&gt; addItem(Item item) async =&gt; await _service.setData(

      isAdd: true, path: Paths.items(), data: item.toMap());


  @override

  Future&lt;bool&gt; addReview(Review review) async =&gt; await _service.setData(

      isAdd: true, path: Paths.reviews(), data: review.toMap());
</code></pre>

<p>And the tests:</p>

<pre><code>
class MockFirestoreService extends Mock implements FirestoreService {}

main() {
  MockFirestoreService service;
  FirestoreDatabase db;
  Item item;
  Review review;

  setup() {
    service = MockFirestoreService();
    db = FirestoreDatabase();
    db.set(service); //Use the mock firestore service

    item = Item(id: 'abc', name: 'abc', description: 'abc test');
    review = Review(id: 'def' rating: 5.0, text: 'review of abc', itemId: 'abc');
  }

  test('This test passes', () async {
    when(service.setData(isAdd: true, path: Paths.items(), data: item.toMap())
.thenAnswer((_) =&gt; Future.value(true);

    final bool result = await db.addItem(item);

    expect(result, true);
  });

test('This test fails', () async {
    when(service.setData(isAdd: true, path: Paths.reviews(), data: review.toMap())
.thenAnswer((_) =&gt; Future.value(true);

    final bool result = await db.addReview(review);

    expect(result, true);
  });
}
</code></pre>

<p>The first test adding a mock item passes, where as the second test adding a review fails, expecting a value of true, but returning null.</p>

<p>I have also tried expecting a completion:</p>

<pre><code>expect(db.setReview(review), completion(expect(true)));
</code></pre>

<p>I am failing to understand why one test passes, yet the other fails. Any help, or improvements to my code is appreciated! Thanks!</p>
",https://stackoverflow.com/questions/60118434/flutter-unit-testing-some-tests-pass-while-other-similar-tests-fail,"['unit-testing', 'flutter', 'google-cloud-firestore']",241,False,0,1
Jest unit testing a function that calls a function returning a Promise,"<p>I have a function that calls a function that returns a Promise. Here is the code for it:</p>
<pre><code>export const func1 = ({
  contentRef,
  onShareFile,
  t,
  trackOnShareFile,
}) =&gt; e =&gt; {
  trackOnShareFile()
  try {
    func2(contentRef).then(url =&gt; {
      onShareFile({
        title: t('shareFileTitle'),
        type: 'application/pdf',
        url,
      })
    }).catch(e =&gt; {
      if (process.env.NODE_ENV === 'development') {
        console.error(e)
      }
    })
    e.preventDefault()
  } catch (e) {
    if (process.env.NODE_ENV === 'development') {
      console.error(e)
    }
  }
}
</code></pre>
<p>And <code>func2</code> that is called in <code>func1</code> is something like this:</p>
<pre><code>const func2 = element =&gt; {
  return import('html2pdf.js').then(html2pdf =&gt; {
    return html2pdf.default().set({ margin: 12 }).from(element).toPdf().output('datauristring').then(pdfAsString =&gt; {
      return pdfAsString.split(',')[1]
    }).then(base64String =&gt; {
      return `data:application/pdf;base64,${base64String}`
    })
  })
}
</code></pre>
<p>Now I am trying to write some unit tests for <code>func1</code> but getting some issues. What I have done so far is this:</p>
<pre><code>describe('#func1', () =&gt; {
  it('calls `trackOnShareFile`', () =&gt; {
      // given
      const props = {
        trackOnShareFile: jest.fn(),
        onShareFile: jest.fn(),
        shareFileTitle: 'foo',
        contentRef: { innerHTML: '&lt;div&gt;hello world&lt;/div&gt;' },
      }
      const eventMock = {
        preventDefault: () =&gt; {},
      }
      // when
      func1(props)(eventMock)
      // then
      expect(props.trackOnShareFile).toBeCalledTimes(1)
    })
    it('calls `onShareFile` prop', () =&gt; {
      // given
      const props = {
        trackOnShareFile: jest.fn(),
        onShareFile: jest.fn(),
        shareFileTitle: 'foo',
        contentRef: { innerHTML: '&lt;div&gt;hello world&lt;/div&gt;' },
      }
      const eventMock = {
        preventDefault: () =&gt; {},
      }
      // when
      func1(props)(eventMock)
      // then
      expect(props.onShareFile).toBeCalledTimes(1)
    })
  })
</code></pre>
<p>Now the first test pass but for the second test I get <code>Expected mock function to have been called one time, but it was called zero times.</code>. I am not sure how to correctly test that. Any kind of help is appreciable.</p>
",https://stackoverflow.com/questions/65077671/jest-unit-testing-a-function-that-calls-a-function-returning-a-promise,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",659,True,5,1
Unit testing a Vue component containing a Vuetify data table with slots,"<p>I'm trying to unit test a simple component with a nested <code>v-data-table</code> component. The page renders properly in the browser, but I can't seem to write a Jest test that works.</p>

<p>The issue seems to be with the template I'm using for the slot -- which I pulled directly off the documentation.</p>

<p>When I comment out the template with the <code>v-slot</code> attribute, the test executes fine.</p>

<p>People.vue:</p>

<pre><code>&lt;template&gt;
  &lt;v-data-table
    :headers=""headers""
    :items=""people""
    disable-pagination
    disable-sort
    disable-filtering
    hide-default-footer
    :loading=""!people""
  &gt;
    &lt;template v-slot:item.id=""{ item }""&gt;
      &lt;v-icon&gt;
        mdi-link-variant
      &lt;/v-icon&gt;
      &lt;router-link
        :to=""{ name: 'assignments', query: { assignee_id: item.id } }""
        &gt;Link&lt;/router-link
      &gt;
    &lt;/template&gt;
  &lt;/v-data-table&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: ""People"",
  data: () =&gt; ({
    headers: [
      {
        text: ""Name"",
        value: ""first_name""
      },
      {
        text: ""Assignment link"",
        value: ""id""
      }
    ]
  }),
  props: {
    people: {
      type: Array,
      required: true
    }
  }
};
&lt;/script&gt;
</code></pre>

<p>People.spec.js:</p>

<pre><code>import { shallowMount } from ""@vue/test-utils"";
import People from ""@/components/People.vue"";

function getMountedComponent(Component, propsData) {
  return shallowMount(Component, { propsData });
}

const propsData = {
  people: [{ id: 1 }]
};
describe(""headers"", () =&gt; {
  it(""contains name and assignment"", () =&gt; {
    expect(getMountedComponent(People, propsData).vm.headers).toEqual([
      {
        text: ""Name"",
        value: ""first_name""
      },
      {
        text: ""Assignment link"",
        value: ""id""
      }
    ]);
  });
});
</code></pre>

<p>Error message:</p>

<pre><code>  console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
    [Vue warn]: Error in render: ""TypeError: Cannot read property 'item' of undefined""

    found in

    ---&gt; &lt;VDataTable&gt;
           &lt;People&gt;
             &lt;Root&gt;

  console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884
    TypeError: Cannot read property 'item' of undefined
</code></pre>
",https://stackoverflow.com/questions/61647512/unit-testing-a-vue-component-containing-a-vuetify-data-table-with-slots,"['javascript', 'vue.js', 'ecmascript-6', 'jestjs', 'vuetify.js']",2329,True,5,1
How can I mock Redis when unit testing an Express node.js app?,"<p>I want to unit test my express app, parts of which set and get data from a Redis database. Investigating why some of my tests intermittently fail — and more frequently as I continue to develop my app — I realised that my tests still call the Redis server rather than the one I thought I had mocked in memory.</p>

<p>How can I successful mock a Redis client (ioredis), so that I can unit test portions of my code in isolation from each other and without calling the Redis server?</p>

<p>Here is what I have so far.</p>

<h2>Code under test</h2>

<p>I have an application model, which merges values from package.json with values from my Redis database, often with fallback values. Values can be added or retrieved.</p>

<pre class=""lang-js prettyprint-override""><code>// models/application.js

import fs from 'fs';
import {client} from '../config/database.js';

export const getAll = async () =&gt; {
  const data = await client.hgetall('application');
  const package_ = JSON.parse(fs.readFileSync('package.json'));

  const application = {
    name: data.name || 'IndieKit',
    version: package_.version,
    description: package_.description,
    repository: package_.repository,
    locale: data.locale || 'en',
    themeColor: data.themeColor || '#0000ee'
  };

  return application;
};

export const get = async key =&gt; {
  const application = await getAll();
  return application[key];
};

export const setAll = async values =&gt; {
  return client.hmset('application', values);
};

export const set = async (key, value) =&gt; {
  return client.hset('application', key, value);
};
</code></pre>

<p><code>client</code> is called from a separate file, where I connect to the Redis server using <a href=""https://github.com/luin/ioredis"" rel=""noreferrer"">ioredis</a>:</p>

<pre class=""lang-js prettyprint-override""><code>// config/database.js

import Redis from 'ioredis';

export const client = new Redis(process.env.REDIS_URL);
export const expires = 3600;

client.on('error', error =&gt; {
  console.error('Redis', error);
});
</code></pre>

<h2>Test</h2>

<p>I’m using <a href=""https://github.com/avajs/ava"" rel=""noreferrer"">Ava</a> as my testing framework, with <a href=""https://github.com/theKashey/rewiremock"" rel=""noreferrer"">rewiremock</a> used to replace ioredis dependency with <a href=""https://github.com/stipsan/ioredis-mock"" rel=""noreferrer"">ioredis-mock</a>… or so I thought!</p>

<pre class=""lang-js prettyprint-override""><code>// tests/models/application.js

import test from 'ava';
import {rewiremock} from '../helpers/rewiremock.js';
import {client} from '../../config/database.js';

test.beforeEach(async t =&gt; {
  t.context.applicationModel = await rewiremock.proxy(() =&gt; {
    return import('../../models/application.js');
  });
});

test.afterEach.always(() =&gt; {
  client.flushall();
});

test.serial('Gets a value', async t =&gt; {
  await t.context.applicationModel.set('name', 'foobar1');
  const result = await t.context.applicationModel.get('name');
  t.is(result, 'foobar1');
});

test.serial('Gets all values', async t =&gt; {
  await t.context.applicationModel.set('name', 'foobar2');
  const result = await t.context.applicationModel.getAll();
  t.is(result.name, 'foobar2');
});

test.serial('Sets a value', async t =&gt; {
  await t.context.applicationModel.set('name', 'foobar3');
  const result = await t.context.applicationModel.get('name');
  t.is(result, 'foobar3');
});

test.serial('Sets all values', async t =&gt; {
  await t.context.applicationModel.setAll({
    name: 'foobar4',
    locale: 'bazqux1'
  });
  const result = await t.context.applicationModel.getAll();
  t.is(result.name, 'foobar4');
  t.is(result.locale, 'bazqux1');
});
</code></pre>

<p>Looking at this again now, there are clearly a couple of issues. First, I was performing a <code>flushAll</code> command on <code>client</code>, which was interacting directly with the Redis server, not the mocked one in memory. Secondly, needing to use different values for each test should have alerted me to something being wrong; I wouldn’t need to this if I was truly flushing the database after each test.</p>

<p>Here’s the rewiremock helper I’m importing into this test:</p>

<pre class=""lang-js prettyprint-override""><code>import rewiremock from 'rewiremock/node.js';

rewiremock('ioredis')
  .by('ioredis-mock');

export {rewiremock};
</code></pre>

<p>So now I find myself at a loss; confused and bewildered by mocking, stubbing and dependency injection (both here and in other tests). What am I doing wrong? What’s the best way to unit test this sort of functionality?</p>
",https://stackoverflow.com/questions/62102788/how-can-i-mock-redis-when-unit-testing-an-express-node-js-app,"['javascript', 'node.js', 'unit-testing', 'redis', 'mocking']",2268,False,5,0
Unit testing that the swagger doc is correct without starting a server,"<p>I'd like to test that the swagger document is correct for my application (mainly, because I've added a strategy to generate custom OperationIds and I want to ensure they are correctly unique)</p>
<p>However, the only solutions I found are all using a &quot;real&quot; server (cf <a href=""https://stackoverflow.com/a/52521454/1545567"">https://stackoverflow.com/a/52521454/1545567</a>), which is not an option for me since I do not have the database, message bus, etc... when I launch the unit tests in CI...</p>
<p>At the moment, I have the following but it always generate 0 paths and 0 models ...</p>
<pre><code>using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using SampleCheckIn;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Linq;
using Xunit;
using SampleCheckIn.Def;
using Service.Utils;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;

namespace D4Interop.Tests
{
    public class TmpTest
    {
        [Fact]
        public void Tmp()
        {
            var controllers = typeof(Startup).Assembly.GetTypes().Where(x =&gt; IsController(x)).ToList();
            controllers.Any().Should().BeTrue();

            var services = new ServiceCollection();
            controllers.ForEach(c =&gt; services.AddScoped(c));
            
            services.AddLogging(logging =&gt; logging.AddConsole());
            services.AddControllers(); //here, I've also tried AddMvcCore and other ASP methods...
            services.AddSwaggerGen(c =&gt;
                {
                    c.SwaggerDoc(&quot;api&quot;, new OpenApiInfo { Title = Constants.SERVICE_NAME, Version = &quot;_&quot;, Description = Constants.SERVICE_DESC });
                    //c.OperationFilter&lt;SwaggerUniqueOperationId&gt;(); //this is my filter that ensures the operationId is unique
                    c.CustomOperationIds(apiDesc =&gt;
                    {
                        return apiDesc.TryGetMethodInfo(out var methodInfo) ? methodInfo.Name : null;
                    });
                });
            services.AddSingleton&lt;IWebHostEnvironment&gt;(new FakeWebHostEnvironment());
            var serviceProvider = services.BuildServiceProvider();


            var swaggerProvider = serviceProvider.GetRequiredService&lt;ISwaggerProvider&gt;();
            var swagger = swaggerProvider.GetSwagger(&quot;api&quot;);

            swagger.Should().NotBeNull();
            swagger.Paths.Any().Should().BeTrue();
        }

        private bool IsController(Type x)
        {
            return typeof(Microsoft.AspNetCore.Mvc.ControllerBase).IsAssignableFrom(x);
        }
    }

    internal class FakeWebHostEnvironment : IWebHostEnvironment
    {
        public FakeWebHostEnvironment()
        {
        }

        public IFileProvider WebRootFileProvider { get =&gt; throw new NotImplementedException(); set =&gt; throw new NotImplementedException(); }
        public string WebRootPath { get =&gt; &quot;/root&quot;; set =&gt; throw new NotImplementedException(); }
        public string EnvironmentName { get =&gt; &quot;dev&quot;; set =&gt; throw new NotImplementedException(); }
        public string ApplicationName { get =&gt; &quot;app&quot;; set =&gt; throw new NotImplementedException(); }
        public string ContentRootPath { get =&gt; &quot;/&quot;; set =&gt; throw new NotImplementedException(); }
        public IFileProvider ContentRootFileProvider { get =&gt; throw new NotImplementedException(); set =&gt; throw new NotImplementedException(); }
    }
}

</code></pre>
",https://stackoverflow.com/questions/62996494/unit-testing-that-the-swagger-doc-is-correct-without-starting-a-server,['swashbuckle.aspnetcore'],2405,True,4,1
How do you mock an Apollo Server RESTDataSource for unit testing with Jest?,"<p>I'm trying to test a data source in my Apollo Server that based on Apollo Server's <code>RESTDataSource</code> (<a href=""https://www.apollographql.com/docs/apollo-server/data/data-sources/#rest-data-source"" rel=""noreferrer"">https://www.apollographql.com/docs/apollo-server/data/data-sources/#rest-data-source</a>).  I'm trying to test it using Jest.  The class has methods that pull in data from an external REST API, as well as from another module that calls a second API (so this <code>RESTDataSource</code> ultimately depends on two external APIs, one of which is called directly here, and one of which is called indirectly). </p>

<p>I'm not an expert on testing, and I'm unclear how to mock the external APIs. GraphQL Tools has some tools that allow you to <a href=""https://www.apollographql.com/docs/graphql-tools/mocking/"" rel=""noreferrer"">mock your server</a>, but I'm not sure that's what I want.  Or should I use <a href=""https://jestjs.io/docs/en/es6-class-mocks"" rel=""noreferrer"">Jest's methods for mocking ES6 classes</a>, forgetting that this is a GraphQL server?  If so, since I'm working with a <code>class</code>, do I just mock the methods using something like <code>MyClass.myMethod</code> as the mocked method?</p>

<p>Does anything change in how I do this if I'm using TypeScript (which I am), other than setting up Jest to work with TypeScript?</p>

<p>Obviously the correct route is to pick one of the options above, but I'm a bit 'not seeing the forest for the trees', that is, due to my inexperience with testing, I don't know which of these is the correct route to follow.</p>

<p>Thanks for any clues.</p>
",https://stackoverflow.com/questions/62022436/how-do-you-mock-an-apollo-server-restdatasource-for-unit-testing-with-jest,"['typescript', 'unit-testing', 'jestjs', 'apollo', 'apollo-server']",4901,True,10,3
Upgrading AutoMapper from v6 to v9 and unit testing with Resolution Context,"<p>I'm hoping that somebody can help me. We are currently upgrading AutoMapper from v6 to v9 - we would go to v10 but the inability to create new <code>ResolutionContext</code> impacts our unit testing. That said with v9 we are still having the following issue with unit testing AutoMapper Converters...</p>
<p>A ConverterClass:</p>

<pre class=""lang-cs prettyprint-override""><code>public class FooBarConverter :
    ITypeConverter&lt;FooSourceObject, BarDestinationObject&gt;
{
    /// &lt;inheritdoc/&gt;
    public virtual BarDestinationObjectConvert(FooSourceObjectsource, BarDestinationObjectdestination, ResolutionContext context)
    {
        EnsureArg.IsNotNull(source, nameof(source));

        switch (source.Type)
        {
            case SomeType.None:
                return context.Mapper.Map&lt;NoneBarDestinationObject&gt;(source);
            case SomeType.FixedAmount:
                return context.Mapper.Map&lt;FixedBarDestinationObject&gt;(source);
            case SomeType.Percentage:
                return context.Mapper.Map&lt;PercentageBarDestinationObject&gt;(source);
            default:
                throw new ArgumentOutOfRangeException(nameof(source));
        }
    }
</code></pre>
<p>Before in AutoMapper 6 we had the following Unit Test (using Xunit):</p>
<pre class=""lang-cs prettyprint-override""><code>public class FooBarConverterTests
{
    private readonly FooBarConverter target;

    private readonly Mock&lt;IRuntimeMapper&gt; mockMapper;
    private readonly ResolutionContext resolutionContext;

    public FooBarConverterTests()
    {
        this.mockMapper = new Mock&lt;IRuntimeMapper&gt;();
        this.resolutionContext = new ResolutionContext(null, this.mockMapper.Object);
        this.target = new FooBarConverter();
    }

    [Fact]
    public void FixedAmountFooModel_ConvertsTo_FixedBarDomainModel()
    {
        // Arrange
        var input = new Foo
        {
            Type = SomeType.FixedAmount
        };

        var expected = new DomainModels.FixedBarDestinationObject();

        this.mockMapper.Setup(x =&gt; x.Map&lt;FixedBarDestinationObject&gt;(It.IsAny&lt;FooSourceObjectsource&gt;()))
            .Returns(expected);

        // Act
        var actual = this.target.Convert(input, It.IsAny&lt;BarDestinationObjectdestination&gt;(), this.resolutionContext);

        // Assert
        actual.ShouldSatisfyAllConditions(
            () =&gt; actual.ShouldNotBeNull(),
            () =&gt; actual.ShouldBeAssignableTo&lt;DomainModels.FixedBarDestinationObject&gt;());

        this.mockMapper.Verify(x =&gt; x.Map&lt;DomainModels.FixedBarDestinationObject&gt;(input));
    }
}
</code></pre>
<p>Essentially, this was working fine, however since upgrading to v9, the mapping setup goes missing as it's passed through the resolution context. Meaning that the resulting call of <code>Mapper.Map&lt;FixedBarDestinationObject&gt;()</code> always returns <code>null</code>.</p>
<p>I understand that the <code>ResolutionContext</code> may have changed slightly, but I don't understand how to resolve this issue and ensure that the mock mapping is passed through to the underlying converter.</p>
<p>Thank you for any help or advice.</p>
",https://stackoverflow.com/questions/63471556/upgrading-automapper-from-v6-to-v9-and-unit-testing-with-resolution-context,['automapper-9'],1833,True,4,1
How to verify log message in Unit testing for a passing test?,"<p>I'm testing an endpoint. I need to figure out how to get the test to pass with my loggerMock. Here is how I currently have the test set up:</p>

<pre><code>public void GetExceptionReportSessionData_Returns200OK()
        {
            //Arrange 
            var response = new RetrieveExceptionReportSessionDatesResponse
            {
                RetrieveExceptionReportSessionDatesResult = string.Empty
            };
            var serviceClient = new Mock&lt;WorkflowService.WorkflowService&gt;();      
            serviceClient
                .Setup(x =&gt; x.RetrieveExceptionReportSessionDatesAsync(It.IsAny&lt;RetrieveExceptionReportSessionDatesRequest&gt;()))
               .ReturnsAsync(response);

            var loggerMock = new Mock&lt;ILogger&gt;();
            loggerMock.Setup(x =&gt; x.LogInfo(null));

            var controller = new ExceptionReportController(loggerMock.Object);

            var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext() };
            ctx.HttpContext.Request.Headers[""token""] = ""fake_token_here""; //Set header
            controller.ControllerContext = ctx;

            //Act
            var result = controller.GetExceptionReportSessionData();

            //Assert
            var viewResult = Assert.IsType&lt;OkObjectResult&gt;(result);
            Assert.Equal(StatusCodes.Status200OK, viewResult.StatusCode);


        }
</code></pre>

<p>Here is how the logger is setup in the endpoint when returning a 200:</p>

<pre><code>if (result != null &amp;&amp; result.ExceptionReportLines != null &amp;&amp; result.ExceptionReportLines.Count &gt; 0)
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                ""Get Exception Report"", ""Exception Report retrieved successfully."");
                logger.LogInfo(logText);
            }
            else
            {
                logText = LogFormatter.Format
                                (WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                ""Get Exception Report"", ""Exception report is empty for the given report filters."");
                logger.LogWarn(logText);
            }

            return Ok(result);
</code></pre>

<p>My test is set up so that the latter message appears. How can I get the test to pass?</p>
",https://stackoverflow.com/questions/62091109/how-to-verify-log-message-in-unit-testing-for-a-passing-test,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'xunit']",10577,True,3,2
Kotlin Flow unit testing exceptions and job with FlowOn with different Dispatchers,"<p>Using the code below to test exceptions with <code>Flow</code> and <code>MockK</code></p>
<p>@Test
fun <code>given network error returned from repos, should throw exception</code>() =
testCoroutineScope.runBlockingTest {</p>
<pre><code>    // GIVEN
    every { postRemoteRepository.getPostFlow() } returns flow&lt;List&lt;PostDTO&gt;&gt; {
        emit(throw Exception(&quot;Network Exception&quot;))
    }

    // WHEN
    var expected: Exception? = null
    useCase.getPostFlow()
        .catch { throwable: Throwable -&gt;
            expected = throwable as Exception
            println(&quot;⏰ Expected: $expected&quot;)
        }
        .launchIn(testCoroutineScope)

    // THEN
    println(&quot;⏰ TEST THEN&quot;)

    Truth.assertThat(expected).isNotNull()
    Truth.assertThat(expected).isInstanceOf(Exception::class.java)
    Truth.assertThat(expected?.message).isEqualTo(&quot;Network Exception&quot;)
}
</code></pre>
<p>And prints</p>
<pre><code>⏰ TEST THEN
⏰ Expected: java.lang.Exception: Network Exception
</code></pre>
<p>And the test fails with</p>
<p><code>expected not to be: null</code></p>
<p>Method i test is</p>
<pre><code>fun getPostFlow(): Flow&lt;List&lt;Post&gt;&gt; {
    return postRemoteRepository.getPostFlow()

            // 🔥 This method is just to show flowOn below changes current thread
        .map {
            // Runs in IO Thread DefaultDispatcher-worker-2
            println(&quot;⏰ PostsUseCase map() FIRST thread: ${Thread.currentThread().name}&quot;)
           it
        }
        .flowOn(Dispatchers.IO)
        .map {
            // Runs in Default Thread DefaultDispatcher-worker-1
            println(&quot;⏰ PostsUseCase map() thread: ${Thread.currentThread().name}&quot;)
            mapper.map(it)
        }
        // This is a upstream operator, does not leak downstream
        .flowOn(Dispatchers.Default)

}
</code></pre>
<p>This is not a completely practical function but just to check how Dispatchers work with Flow and tests.</p>
<p>At the time of writing the question i commented out <code>.flowOn(Dispatchers.IO)</code>, the one on top
the test passed. Also changing Dispatchers.IO to Dispatchers.Default and caused test to pass. I assume it's due to using different threads.</p>
<p>1- Is there a function or way to set all flowOn methods to same thread without modifying the code?</p>
<p>I tried testing success scenario this time with</p>
<pre><code>    @Test
    fun `given data returned from api, should have data`() = testCoroutineScope.runBlockingTest {

        // GIVEN
        coEvery { postRemoteRepository.getPostFlow() } returns flow { emit(postDTOs) }
        every { dtoToPostMapper.map(postDTOs) } returns postList

        val actual = postList

        // WHEN
        val expected = mutableListOf&lt;Post&gt;()
//        useCase.getPostFlow().collect {postList-&gt;
//            println(&quot;⏰ Collect: ${postList.size}&quot;)
//
//            expected.addAll(postList)
//        }

        val job = useCase.getPostFlow()
            .onEach { postList -&gt;
                println(&quot;⏰ Collect: ${postList.size}&quot;)

                expected.addAll(postList)
            }
            .launchIn(testCoroutineScope)

        job.cancel()

        // THEN
        println(&quot;⏰ TEST THEN&quot;)
        Truth.assertThat(expected).containsExactlyElementsIn(actual)
    }
</code></pre>
<p>When i tried to snippet that is commented out, test fails with</p>
<pre><code>java.lang.IllegalStateException: This job has not completed yet
</code></pre>
<p>It seems that test could pass if <code>job</code> has been canceled, the one with <code>launchIn</code> that returns <code>job</code> passes.</p>
<p>2- Why with collect job is not canceled, and it only happens when the first <code>flowOn</code> uses <code>Dispatchers.IO</code>?</p>
",https://stackoverflow.com/questions/63357804/kotlin-flow-unit-testing-exceptions-and-job-with-flowon-with-different-dispatche,"['android', 'unit-testing', 'kotlin-flow']",1920,False,3,0
"AngularFireDatabase, Jest and Unit Testing, how to create a reusable class stub?","<p>I have a test file that is testing a service that returns data from AngularFireDatabase:</p>
<pre class=""lang-js prettyprint-override""><code>import {TestBed, async} from '@angular/core/testing';
import {ProductService} from './product.service';
import {AngularFireDatabase} from '@angular/fire/database';
import {productsMock} from '../../../../mocks/products.mock';
import {Product} from 'shared';
import {Observable} from 'rxjs';
import {getSnapShotChanges} from 'src/app/test/helpers/AngularFireDatabase/getSnapshotChanges';

let list: Product[];
let key: string = '';

const afDatabaseStub = {
  db: jest.fn().mockReturnThis(),
  list: jest.fn(() =&gt; ({
    snapshotChanges: jest.fn().mockReturnValue(getSnapShotChanges(list, true)),
    valueChanges: jest.fn(
      () =&gt; new Observable(sub =&gt; sub.next(Object.values(list)))
    )
  })),
  object: jest.fn(() =&gt; ({
    valueChanges: jest.fn(() =&gt; new Observable(sub =&gt; sub.next({id: key})))
  }))
};

describe('ProductService', () =&gt; {
  let service: ProductService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [{provide: AngularFireDatabase, useValue: afDatabaseStub}]
    });
    service = TestBed.inject(ProductService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

  describe('getAllProducts', () =&gt; {
    it('should be able to return all products', async(() =&gt; {
      list = productsMock;

      service.getAllProducts().subscribe((products: Product[]) =&gt; {
        expect(products?.length).toEqual(10);
      });
    }));
  });

  it('should be able to return a single product using the firebase id', async(() =&gt; {
    key = '-MA_EHxxDCT4DIE4y3tW'
    const response$ = service.getProductById(key);
    response$.subscribe((giveawayProduct: GiveawayProduct) =&gt; {
      expect(giveawayProduct).toBeDefined();
      expect(giveawayProduct.id).toEqual(key);
    });
  }));

});
</code></pre>
<p>The problem I am facing is that I now want to test another service that also uses AngularFireDatabase.</p>
<p>So how can I make this stub more general purpose and put it into a shared helper file that I can use in different specs?</p>
<p>For example, I know you can do <code>useClass</code> instead of <code>useValue</code>:</p>
<p><code>providers: [{provide: AngularFireDatabase, useClass: afDatabaseStub}]</code></p>
<p>If it was a class then <code>list</code> and <code>key</code> could be class properties that I could set before running the tests.</p>
<p>But when I try that, I get errors like this:</p>
<p><code>db.list.object</code> is not a function</p>
<p><code>db.list(...).snapshotchanges</code> is not a function</p>
",https://stackoverflow.com/questions/62759746/angularfiredatabase-jest-and-unit-testing-how-to-create-a-reusable-class-stub,"['angular', 'unit-testing', 'jestjs', 'angularfire']",329,True,3,2
Android Robolectric unit testing not working in a dynamic feature modules why?,"<p>Robolectric unit testing fails with error message <code>java.lang.RuntimeException: android.content.pm.PackageParser$PackageParserException: Failed to parse {projectDir}/build/intermediates/apk_for_local_test/debugUnitTest/apk-for-local-test.ap_</code>, </p>

<pre><code>Caused by: java.lang.NullPointerException
</code></pre>

<p>I started writing unit tests for my application using Robolectric in multi-dynamic feature application, I also just got a fair grip of dynamic feature modules and how best to share dependencies among them. Below is how I solved it.</p>

<p><a href=""https://i.stack.imgur.com/0FZUW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0FZUW.png"" alt=""Dynamic feature architecture""></a></p>

<p>The problem is that a viewMoel factory dependency common to all which is inject by dagger resides in the library module and a viewModel unit test class resides in the DynamicFeat-1 always fails with error <code>java.lang.RuntimeException: android.content.pm.PackageParser$PackageParserException: Failed to parse {projectDir}/build/intermediates/apk_for_local_test/debugUnitTest/apk-for-local-test.ap_</code></p>

<p>And the unit test base class</p>

<pre><code>abstract class BaseTest {

    lateinit var mockServer: MockWebServer

    @Inject
    lateinit var factory: ViewModelProviderFactory


    @Before
    open fun setUp(){

        setUpMockServer()
        configureDI()

    }

    @After
    open fun tearDown(){

        if(isMockServerEnabled()){

            mockServer.shutdown()
        }
    }



    abstract fun isMockServerEnabled(): Boolean

    private fun setUpMockServer(){

        if(isMockServerEnabled()){

            mockServer = MockWebServer()
            mockServer.start()
        }
    }

    open fun mockHttpResponse(fileName: String, responseCode: Int) = mockServer.enqueue(MockResponse()
            .setResponseCode(responseCode)
            .setBody(getJson(fileName)))

    private fun getJson(path : String) : String {
        val uri = this.javaClass.classLoader!!.getResource(path)
        val file = File(uri.path)
        return String(file.readBytes())
    }

    private fun configureDI(){

        //val coreComponent = DaggerCoreComponent.builder().contextModule(ContextModule(RuntimeEnvironment.application)).build()
        DaggerTestHomeComponent.builder().build().inject(this)
    }
}
</code></pre>

<p>The unit test class extends the base and sets up the viewModel by calling <code>super.setUp()</code> but this will always fail. Can anyone help me figure out how to make this work? I will be happy to provide more details if needed, am using robolectric <code>4.3</code></p>
",https://stackoverflow.com/questions/62202196/android-robolectric-unit-testing-not-working-in-a-dynamic-feature-modules-why,"['android', 'robolectric']",615,False,3,0
Error &quot;query was not expected&quot; on INSERT while unit testing using sqlmock,"<p>I'm trying to run an unit test that executes an INSERT into DB, so I mocked exactly the same query string that the gorm log displays with the same arguments but I'm still having problem while trying to execute the test, (with postgres driver) because it seems like the sql-mock does not match the SQL that I defined in the mock and display an error like: </p>

<pre><code>""**call to Query** 'INSERT  INTO ""customer"" (""customer_key"",""first_name"",""middle_name"",""last_surname"") VALUES ($1,$2,$3,$4) RETURNING ""customer"".""customer_key""' with args 
[{Name: Ordinal:1 Value:RLKuxK-wnj8SUn50iFMjsrCtikTLTEmUFP7fOSE2veI=}
 {Name: Ordinal:2 Value:Martín} {Name: Ordinal:3 Value:Constan} 
{Name: Ordinal:4 Value:Smith}] 
**was not expected** ""
</code></pre>

<p><a href=""https://play.golang.org/p/-HZ4YbexWsI"" rel=""nofollow noreferrer"">GO Playgound Running example</a></p>

<p><strong>repository.go</strong></p>

<pre class=""lang-golang prettyprint-override""><code>...
func (r *repository) Register(customer *models.Customer) (*string, error) {
    err := r.db.Create(&amp;customer).Error
    if err != nil {
        return nil, err
    }

    return customer.CustomerKey, nil
}
...
</code></pre>

<p><strong>repository_test.go</strong></p>

<pre class=""lang-golang prettyprint-override""><code>func TestRegister(t *testing.T) {
    qStr := `INSERT  INTO ""customer"" (""customer_key"",""first_name"",""middle_name"",""last_surname"") 
    VALUES ($1,$2,$3,$4) RETURNING ""customer"".""customer_key""`

    t.Run(""Must return the newly created customer key, if given customer input is valid"", func(t *testing.T) {
        r := mocks.CustomerModel

        mock.MatchExpectationsInOrder(false)
        mock.ExpectBegin()
        mock.ExpectQuery(regexp.QuoteMeta(qStr)).
            WithArgs(r.CustomerKey, r.FirstName, r.MiddleName, r.LastSurname).
            WillReturnRows(sqlmock.NewRows([]string{""customer_key""}).AddRow(r.CustomerKey))
        mock.ExpectCommit()
        customerKey, err := repo.Register(r)

        assert.Nil(t, err)
        assert.NotNil(t, customerKey)
    })
}
</code></pre>

<p>and I get the following error:</p>

<pre><code>Running tool: /usr/local/go/bin/go test -timeout 30s /internal/customer -run ^(TestRegister)$
call to Query 'INSERT  INTO ""customer"" (""customer_key"",""first_name"",""middle_name"",""last_surname"") VALUES ($1,$2,$3,$4) RETURNING ""customer"".""customer_key""' with args [{Name: Ordinal:1 Value:RLKuxK-wnj8SUn50iFMjsrCtikTLTEmUFP7fOSE2veI=}
 {Name: Ordinal:2 Value:Martín} {Name: Ordinal:3 Value:Constan} 
{Name: Ordinal:4 Value:Smith}] 
was not expected &lt;----------------------ERROR-------------------------

INSERT  INTO ""customer"" (""customer_key"",""first_name"",""middle_name"",""last_surname"") VALUES ('RLKuxK-wnj8SUn50iFMjsrCtikTLTEmUFP7fOSE2veI=','Martín','','Constan','Smith'') RETURNING ""customer"".""customer_key""  
[0 rows affected or returned ]

[35m(data-repository/internal/customer/repository.go:57)[0m 
[33m[2020-01-22 19:39:18][0m [31;1m call to Query 'INSERT INTO ""customer"" (""customer_key"",""first_name"",""middle_name"",""last_surname"") VALUES ($1,$2,$3,$4) RETURNING ""customer"".""customer_key""' with args [{Name: Ordinal:1 Value:RLKuxK-wnj8SUn50iFMjsrCtikTLTEmUFP7fOSE2veI=} {Name: Ordinal:2 Value:Martín} {Name: Ordinal:3 Value:Constan} {Name: Ordinal:4 Value:Smith}] 
was not expected &lt;----------------------ERROR AGAIN-------------------------

--- FAIL: TestRegister (0.00s)
    --- FAIL: TestRegister/Must_return_the_newly_created_customer_key,_if_given_customer_input_is_valid (0.00s)
        data-repository/internal/customer/repository_test.go:89: 
                Error Trace:    repository_test.go:89
                Error:          Expected nil, but got: &amp;status.statusError{Code:13, Message:""An error occurred."", Details:[]*any.Any{(*any.Any)(0xc000215f90)}, XXX_NoUnkeyedLiteral:struct {}{}, XXX_unrecognized:[]uint8(nil), XXX_sizecache:0}
                Test:           TestRegister/Must_return_the_newly_created_customer_key,_if_given_customer_input_is_valid
FAIL
FAIL    /internal/customer  0.008s
FAIL
Error: Tests failed.
</code></pre>

<p>I'm using the following versions:</p>

<p><code>github.com/DATA-DOG/go-sqlmock v1.4.0</code> and
<code>github.com/jinzhu/gorm v1.9.11</code></p>

<p>I would appreciate any help... </p>
",https://stackoverflow.com/questions/59878237/error-query-was-not-expected-on-insert-while-unit-testing-using-sqlmock,"['go', 'go-gorm', 'go-sqlmock']",1406,False,3,0
Mock an if/else statement with jasmine - unit testing with Angular/Typescript,"<p>I have added a minor amendment within an existing function. Our quality checks have identified this as new code therefore I need to cover the new 4 lines with a unit test - within mind there was never a unit test there to begin with and the function I added to is pretty large!</p>
<p>I've tried a number of ways to try and mock services, variables, spying etc... but always get errors. I'm new to jasmine so struggling. All I need to do is get any sort of check to cover the lines truthy/falsy.</p>
<p><strong>component.ts file</strong></p>
<pre><code>hasDescription() {
        return this.isBrilliant() || this.isCool();
    }

isBrilliant() {
        return this.service.Type.description == 'Brilliant';
    }

isCool() {
        return this.service.Type.description == 'Cool';
    }



onExportToExcel(): void {
        var r = [];
        // added the below if/else - any check on this will be suffice.
        if (this.hasDescription()) {
            if (!this.isBrilliant()) {
                r.push('This is Cool');
            } else {
                r.push('This is Brilliant');
            }
            if (!this.isBrilliant()) {
            r.push('More Cool content');
            }
        }
}
</code></pre>
<p>I tried to set <code>isBrilliant(</code>) with a mock value of <code>true</code>, and expect that the value to be truthy <code>expect(component.isBrilliant()).toBeTruthy();</code></p>
<p>I tried to set this in the spec file by:</p>
<pre><code>const isBrilliant = true;
component.isBrilliant = isBrilliant;
</code></pre>
<p>however the error I got here was that <code>Type 'true' is not assignable to type '() =&gt; boolean'.</code></p>
<p>If any experienced jasmine dev can show me a quick way to get some coverage for this simple statement that would be appreciated. Thanks</p>
<hr />
<p><strong>UPDATE</strong>:</p>
<p>I can get <code>isBrilliant()</code> to be true or false. I now need to check the array r to see if the correct string has been <code>.push</code> into it? any ideas?</p>
",https://stackoverflow.com/questions/64662229/mock-an-if-else-statement-with-jasmine-unit-testing-with-angular-typescript,"['javascript', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",11574,True,2,1
Unit testing for appconfig service which gets json file in angular 9,"<p>I have recently started learning unit testing in angular and currently trying to write tests for appconfig service.</p>

<p>The Code which I want to unit test for appservice config is as below, which gets the environments from the json file:</p>

<pre><code>public loadEnvironment(): Observable&lt;AppSettings&gt; {
    if (!this.configuration$) {
      this.configuration$ = this.http.get&lt;AppSettings&gt;(`/environment`).pipe(
        shareReplay(1)
      );
    }
    return this.configuration$;
  }
</code></pre>

<p>For this, I tried to write below test but somehow I am not able to figure out how I can mock the json file get here?</p>

<pre><code>describe('AppConfigService', () =&gt; {
  let appConfigService: AppConfigService;
  let httpMock: HttpTestingController;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      providers: [
        AppConfigService
      ],
    });

    appConfigService = TestBed.get(AppConfigService);
    httpMock = TestBed.get(HttpTestingController);
  });

  it(`should fetch enviornment as an Observable`, async(inject([HttpTestingController, AppConfigService],
    (httpClient: HttpTestingController, appConfigService: AppConfigService) =&gt; {

      appConfigService.loadEnvironment().subscribe();

      let req = httpMock.expectOne('/environment');
      expect(req.request.method).toBe(""GET"");

      httpMock.verify();
    })));
});
</code></pre>

<p>As I said I am very new so please consider that.</p>
",https://stackoverflow.com/questions/61439105/unit-testing-for-appconfig-service-which-gets-json-file-in-angular-9,"['angular', 'unit-testing', 'angular9']",596,False,2,0
Angular using Apollo: Unit testing: Error: Client has not been defined yet,"<p>I'm using apollo client for graphql. I set up the client in GraphQLModule which I'm importing in AppModule. I'm making a query in a service which is also imported right in the AppModule.
But i get this error: Error: Client has not been defined yet
Tried already: <a href=""https://stackoverflow.com/questions/49257668/angular-apollo-client-has-not-been-defined-yet"">Angular - Apollo: Client has not been defined yet</a>.</p>

<p><strong>grapgql.module.ts</strong></p>

<pre><code>import { NgModule } from '@angular/core';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { environment } from 'src/environments/environment';
import { GraphqlService } from './graphql.service';

const uri = 'https://api.example.com/graphql';
export function createApollo(httpLink: HttpLink) {
    return {
        link: httpLink.create({ uri }),
        cache: new InMemoryCache(),
    };
}

@NgModule({
    exports: [
        ApolloModule,
        HttpLinkModule
    ],
    providers: [
        {
            provide: APOLLO_OPTIONS,
            useFactory: createApollo,
            deps: [HttpLink],
        },
        GraphqlService,
    ],
})
export class GraphQLModule { }
</code></pre>

<p><strong>graphsl.service.spec.ts</strong> - this test passes.</p>

<pre><code>import { TestBed } from '@angular/core/testing';

import { GraphqlService } from './graphql.service';
import { Apollo } from 'apollo-angular';

describe('GraphqlService', () =&gt; {
    let service: GraphqlService;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                GraphqlService,
                Apollo
            ]
        });
        service = TestBed.inject(GraphqlService);
    });

    it('should be created', () =&gt; {
        expect(service).toBeTruthy();
    });
});
</code></pre>

<p><strong>app.module.ts</strong> - this test fails and throws error: Client has not been defined yet</p>

<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { GraphQLModule } from './graphql/graphql.module';
import { HttpClientModule } from '@angular/common/http';
import { CmTableModule } from './shared/cm-table/cm-table.module';
import { CmComponentsModule } from './shared/cm-components/cm-components.module';
import { CmDirectivesModule } from './shared/cm-directives/cm-directives.module';
import { CmPipesModule } from './shared/cm-pipes/cm-pipes.module';
import { CmDragDropModule } from './shared/cm-drag-drop/cm-drag-drop.module';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { GraphqlService } from './graphql/graphql.service';


const uri = 'https://api.example.com/graphql';
export function createApollo(httpLink: HttpLink) {
    return {
        link: httpLink.create({ uri }),
        cache: new InMemoryCache(),
    };
}
@NgModule({
    declarations: [
        AppComponent,
    ],
    exports: [
        ApolloModule,
        HttpLinkModule
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        NoopAnimationsModule,
        GraphQLModule,
        HttpClientModule,
        CmTableModule,
        CmComponentsModule,
        CmPipesModule,
        CmDirectivesModule,
        CmDragDropModule,
        ApolloModule,
        HttpLinkModule
    ],
    providers: [{
        provide: APOLLO_OPTIONS,
        useFactory: createApollo,
        deps: [HttpLink],
    },
        GraphqlService],
    bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>

<p><strong>app.component.spec.test</strong></p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { GraphqlService } from './graphql/graphql.service';
import { Apollo, ApolloModule } from 'apollo-angular';

describe('AppComponent', () =&gt; {
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule,
                ApolloModule
            ],
            declarations: [
                AppComponent
            ],
            providers: [
                GraphqlService,
                Apollo
            ]
        }).compileComponents();
    }));

    it('should create the app', () =&gt; {
        const fixture = TestBed.createComponent(AppComponent);
        const app = fixture.componentInstance;
        expect(app).toBeTruthy();
    });

});
</code></pre>
",https://stackoverflow.com/questions/61797767/angular-using-apollo-unit-testing-error-client-has-not-been-defined-yet,"['angular', 'unit-testing', 'graphql', 'apollo']",2483,True,2,1
Vue3 Unit Testing: [Vue warn]: Component is missing template or render function,"<p>I have a Vue3 project created with the VueCLI. Executing unit tests fails for mounted components. It says <code>[Vue warn]: Component is missing template or render function.</code> The test file below complains about the made assertion: <code>AssertionError: expected '' to include 'Test'</code> on the Test.vue component. The first specified test works. What could be the issue? Which dependency versions and config files are needed in order to find the issue? I wanted to avoid to paste all of them to keep a better overview. I am using <strong>mocha</strong> and <strong>chai</strong>. Thanks!</p>
<p><a href=""https://i.stack.imgur.com/sQa2B.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sQa2B.png"" alt=""example.spec.ts"" /></a></p>
<p><a href=""https://i.stack.imgur.com/kG5X3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/kG5X3.png"" alt=""Test.vue"" /></a></p>
",https://stackoverflow.com/questions/64577822/vue3-unit-testing-vue-warn-component-is-missing-template-or-render-function,"['vue.js', 'mocha.js']",1484,False,2,0
How to pass any UUID in a function in unit testing in mockito?,"<p>I have a function func() which accepts UUID as an argument. I am making a unit test for which I need to return a specific value for any UUID value passed to func(). How can I make it work for any UUID type value (just like <code>anyString()</code> for any string, <code>anyInt()</code> for any integer, etc)?</p>

<p>I have already tried: </p>

<pre><code>when(obj.func(any(UUID.class)).thenReturn(null);
</code></pre>

<p>It gives the following error: </p>

<p><code>The method any(Class&lt;UUID&gt;) is ambiguous for the type &lt;Test_Class_Name&gt;</code></p>

<p>where Test_Class_Name is the name of the class where I am writing the unit tests.</p>

<p>func() is an overloaded function : func(String) and func(UUID)</p>
",https://stackoverflow.com/questions/60118866/how-to-pass-any-uuid-in-a-function-in-unit-testing-in-mockito,"['java', 'generics', 'junit', 'mockito', 'testng']",4478,True,7,1
Element still defined even though *ngIf is false Jasmine unit testing Angular,"<p>I'm completely new to unit testing, so I may just be doing everything wrong here. I'm using *ngIf to display a data grid from DevExpress once my GET request completes, and I'm trying to verify with the Jasmine test that it only is displayed once my *ngIf condition is set to true.</p>
<p>A truncated version of my grid:</p>
<pre><code>
    &lt;dx-data-grid #grid *ngIf=&quot;!loading&quot;&gt;
        ...
    &lt;/dx-data-grid&gt;

</code></pre>
<p>and my .spec file:</p>
<pre><code>import { ApplicationsComponent } from &quot;./applications.component&quot;;
import { ComponentFixture, async, TestBed } from &quot;@angular/core/testing&quot;;
import { RouterTestingModule } from &quot;@angular/router/testing&quot;;
import { HttpClientTestingModule } from &quot;@angular/common/http/testing&quot;;
import { DxDataGridModule } from &quot;devextreme-angular&quot;;
import { DebugElement } from &quot;@angular/core&quot;;
import { By } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

describe(&quot;ApplicationPocComponent&quot;, () =&gt; {
  let component: ApplicationsComponent;
  let fixture: ComponentFixture&lt;ApplicationsComponent&gt;;
  let el: DebugElement;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ApplicationsComponent],
      imports: [RouterTestingModule, HttpClientTestingModule, DxDataGridModule, CommonModule ],
    })
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(ApplicationsComponent);
        component = fixture.componentInstance;
        el = fixture.debugElement; 
      });
  }));

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

  it(&quot;should display the data grid&quot;, () =&gt; { 
    component.loading = true; 
    fixture.detectChanges(); 
    const dataGrid = el.queryAll(By.css(&quot;#grid&quot;)); 
    expect(dataGrid).toBeTruthy(&quot;Datagrid not created&quot;); 
    expect(dataGrid).toBeNull(&quot;Datagrid is created&quot;); 
  })
});
</code></pre>
<p>My first assertion, <code>expect(dataGrid).toBeTruthy()</code> succeeds, whereas the assertion <code>.toBeNull()</code> fails. This is the opposite of what I expected, what am I missing here?</p>
",https://stackoverflow.com/questions/63041732/element-still-defined-even-though-ngif-is-false-jasmine-unit-testing-angular,"['angular', 'jasmine', 'angular-ng-if']",1781,True,1,2
How to allow scss in jest for unit testing for typescript nextjs?,"<p>I have an error on the scss importation. I have tried using mockup and <code>identity-obj-proxy</code> but none of them work. I am wondering if my regex expression might be wrong or something.</p>

<p>The error is located at</p>

<pre><code> import utilityStyles from ""~/scss/Utils.scss""; and `{@import ""~Scss/helpers/variables"";`
</code></pre>

<p>In package.json I have</p>

<pre><code>""preset"": ""ts-jest"",
""moduleNameMapper"": {
  ""^~(.*)$"": ""&lt;rootDir&gt;/src/$1"",
  ""^src/(.*)$"": ""&lt;rootDir&gt;/src/$1"",
  ""^.*.(css|scss)$"": ""identity-obj-proxy""
},
</code></pre>

<p>In the index.d.ts I have</p>

<pre><code>declare module '*.scss' {
  const content: { [key: string]: string };
  export default content;
}

declare module 'raw-loader!*' {
  const content: string
  export default content
}
</code></pre>

<p><strong>Update</strong></p>

<p>I thought the problem was due to my regex expression, so I tried
<code>""^(.*)(css|less|scss)$"": ""identity-obj-proxy""</code> but still doesn't work</p>
",https://stackoverflow.com/questions/60474127/how-to-allow-scss-in-jest-for-unit-testing-for-typescript-nextjs,"['reactjs', 'typescript', 'sass', 'jestjs', 'next.js']",1849,True,1,1
Angular 10 Unit Testing PrimeNG p-dropdown with 2-Way Data Binding,"<p>In my Angular 10 app with Jasmine test framework, I need help testing that a PrimeNG <code>p-dropdown</code> with 2-way databinding updates my model automatically when an item is selected. In the example below, how would I verify that when an an item is selected, that <code>selectedCity</code> (the model in my component) gets updated?</p>
<p>Example Dropdown used in my component:</p>
<pre><code>&lt;p-dropdown [options]=&quot;cities&quot; [(ngModel)]=&quot;selectedCity&quot;&gt;&lt;/p-dropdown&gt;
</code></pre>
<p>Dropdown Options:</p>
<pre><code>this.cities = [
    { label: 'Select City', value: null },
    { label: 'New York', value: { id: 1, name: 'New York', code: 'NY' } },
    { label: 'Rome', value: { id: 2, name: 'Rome', code: 'RM' } },
    { label: 'London', value: { id: 3, name: 'London', code: 'LDN' } },
    { label: 'Istanbul', value: { id: 4, name: 'Istanbul', code: 'IST' } },
    { label: 'Paris', value: { id: 5, name: 'Paris', code: 'PRS' } }
];
</code></pre>
<p>I tried the following in my component test to no avail, the model is still undefined:</p>
<pre><code>it('should populate the model when an item is selected', async(() =&gt; {
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
        const dropdown: Dropdown = fixture.debugElement.query(By.css('p-dropdown')).componentInstance;
        dropdown.selectItem(new Event('change'), dropdown.options[1].value);
        fixture.detectChanges();
        expect(component.selectedCity).toEqual(dropdown.options[1].value);
    });
}));
</code></pre>
",https://stackoverflow.com/questions/64763356/angular-10-unit-testing-primeng-p-dropdown-with-2-way-data-binding,"['angular', 'typescript', 'testing', 'jasmine', 'primeng']",1582,False,1,1
"AssertionError on unit testing a celery task with autoretry, backoff and jitter","<p>Using celery 4.3.0. I tried to write a unit test for the following task.</p>

<pre><code>    from django.core.exceptions import ObjectDoesNotExist

    @shared_task(autoretry_for=(ObjectDoesNotExist,), max_retries=5, retry_backoff=10)
    def process_something(data):
        product = Product()
        product.process(data)
</code></pre>

<p>Unit test:</p>

<pre><code>@mock.patch('proj.tasks.Product')
@mock.patch('proj.tasks.process_something.retry') 
def test_process_something_retry_failed_task(self, process_something_retry, mock_product):

    mock_object = mock.MagicMock()
    mock_product.return_value = mock_object
    mock_object.process.side_effect = error = ObjectDoesNotExist()

    with pytest.raises(ObjectDoesNotExist):
        process_something(self.data)

    process_something_retry.assert_called_with(exc=error)
</code></pre>

<p>This is the error I get after running the test:</p>

<pre><code>    @wraps(task.run)
    def run(*args, **kwargs):
        try:
            return task._orig_run(*args, **kwargs)
        except autoretry_for as exc:
            if retry_backoff:
                retry_kwargs['countdown'] = \
                    get_exponential_backoff_interval(
                        factor=retry_backoff,
                        retries=task.request.retries,
                        maximum=retry_backoff_max,
                        full_jitter=retry_jitter)
&gt;           raise task.retry(exc=exc, **retry_kwargs)
E           TypeError: exceptions must derive from BaseException
</code></pre>

<p>I understand it is because of the exception. I replaced <code>ObjectDoesNotExist</code> everywhere with <code>Exception</code> instead. After running the test, I get this error:</p>

<pre><code>    def assert_called_with(self, /, *args, **kwargs):
        """"""assert that the last call was made with the specified arguments.

            Raises an AssertionError if the args and keyword args passed in are
            different to the last call to the mock.""""""
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\nActual: %s'
                    % (expected, actual))
            raise AssertionError(error_message)

        def _error_message():
            msg = self._format_mock_failure_message(args, kwargs)
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
&gt;           raise AssertionError(_error_message()) from cause
E           AssertionError: expected call not found.
E           Expected: retry(exc=Exception())
E           Actual: retry(exc=Exception(), countdown=7)
</code></pre>

<p>Please let me know how I can fix both the errors.</p>
",https://stackoverflow.com/questions/61681632/assertionerror-on-unit-testing-a-celery-task-with-autoretry-backoff-and-jitter,"['django', 'python-3.x', 'celery', 'django-celery', 'celery-task']",1170,False,1,1
Unit testing Spring Boot RestController that invokes Google Calendar API with OAuth2,"<p>I'm building a rather simple Spring Boot API which integrates with Google Calendar. I authenticate to Google Calendar using OAuth2  and then do my Calendar specific requests in my controller.</p>
<p>Now, testing a RestController is simple enough but I'm stumped for how to Unit (not Integration) test code that uses both OAuth2  and a 3rd party API.</p>
<p>I am using the Google Cloud Java Client library but I'm not certain if I should try to mock those classes, somehow  intercept the HTTP request/response that the library makes or some third option. Such as abstracting away the Calendar API to some service and mock that instead (since that also let's me hide OAuth2) or in some other way inject some &quot;authorized&quot; mock client.<br />
I'm a little concerned that  I will end up mocking away &quot;too much&quot;.</p>
<p>Grateful for any help to get started on the right foot.</p>
",https://stackoverflow.com/questions/64540227/unit-testing-spring-boot-restcontroller-that-invokes-google-calendar-api-with-oa,"['java', 'spring-boot', 'junit', 'google-oauth', 'google-calendar-api']",174,False,1,0
How to mock ElasticsearchOperations (spring-data-elasticsearch v.4.0.3) when unit testing,"<p>I am working on a project that uses Spring 2.3.3, spring-data-elastic-4.0.3, ElasticSearch 7.9.0 and mockito-core 3.3.3</p>
<p>I'm trying to mock ElasticsearchOperations when writing unit tests, this is the Service I would like to test (where it's used ElasticsearchOperations):</p>
<pre><code>@Service
public class SearchByLabelServiceImpl implements SearchByLabelService {
     private ElasticsearchOperations elasticsearchTemplate;
    
        public SearchByLabelServiceImpl(ElasticsearchOperations elasticsearchTemplate) {
            this.elasticsearchTemplate = elasticsearchTemplate;
        }
    
    public SearchPage&lt;TagResponse&gt; searchByLabel(String query, List&lt;String&gt; labelsToExclude, boolean shouldIncludeDescription, Pageable pageable) {

    ....
    enter code here
    var result = elasticsearchTemplate.search(nativeSearchQuery, TagResponse.class, IndexCoordinates.of(tagIndexName));


}
</code></pre>
<p>And this is the Test class:</p>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = &quot;test&quot;)
public class SearchByLabelServiceImplTest {


private ElasticsearchOperations elasticsearchTemplate = mock(ElasticsearchOperations.class);

    private SearchByLabelService searchByLabelService = new SearchByLabelServiceImpl(elasticsearchTemplate);

    @Test
    @Ignore
    public void shouldReturnTheTagsBasedOnSearchRequestIncludingDescription() {

   ...//Arrange

when(elasticsearchTemplate.search(queryArgumentCaptor.capture(), eq(TagResponse.class), IndexCoordinates.of(tagIndexName))).thenReturn(searchHitsResponse);

        var searchResponse = searchByLabelService.searchByLabel(testSearchQuery, testLabelsToExcludeList, true, PageRequest.of(1, 1));

....

//Assertions 

}
   
</code></pre>
<p>And the error I get is this one:</p>
<pre><code>org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: interface org.springframework.data.elasticsearch.core.ElasticsearchOperations.

Mockito can only mock non-private &amp; non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.


Java               : 11
JVM vendor name    : Oracle Corporation
JVM vendor version : 11.0.5+10-LTS
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 11.0.5+10-LTS
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 10.15.7


Underlying exception : java.lang.TypeNotPresentException: Type org.elasticsearch.cluster.metadata.AliasMetaData not present

    at com.optum.genesis.tag.service.SearchByLabelServiceImplTest.&lt;init&gt;(SearchByLabelServiceImplTest.java:41)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:250)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:226)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    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$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    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)
Caused by: java.lang.TypeNotPresentException: Type org.elasticsearch.cluster.metadata.AliasMetaData not present   
</code></pre>
<p>Many thanks in advance.</p>
",https://stackoverflow.com/questions/64589066/how-to-mock-elasticsearchoperations-spring-data-elasticsearch-v-4-0-3-when-uni,"['spring-boot', 'unit-testing', 'elasticsearch', 'mockito', 'spring-data-elasticsearch']",3873,True,1,2
Skipping a send email function and celery task during the unit testing,"<p>I have a Django view that I want to unit test it but the problem is in some line of the function it calls another function which has a send email function and this send email function has a celery task inside it. I don't know what to do to surpass this function call because when the debugger hits the send email function it stops and does nothing which I think is because of the celery task.
Due to this problem, my unit test can't run completely. <br>
So I would be happy if someone could tell me what to do then. My own solution was to mock the sending email function but it doesn't work. I don't know what to do now. <br>
here is the code example of what happens during the view function. <br></p>
<pre><code>view_funtion():
...
function_a is called here
</code></pre>
<pre><code>function_a():
...
send_email_function is called here
</code></pre>
<pre><code>send_email_function():
some code here and initialization of the email template
celery_task.delay()
</code></pre>
<p>please let me know if I should add more detail. Thanks. <br>
<strong>Update</strong>: <br>
this is the unit test function <br></p>
<pre><code>@patch('path_to_send_email_function')
    def test_view_function(self, mock_send_email):
       mock_send_email.return_value = None
       ...
</code></pre>
<p>I also use the API request factory which is for the Django rest framework for testing the view. The execution steps are in the body of the test the view function is called and it executes until function_a is called and then send_email_function is called in the body of function_a.</p>
",https://stackoverflow.com/questions/64423104/skipping-a-send-email-function-and-celery-task-during-the-unit-testing,"['python', 'unit-testing', 'django-rest-framework', 'mocking', 'celery']",322,False,1,0
Net Framework Xunit With Moq Unit Testing Keep Calling The Original Function,"<p>I have a problem with mocking cause it keep calling the original function. This is my demo code</p>

<p>First file is interface that contains the function that I want to mock.</p>

<pre><code>public interface IDemoReplace
{
    int FunctionToBeReplaced();
}
</code></pre>

<p>Second file is a class that actually has the implementation for the function</p>

<pre><code>public class DemoReplace : IDemoReplace
{
    public int FunctionToBeReplaced()
    {
        //this function contains sql query in my real project
        return 1;
    }
}
</code></pre>

<p>Third file is a class that I want to test</p>

<pre><code>public class ClassToBeTested
{
    public int TestThisFunction()
    {
        IDemoReplace replace = new DemoReplace();
        var temp = replace.FunctionToBeReplaced();
        return temp;
    }
}
</code></pre>

<p>Last file is the test class</p>

<pre><code>public class TestClass
{

    [Fact]
    public void TryTest()
    {
        using (var mock = AutoMock.GetLoose()) {
            //Arrange
            mock.Mock&lt;IDemoReplace&gt;()
                .Setup(x =&gt; x.FunctionToBeReplaced())
                .Returns(returnTwo());

            var classToBeTested = mock.Create&lt;ClassToBeTested&gt;();
            var expected = 2;

            //Act
            var actual = classToBeTested.TestThisFunction();

            //Assert
            Assert.Equal(expected, actual);
        }
    }

    public int returnTwo() {
        return 2;
    }
}
</code></pre>

<p>This test will be failed with expected is 2 and actual is 1. When I tried to debug it doesn't call <code>returnTwo</code> but call the original function instead. </p>

<p>I am new to unit testing so what did I miss? Please be considered that the code above is only a demo of what is happened in my actual project. <code>FunctionToBeReplaced</code> is actually a function that execute and return record from database so I want to mock that function. </p>

<p>Thanks :)</p>
",https://stackoverflow.com/questions/60811652/net-framework-xunit-with-moq-unit-testing-keep-calling-the-original-function,"['asp.net', 'unit-testing', 'moq', 'xunit']",165,True,1,1
Android unit testing using Mockito : can&#39;t get the right behaviour for mocks,"<p>I am testing my Repository class using Mockito, specifically getProducts() functionality:</p>
<pre><code>class Repository private constructor(private val retrofitService: ApiService) {

    companion object {
        @Volatile
        private var INSTANCE: Repository? = null

        fun getInstance(retrofitService: ApiService): Repository {
            synchronized(this) {
                var instance = INSTANCE
                if (instance == null) {
                    instance = Repository(retrofitService)
                }
                INSTANCE = instance
                return instance
            }
        }
    }

    suspend fun getProducts(): ProductsResponse = withContext(IO) {
        retrofitService.getProducts()
    }
}
</code></pre>
<p>This is my test class:</p>
<pre><code>@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class RepositoryTest {

    // Class under test
    private lateinit var repository: Repository

    // Executes each task synchronously using Architecture Components.
    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    // Set the main coroutines dispatcher for unit testing.
    @ExperimentalCoroutinesApi
    @get:Rule
    var mainCoroutineRule = MainCoroutineRule()

    @Mock
    private lateinit var retrofitService: ApiService

    @Before
    fun createRepository() {
        MockitoAnnotations.initMocks(this)
        repository = Repository.getInstance(retrofitService)
    }

    @Test
    fun test() = runBlocking {

        // GIVEN
        Mockito.`when`(retrofitService.getProducts()).thenReturn(fakeProductsResponse)

        // WHEN
        val productResponse: ProductsResponse = repository.getProducts()

        println(&quot;HERE = ${retrofitService.getProducts()}&quot;)

        // THEN
        println(&quot;HERE: $productResponse&quot;)
        MatcherAssert.assertThat(productResponse, `is`(fakeProductsResponse))
    }
}
</code></pre>
<p>And my ApiService:</p>
<pre><code>interface ApiService {
    @GET(&quot;https://www...&quot;)
    suspend fun getProducts(): ProductsResponse
}
</code></pre>
<p>When I call <code>repository.getProducts()</code>, it returns null despite the fact, that I explicitly set <code>retrofitService.getProducts()</code> to return <code>fakeProductsResponse</code>, which is being called inside repository's <code>getProducts()</code> method. It should return <code>fakeProductsResponse</code>, but it returns null.</p>
<p>Am I doing wrong mocking or what the problem can be? Thanks...</p>
<p>EDIT: this is my <code>MainCoroutineRule</code>, if you need it</p>
<pre><code>@ExperimentalCoroutinesApi
class MainCoroutineRule(val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()):
    TestWatcher(),
    TestCoroutineScope by TestCoroutineScope(dispatcher) {
    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(dispatcher)
    }

    override fun finished(description: Description?) {
        super.finished(description)
        cleanupTestCoroutines()
        Dispatchers.resetMain()
    }
}
</code></pre>
",https://stackoverflow.com/questions/65244685/android-unit-testing-using-mockito-cant-get-the-right-behaviour-for-mocks,"['android', 'unit-testing', 'kotlin', 'mockito', 'android-testing']",321,True,1,1
Why is RefreshDatabase seem to be required when unit testing Laravel Passport?,"<p>I am using Laravel Passport to build an API for my Vue application. I am able to send <code>POST</code> request via browser and Postman without any issues.</p>

<p>I am (learning) about writing unit tests and would like to test my <code>store</code> method.</p>

<p>Here is what my sample test looks like:</p>

<pre><code>/** @test */
public function a_user_can_create_a_thing()
{
    $this-&gt;withExceptionHandling();

    $thing = factory(Thing::class)-&gt;raw();

    $response = $this-&gt;post('api/v1/thing', $thing);

    $response-&gt;assertStatus(200);

    $this-&gt;assertDatabaseHas('things', $thing);
}
</code></pre>

<p><strong>Controller.php</strong></p>

<pre><code>public function store(Request $request)
{
    $attributes = request()-&gt;validate([
        'foo' =&gt; 'nullable',
        'bar' =&gt; 'required',
        'baz' =&gt; 'required',
    ]);

    $thing = Thing::create($attributes);

    return response()-&gt;json(['data' =&gt; $thing], 200);
}
</code></pre>

<p>I'm not checking/setting any authentication at this point (yet). Maybe that's where I'm going wrong.</p>

<p><strong>routes/api.php</strong></p>

<pre><code>Route::prefix('v1')-&gt;group(function () {
    Route::post('thing', 'Api\v1\ThingController@store');
});
</code></pre>

<p>If I use <code>dd($thing)</code> I can see that everything is getting generated correctly and my controller is picking everything up as expected.</p>

<p>The error I get back is:</p>

<blockquote>
  <p>Expected status code 200 but received 500.
  Failed asserting that false is true.</p>
</blockquote>

<p>In Postman, If I send a <code>POST</code> request to the same controller: <code>http://mysite.local/api/v1/thing</code></p>

<p>Everything works great.</p>

<p>If I add <code>RefreshDatabase</code> my test passes. I don't understand why.</p>

<p>I've looked at the docs and added:</p>

<pre><code>...
Passport::actingAsClient(
    factory(Client::class)-&gt;create(),
    ['check-status']
);
...
</code></pre>

<p>I get other additional errors using that. I've found <a href=""https://laracasts.com/discuss/channels/testing/test-fails-always-500-where-200-expected"" rel=""nofollow noreferrer"">a post on Laracasts</a> that suggested setting <code>RefreshDatabase</code>. What that <em>does</em> seem to make the test pass, I don't feel super great about it.</p>

<p>How can I be sure my test(s) will work? I feel like this is a really basic test. Thank you for any suggestions!</p>
",https://stackoverflow.com/questions/60079913/why-is-refreshdatabase-seem-to-be-required-when-unit-testing-laravel-passport,"['laravel', 'laravel-passport', 'laravel-6']",215,False,1,0
How do we do Unit testing for AWS CDK code? And should we?,"<p>Based on the examples I see, the code assertions are expected json cf template versus the cdk synth generated template.</p>

<p>How do we setup expected json cf template? </p>

<ul>
<li>If we manually create it, that defeats the purpose of using cdk. </li>
<li>If we just copy paste the cdk synth output, that defeats the purpose of unit testing it.</li>
</ul>

<p>Having said that, is there a purpose on having unit tests for CDK code?
Maybe I'm missing the idea here. Please do point it out.</p>
",https://stackoverflow.com/questions/60225645/how-do-we-do-unit-testing-for-aws-cdk-code-and-should-we,"['amazon-web-services', 'aws-cloudformation', 'aws-cdk']",6294,True,7,2
Unit testing branch coverage(100%) using @testing-library/react (react-testing-library),"<p>How to cover all branches (100%) in unit testing using @testing-library/react (react-testing-library).</p>
<p>Below are some scenarios</p>
<ol>
<li><p>Conditonal Statements</p>
<pre><code>const num = getNum();
if(num%2 === 0){
  statements...
} else {
  statements...
}
</code></pre>
</li>
</ol>
<p>How to cover statements in both if and else branch?</p>
<ol start=""2"">
<li><p>Private methods in component</p>
<pre><code>const onDateSelectorChange = (elem, value) =&gt; {
  statements...
} 
</code></pre>
</li>
</ol>
<p>How to cover statements in private method like above, that are created to pass as props to child and
only triggered from child?</p>
",https://stackoverflow.com/questions/63328947/unit-testing-branch-coverage100-using-testing-library-react-react-testing-l,"['reactjs', 'unit-testing', 'react-testing-library', 'testing-library']",3498,True,1,1
Laravel GraphQL Lighthouse unit testing mutation returns error &quot;Syntax Error: Unexpected &lt;EOF&gt;&quot;,"<p>I am working on a Laravel project. I am developing an API using GraphQL Lighthouse. I am writing the unit tests for my application where it involves file upload feature. But it is throwing error.</p>
<p>This is my mutation code:</p>
<pre><code>class CreateMenuItem
{
    public function __invoke($_, array $args)
    {
        //create menu item and returns

        return $menuItem;
    }
}
</code></pre>
<p>I have a schema for the mutation as follows:</p>
<pre><code>input CreateMenuItemInput {
    image: Upload
    name: String
    price: Float
    menu_item_option_name: [String]
    menu_item_option_price: [Float]
    menu_item_extra_name: [String]
    menu_item_extra_price: [Float]
}

extend type Mutation @middleware(checks: [&quot;auth:api&quot;, &quot;auth.restaurant-admin&quot;]) {
    createMenuItem(input: CreateMenuItemInput): MenuItem! @createMenuItemValidation
}
</code></pre>
<p>This is my validation directive:</p>
<pre><code>use Nuwave\Lighthouse\Schema\Directives\ValidationDirective;

class CreateMenuItemValidationDirective extends ValidationDirective
{
    public function name()
    {
        return 'createMenuItemValidation';
    }

    public function rules(): array
    {
        return [
            'input.name' =&gt; [ 'required' ],
            'input.price' =&gt; [ 'required', 'numeric' ],
            'input.menu_item_option_name' =&gt; [ 'required', 'array' ],
            'input.menu_item_option_price' =&gt; [ 'required', 'array' ],
            'input.menu_item_extra_name' =&gt; [ 'required', 'array' ],
            'input.menu_item_extra_price' =&gt; [ 'required', 'array' ],
        ];
    }
}
</code></pre>
<p>I can create the menu item from the GraphQL playground. But when I write the test for it, it is failing. This is my test:</p>
<pre><code>class CreateMenuItemTest extends RestaurantAdminTestCase
{
    /** @test */
    public function creating_menu_item_create_menu_if_not_exists()
    {
        Passport::actingAs($this-&gt;restaurantAdmin);
        $imageFile = UploadedFile::fake()-&gt;create('image.jpg', 500);
        $this-&gt;multipartGraphQL(
            [
                'operations' =&gt;
                    '
                    {
                        &quot;query&quot;: &quot;mutation Upload($image: Upload) { createMenuItem(input: { image: $image, name: &quot;testing&quot;, price: 12, menu_item_option_name:[ &quot;testing 1&quot;, &quot;testing 2&quot; ], menu_item_option_price:[ 11, 12 ], menu_item_extra_name:[ &quot;testing 1&quot;, &quot;testing 2&quot; ], menu_item_extra_price:[ 12, 13 ] }) { id } }&quot;,
                        &quot;variables&quot;: {
                            &quot;image&quot;: null
                        }
                    }
                    ',
                'map' =&gt;
                    '
                    {
                        &quot;0&quot;: [&quot;variables.image&quot;]
                    }
                    '
            ],
            [
                '0' =&gt; $imageFile
            ]
        );
    }
}
</code></pre>
<p>It is not even hitting the mutation. I get the following response.</p>
<pre><code>[{
    &quot;errors&quot;: [
        {
            &quot;message&quot;: &quot;Syntax Error: Unexpected &lt;EOF&gt;&quot;,
            &quot;extensions&quot;: {
                &quot;category&quot;: &quot;graphql&quot;
            },
            &quot;locations&quot;: [
                {
                    &quot;line&quot;: 1,
                    &quot;column&quot;: 1
                }
            ]
        }
    ]
}].
</code></pre>
<p>What is wrong with my code and how can I fix it?</p>
",https://stackoverflow.com/questions/63177063/laravel-graphql-lighthouse-unit-testing-mutation-returns-error-syntax-error-un,"['laravel', 'graphql', 'laravel-lighthouse']",2017,True,1,2
Angular Unit Testing: Observable variable value not updating in the data service,"<p>I have a data service that is used by a component.</p>

<p>For example:</p>

<p>BookService:</p>

<pre><code>...
private book: Book;
private bookSubject = new BehaviorSubject&lt;Book&gt;(this.book);
bookChanged = this.bookSubject.asObservable();
...
</code></pre>

<p>BookComponent:</p>

<pre><code>...
book: Book;
ngOnInit() {
  this.bookService.bookChanged.subscribe(
    (book: Book) =&gt; this.book = book;
  )
}
...
</code></pre>

<p>Spec (test file) for the component:</p>

<pre><code>describe('BookComponent', () =&gt; {
  let component: BookComponent;
  let fixture: ComponentFixture&lt;BookComponent&gt;;
  let bookServiceStub: Partial&lt;BookService&gt;;

  bookServiceStub = {
    bookChanged: of({id: 123, name: 'Book 1'})
  };
  beforeEach(async(() =&gt; {
    TestBed
      .configureTestingModule({
        declarations: [BookComponent],
        providers: [
          {provide: BookService, useValue: bookServiceStub},
          ...
        ]
      })
      .compileComponents();
  }));

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

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

  it('should change the book with a new one', fakeAsync(() =&gt; {
    const newBook = {
      id: 769,
      name: 'Book 2'
    };
    bookServiceStub.bookChanged = of(newBook);
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
      fixture.detectChanges();
      expect(component.book.id).toBe(newBook.id); // FAILS (still has old value)
      expect(component.book).toBe(newBook); // FAILS (still has old value)
    });
  }));
});

</code></pre>

<p>So the tests fail because the ""book"" variable does not update with the new values. </p>

<p><strong>What am I doing wrong here?</strong></p>

<p>NOTE: I actually wanted to test if the subscriptions in the component are working as expected or not! </p>

<p>REASON: I would like to check-in further tests that when the value in service is updated, does the DOM changes automatically or not</p>
",https://stackoverflow.com/questions/62153807/angular-unit-testing-observable-variable-value-not-updating-in-the-data-service,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-test']",4128,True,1,3
What are the advantages and disadvantages of conducting non-isolated unit testing?,"<p>I created a simple project for conducting unit tests, here is the sample code:</p>

<pre><code>        [TestMethod]
        public async Task GetCountry_ShouldReturnAndorra()
        {
            // Arrange
            int countryId = 1;
            string requestUrl = baseUrl + ""/Countries/"" + countryId;

            // Act
            // GET : /api/v1/Locations/Countries/{countryId} 
            HttpResponseMessage response = await client.GetAsync(requestUrl); 

            // Assert
            Assert.IsTrue(response.IsSuccessStatusCode, ""Response StatusCode is not success"");

            string value = await response.Content.ReadAsStringAsync();
            Assert.IsNotNull(value);

            var country = DeserializeCountryResponse(value);
            Assert.AreEqual(country.data.Id, countryId);

            Assert.AreEqual(country.errors.Count, 0, 0, ""Reponse contains errors"");
        }
</code></pre>

<p>And this project depends on whether the API server is running and its dependencies (databases, etc.)</p>

<p>But the documentation says that this is not the best practice (<a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices#characteristics-of-a-good-unit-test"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices#characteristics-of-a-good-unit-test</a>):</p>

<blockquote>
  <p><strong>Characteristics of a good unit test</strong></p>
  
  <p>...</p>
  
  <p><strong>Isolated.</strong> Unit tests are standalone, can be run in isolation, and have no dependencies on any outside factors such as a file system or database.</p>
  
  <p>...</p>
</blockquote>

<p>So should you go this way or is there another?</p>
",https://stackoverflow.com/questions/61094328/what-are-the-advantages-and-disadvantages-of-conducting-non-isolated-unit-testin,"['c#', 'unit-testing', 'asp.net-web-api']",72,True,1,1
Why I get java.lang.IllegalStateException while unit-testing module that works with Firebase?,"<p>I unit-test the class that performs some logic with Firebase. All the unit tests on that module seemed to work fine apprx. 2 weeks ago. This week I changed a lot of stuff in my app and today unit-tests, mentioned above, threw errors.</p>
<blockquote>
<p>java.lang.IllegalStateException: Failed to transform class with name com.google.firebase.messaging.RemoteMessage. Reason: getSentTime ()J in com.google.firebase.messaging.RemoteMessage: inconsistent stack height -1</p>
</blockquote>
<p>Unit-test:</p>
<pre><code>    @Test
    public void onMessageReceived() throws Exception {
        PowerMockito.mockStatic(UiTools.class);
        PowerMockito.mockStatic(RemoteMessage.class);
        fcmService = spy(Whitebox.newInstance(FcmService.class));
        Service service = mock(Service.class);
        PowerMockito.whenNew(Service.class).withNoArguments().thenReturn(service);
        Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
        map.put(&quot;message&quot;, &quot;test&quot;);
        remoteMessage = mock(RemoteMessage.class);
        PowerMockito.when(remoteMessage.getData()).thenReturn(map);
        PowerMockito.when(remoteMessage.getNotification()).thenReturn(mock(RemoteMessage.Notification.class));
        PowerMockito.doNothing().when(UiTools.class, &quot;sendNotification&quot;, anyString(), anyString());
        fcmService.onMessageReceived(remoteMessage);
        verify((FirebaseMessagingService)fcmService).onMessageReceived(remoteMessage);
    }
</code></pre>
<p>I try to mock RemoteMessage, try to spy RemoteMessage, try to use WhiteBox on RemoteMessage - but error not fixed.</p>
<p>When I change mock RemoteMessage to create new object</p>
<pre><code>final HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;();
map.put(&quot;message&quot;, &quot;test message&quot;);
RemoteMessage remoteMessage = new RemoteMessage.Builder(&quot;test&quot;).setData(map).build();
/* next string is DataApi_FcmServiceTest.java:97 - look on next error */
fcmService.onMessageReceived(remoteMessage); 
</code></pre>
<p>I get new error:</p>
<pre><code>java.lang.NullPointerException
    at com.google.firebase.messaging.Constants$MessagePayloadKeys.extractDeveloperDefinedPayload(com.google.firebase:firebase-messaging@@21.0.1:2)
    at com.google.firebase.messaging.RemoteMessage.getData(com.google.firebase:firebase-messaging@@21.0.1:1)
    at club.people.fitness.data_api.FcmService.onMessageReceived(FcmService.java:30)
    at club.people.fitness.data_api.DataApi_FcmServiceTest.onMessageReceived(DataApi_FcmServiceTest.java:97)
</code></pre>
<p>And this error I can't fix becouse in method getData() Firebase want to do this: <code>this.bundle.putString(&quot;collapse_key&quot;, var1);</code> but this.bundle allways null</p>
",https://stackoverflow.com/questions/65410297/why-i-get-java-lang-illegalstateexception-while-unit-testing-module-that-works-w,"['android', 'firebase', 'junit', 'mockito', 'powermockito']",217,False,1,0
Angular Unit Testing - Verify emitted value from an observable using marble testing,"<p>I'm creating some unit tests for an Angular application that I have. I have managed to test services that make HTTP calls without any problems. I now moved to a different kind of service, which is shown below.</p>

<p><strong>Code</strong></p>



<pre><code>import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

import { UICoupon } from '../models';

@Injectable()
export class ClaimCouponService {
    hasClaimedCoupons = false;

    claimedCoupons: UICoupon[] = [];

    onClaimCoupons: Observable&lt;UICoupon[]&gt;;

    private couponsUpdate: Subject&lt;UICoupon[]&gt; = new Subject&lt;UICoupon[]&gt;();

    constructor() {
        this.onClaimCoupons = this.couponsUpdate.asObservable();
    }

    claimCoupon(coupon: UICoupon) {
        if (!coupon.claimed) {
            coupon.claimed = true;
            this.claimedCoupons.push(coupon);
        }
        this.hasClaimedCoupons = true;
        this.couponsUpdate.next(this.claimedCoupons);
    }
}
</code></pre>

<p>I have managed to test the logic for this service using the ""Subscribe / Assert pattern"". Using the below code:</p>



<pre><code>...

it('should claim a coupon', (done) =&gt; {
    claimCouponsService.onClaimCoupons
        .subscribe(claimedCoupons =&gt; {
            expect(claimedCoupons).toEqual([mockData[0]]);
            done();
        });

    claimCouponsService.claimCoupon(mockData[0]);
});
</code></pre>

<p>The above works well, however I was researching and I was curious about Marble Testing. I've read a few articles and I like how the logic is structured in the test. I've tried to replicate the above test with Marble Testing, but in my case I couldn't find a way to verify what is emitted from the service after the <code>claimCoupon(...)</code> function is run.</p>



<pre><code>let scheduler: TestScheduler;
let claimCouponsService: ClaimCouponsService;

...

it('should claim a coupon', (done) =&gt; {
    const expectedObservable = claimCouponsService.onClaimCoupons;

    scheduler.run(runHelpers =&gt; {
        claimCouponsService.claimCoupon(mockData[0]);

        const expectedMarble = '^a|';
        const expectedData = { a: [mockData[0]] };

        runHelpers.expectObservable(expectedObservable)
            .toBe(expectedMarble, expectedData);
    });
});
</code></pre>

<p>I'm pretty sure that this is possible, but I have some kind of mistake in my test - or haven't really understood the way marble testing works. The above results in an error <code>Expected $.length = 0 to equal 1.</code> which I think means that the observable didn't get any values. I know the test I wrote does run successfully, however I'm curious to see how Marble Testing can be used.</p>
",https://stackoverflow.com/questions/60817058/angular-unit-testing-verify-emitted-value-from-an-observable-using-marble-test,"['angular', 'rxjs', 'angular-test']",453,False,1,0
Run typemock unit testing on Visual Studio without typemock extension tools installed,"<p>I need run Typemock unit tests on Visual Studio without the typemock extension installed.
Of course, I have a license for typemock. Can I achieve the functionality of 'Integrate with Other Runners' without installing extension tools?</p>
",https://stackoverflow.com/questions/60679706/run-typemock-unit-testing-on-visual-studio-without-typemock-extension-tools-inst,['typemock'],50,False,1,0
"Unit testing vuex action in typescript, how to pass the this value?","<p>I'm using Vuex in a typescript setup and want to unit test an action, but having trouble with setting the <code>this</code> parameter of the action method.</p>

<p>Action is something like this:</p>

<pre><code>export const login: ActionHandler&lt;AuthState, RootState&gt; = ({ commit },
  creds: { email: string, password: string }) =&gt; {
};
</code></pre>

<p>Test is as follows:</p>

<pre><code>  describe('actions', () =&gt; {
    test('login should call api with credentials', () =&gt; {
      (ApiService.post as jest.Mock).mockResolvedValue({
        data: { userId: 1234 }
      });
      const commit = jest.fn();
      login({ commit }, { email: 'username@gmail.com', password: 'Pa$$w0rd123' });
    });
  });
</code></pre>

<p>Problem is the <code>ActionHandler</code> is having a signature like:
<code>login(this: Store&lt;RootState&gt;, injectee: ActionContext&lt;AuthState, RootState&gt;, payload?: any): any</code>.</p>

<p>And TS is giving me an error:</p>

<pre><code>The 'this' context of type 'void' is not assignable to method's 'this' of type 'Store&lt;RootState&gt;'.ts(2684)
</code></pre>

<p>I'm unable to figure out how to set an instance of <code>Store&lt;RootState&gt;</code> as the <code>this</code> of the login action. Am I doing this wrong? I understand this issue would not arise if I use vanilla JS, but would like to keep using TS if that's possible.</p>
",https://stackoverflow.com/questions/60013817/unit-testing-vuex-action-in-typescript-how-to-pass-the-this-value,"['typescript', 'unit-testing', 'vue.js', 'jestjs', 'vuex']",1636,False,1,2
Database function Mock is not working in c# web api unit testing,"<p>Here is my controller method</p>
<pre><code>[HttpPost]
    [Authorize]
    [Route(RouteConfig.Routes.LovList.contactStatus)]
    public IHttpActionResult ContactStatusList()
    {
        try
        {
            var result = new DBClass.HeroDb().GetList(
                            DBClass.DBConstants.ListConstants.query_Contact_Status);
            return Json(new Models.Response(
                        Models.ResponseMessages.Success,
                        result)
                     );
        }
        catch(System.Data.SqlClient.SqlException)
        {
            return InternalServerError();
        }
        catch(System.Exception ex)
        {
            Logger.Error(ex, ex.Message, ex.StackTrace);
            return InternalServerError();
        }
        
    }
</code></pre>
<p>and this is my test case method</p>
<pre><code>[TestMethod()]
    public void ContactStatusListTest()
    {
        
        Mock&lt;DBClass.HeroDb&gt; mock = new Mock&lt;DBClass.HeroDb&gt;();
        mock.Setup(x =&gt; x.GetList(DBClass.DBConstants.ListConstants.query_Contact_Status))
            .Returns(CreateContactList());
        var result = new ListController().ContactStatusList();
        Models.Response response = (Models.Response)result;
        Assert.AreEqual(response.Message, Models.ResponseMessages.Success);
        Assert.IsNotNull(response.Data);
    }
    public System.Data.DataTable CreateContactList()
    {
        DataTable table = new DataTable();
        table.Columns.Add(&quot;ContactStatus&quot;);
        DataRow row1 = table.NewRow();row1[&quot;ContactStatus&quot;] = &quot;Contacted&quot;; table.Rows.Add(row1);
        DataRow row2 = table.NewRow(); row2[&quot;ContactStatus&quot;] = &quot;Not Contacted&quot;; table.Rows.Add(row2);
        DataRow row3 = table.NewRow(); row3[&quot;ContactStatus&quot;] = &quot;Contacted&quot;; table.Rows.Add(row3);
        return table;
    }
</code></pre>
<p>I tried to mock <strong>GetList()</strong> function in my test method but it is not working. Controller method is giving an Internal server error . Because conrol is going to</p>
<pre><code>var result = new DBClass.HeroDb()
            .GetList(DBClass.DBConstants.ListConstants.query_Contact_Status);
</code></pre>
<p>this line and db object is null here. Please help as i am beginner in unit test case building .</p>
",https://stackoverflow.com/questions/64059728/database-function-mock-is-not-working-in-c-web-api-unit-testing,"['c#', 'unit-testing', 'mocking', 'webapi', 'rest']",574,True,1,1
Unit testing to check that the accept was called when using RxBindings,"<pre><code>AS 4.0.2
RxBindings 4.0.0
</code></pre>
<p>I have written a unit test for testing if the PublishRelay accept has been called that uses jakeWartons rxBindings</p>
<p>This is the snippet of code I am testing</p>
<pre><code>private val checkStoresRelay: Relay&lt;Unit&gt; = PublishRelay.create&lt;Unit&gt;()

private fun onCheckStockTapped(view: View) {
    view.textViewCheckStock
        .clicks()
        .debounce(TIME_OUT, TimeUnit.MILLISECONDS)
        .subscribeBy(
            onNext = checkStoresRelay::accept,
            onError = { Timber.e(it, it.localizedMessage) }
        )
}
</code></pre>
<p>In the test class I am doing the following. The <code>textViewCheckStock.performClick()</code> will trigger and I check that the checkStoresRelay.accept(Unit) had been called.</p>
<p>But I am not sure about the <code>availableDeliveryOptionsModel.checkStoresRelay.accept(Unit)</code> As I don't think I should be calling this in the test. However, the test will fail if I remove this. Just wondering what would be the best way to test this?</p>
<pre><code>@Test
fun `should check stores when checkStock is tapped`() {
    // Arrange
    val viewHolder = createViewHolder()
    availableDeliveryOptionsModel.bind(viewHolder)
    val actual = availableDeliveryOptionsModel.checkStoresRelay.test()

    // Act
    availableDeliveryOptionsModel.checkStoresRelay.accept(Unit)
    viewHolder.itemView.textViewCheckStock.performClick()

    // Assert
    actual.assertValue(Unit)
}
</code></pre>
<p>Many thanks for any suggestions,</p>
",https://stackoverflow.com/questions/64328289/unit-testing-to-check-that-the-accept-was-called-when-using-rxbindings,"['android', 'unit-testing', 'rx-java2', 'rx-binding']",416,True,1,1
How to patch or mock subsequent API calls in python unit testing?,"<p>I have following function</p>
<pre><code>def test_dir_creation():
    if not os.path.exists(root_dir_path):
        raise Exception(&quot;Root dir don't exits&quot;)

    if not os.path.exists(log_dir_path):
        raise Exception(&quot;Log dir don't exits&quot;)

    if not os.path.exists(subscription_handle_dir_path):
        raise Exception(&quot;subscription_handle_dir_path dir don't exits&quot;)
</code></pre>
<p>I want to test three conditions for that my test case is as follows -</p>
<pre><code>@mock.patch(&quot;os.path.exists&quot;, return_value=False)
def test_args_parser_when_root_dir_dont_exists(*mocks):
    with pytest.raises(Exception) as excinfo:
        args_parser()
    expected_message = &quot;Root dir don't exits&quot;
    assert expected_message in str(excinfo)
</code></pre>
<p>This test case works but I want to test other two conditions as well, how to do that?</p>
<p>How I can patch something like os.path.exists(log_dir_path) == False?</p>
",https://stackoverflow.com/questions/63393590/how-to-patch-or-mock-subsequent-api-calls-in-python-unit-testing,"['python', 'unit-testing']",81,False,1,1
Unit testing retrofit2 call giving me a null when mocking Call&lt;Void&gt;,"<p>I've seen a lot of different ways people have tested their unit tests for retrofit2 and I feel like this has been the closest I've come. I'm able to mock my api interface but when it comes down to mocking the call, the call always comes back <code>null</code>. Is there anything that I'm missing or doing incorrectly?</p>

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

<pre><code>@Test
public void testApiSuccess() {
    TestRequestBody testRequestBody = Util.getTestBody();

    ApiService mockedApiService = Mockito.mock(ApiService.class);
    Call&lt;Void&gt; mockedCall = Mockito.any(Call.class);

    when(mRestClient.apiService()).thenReturn(mockedApiService);
    Mockito.when(mockedApiService.executeApi(testRequest)).thenReturn(mockedCall);

    Mockito.doAnswer(invocation -&gt; {
        Callback&lt;Void&gt; callback = invocation.getArgumentAt(0, Callback.class);
        callback.onResponse(mockedCall, Response.success(null));
        return null;
    }).when(mockedCall).enqueue(any(Callback.class));

    presenter.executeApi();
    verify(view).showSuccess();
}
</code></pre>

<p>The code block that I'm testing is as follows:</p>

<pre><code>@Override
public void executeApi() {
    RequestBody requestBody = getRequestbody();

    Call&lt;Void&gt; call = mRestClient.apiService().executeApi(requestBody);
    call.enqueue(new Callback&lt;Void&gt;() {
        @Override
        public void onResponse(Call&lt;Void&gt; call, Response&lt;Void&gt; response) {
            if (response != null &amp;&amp; response.code() == 200) {
                view.showSuccess();
            } else {
                view.showError();
            }
        }

        @Override
        public void onFailure(Call&lt;Void&gt; call, Throwable t) {
            view.showError();
        }
    });
}
</code></pre>

<p>My test goes up until the <code>call.enqueue</code> and fails here because the <code>call</code> is null. Something is wrong when I'm trying to mock the <code>call</code>. Been stumped here now for half the day. Any clues could help.</p>
",https://stackoverflow.com/questions/60824911/unit-testing-retrofit2-call-giving-me-a-null-when-mocking-callvoid,"['java', 'android', 'unit-testing']",265,False,0,1
Inserting a line of code in a method only when unit-testing,"<p>Hello i am unit testing a method which deals some <code>I/O</code> operations.I was wondering if there is some kind of way to pause that method for a specific time , <strong>at a specific line</strong> , without altering the original code.</p>

<p><strong>Original Method</strong></p>

<pre><code>public async Task&lt;int&gt; SomeMethodAsync()
{
    var x=DoSomething1();
    int value=await DoSomething2Async(); 
    return value;
}
</code></pre>

<p>Look at the method above.Is there any way from a <code>TestCase</code> to add a delay or a pause at a specific location in the target method?
I would like my method to become something like this <strong>Only when unit testing</strong> !:</p>

<p><strong>Desired method when unit testing</strong></p>

<pre><code>  public async Task&lt;int&gt; SomeMethodAsync()
    {
         var x=DoSomething1();   //line index=0
    #    await Task.Delay(delay) //delay set in the testcase
         int x=await DoSomething2Async();  //line index=1
         return x;  
    }
</code></pre>

<p><strong>Unit Test</strong></p>

<pre><code>[TestCase]
public void TestSomeMethodWithDelay()
{
    var delay=1000;
    int desiredLineIndex=1;
    int result=await SomeMethodAsync();
}
</code></pre>

<p>As you can see i would like when testing a method to insert some code before a target line , in my case an <code>await Task.Delay(interval)</code> where <code>interval</code> is set in the <code>TestCase</code>.
I do not want to modify/pollute the source code with preprocessor directives for testing.The only other way i could think is to use something like <code>System.Reflection.Emit</code> and rewrite the target method when testing.</p>

<p>Is there some other elegant way?</p>

<p><strong>P.S</strong> I just want , when running a particular set of tests to insert a delay between two <code>lines of code</code> without altering the original code.</p>

<p><strong>Update</strong>
The <code>SomeMethodAsync</code> is from another <code>dll</code>.The code must not be changed  ! The <code>DoSomething2Async</code> is an external call.</p>
",https://stackoverflow.com/questions/60548326/inserting-a-line-of-code-in-a-method-only-when-unit-testing,"['unit-testing', '.net-core', 'reflection', 'preprocessor', 'lines-of-code']",154,False,0,0
Unit testing S3 getObject with aws-sdk-mock issue on unit test,"<p>I am writing a unit test for S3 getObject. I used aws-sdk-mock, but when I run it I get an issue.</p>

<pre><code>Error: the object {
  ""error"": ""InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.""
  ""status"": false
} was thrown, throw an Error :)
</code></pre>

<p>Here is the Unit test which I am writing:</p>

<pre><code>const { expect } = require( 'chai' );
const utils = require( './s3Utils' );
const AWS = require( 'aws-sdk' );
const awsMock = require( 'aws-sdk-mock' );
const fs = require( 'fs' );

awsMock.setSDKInstance( AWS );


describe( 'S3 Utils', () =&gt; {
  before(() =&gt; {
    const rootPath = process.cwd();
    awsMock.mock( 'S3', 'getObject', Buffer.from( fs.readFileSync( `${ rootPath }/file.js` )));
  });

  after(() =&gt; {
    awsMock.restore( 'S3' );
  });

  it( 'Get the object from S3', async () =&gt; {
    const result = await utils.getFilesFromS3( '/somepath' );
    expect( result ).to.have.ownProperty( 'status' );
  });
});
</code></pre>

<p>Here is the function for which I am writing the unit test:</p>

<pre><code>const { s3Handler, BUCKET } = require( './../../config/s3Config' );

exports.getFilesFromS3 =
( bucketPath, fileName = 'index.js', bucketName = BUCKET ) =&gt; new Promise(( resolve, reject ) =&gt; {
  try {
    const params = { Key: `${ bucketPath }/${ fileName }`, Bucket: bucketName };
    s3Handler.getObject( params, ( error, data ) =&gt; {
      if ( error ) {
        reject({ status: false, error });
      } else {
        if (( data !== undefined || data !== null ) &amp;&amp; Object.prototype.hasOwnProperty.call( data, 'Body' )) {
          const contents = data.Body.toString( 'utf-8' );
          resolve({ status: true, contents });
        }
        reject({ status: false, error: `No body present ${ bucketPath }/${ fileName }` });
      }
    });
  } catch ( error ) {
    reject({ status: false, error });
  }
});
</code></pre>

<p>What am I missing here?</p>
",https://stackoverflow.com/questions/61230597/unit-testing-s3-getobject-with-aws-sdk-mock-issue-on-unit-test,"['node.js', 'unit-testing', 'amazon-s3', 'aws-sdk-mock']",4013,False,0,1
Unit testing of the updated component in react using jest and enzyme,"<p>I am trying to write the testing file for the following code.
with my present code</p>
<pre><code>import React from 'react';
import renderer from 'react-test-renderer';
// import { mount } from 'enzyme';
import LazyToastMessage from '../LazyToastMessage';
import IntlHelper from &quot;test/util/Mount&quot;;
import nls from &quot;src/nls/homepageHeader.json&quot;;

describe('the suspended toast message component renders correctly', () =&gt; {
    const mountWithNLS = new IntlHelper(nls);
    
    it('LazyToastMessage fallback', () =&gt; {
        const mockHandler = jest.fn();
        const wrapper = renderer.create(mountWithNLS.mountWithIntl(
        &lt;LazyToastMessage
        state
        message=&quot;test message&quot;
        iconType=&quot;success&quot;
        handleToasterStateChange={mockHandler}
        /&gt;)
        )
        expect(wrapper.toJSON()).toMatchSnapshot();
    })
});
</code></pre>
<p>The result of the snapshot is giving as <code>null</code>. How can I test the updated component and take its snapshot?</p>
<p>The Lazy component is the following:</p>
<pre><code>import React, {lazy, Suspense} from &quot;react&quot;;
import {IAppProps} from 'src/js/components/misc/ToastMessage'

const LazyToastMessage = lazy(() =&gt;
    import(/* webpackChunkName: &quot;toast-message&quot; */ &quot;./ToastMessage&quot;),
);

export default function(props: IAppProps) {
    return (
        &lt;Suspense fallback={null}&gt;
            &lt;LazyToastMessage {...props} /&gt;
        &lt;/Suspense&gt;
    );
}
</code></pre>
",https://stackoverflow.com/questions/62274719/unit-testing-of-the-updated-component-in-react-using-jest-and-enzyme,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",246,False,0,1
unit testing in web api with N tier without actual database calls,"<p>I am writing Unit Tests for My Web API application ,created with .net Core. I use MSTest with MOQ for mocking.</p>
<p>It has many layers as below.</p>
<p><strong>Controller =&gt; Manager classes =&gt; Facade classes =&gt; Contract class</strong></p>
<p>I am providing entity in controller that I have mocked.</p>
<pre><code>[TestMethod]
public void InvoiceUpdateFinanceTest_Success()
{
    var mock = mockFactory.OutstandingInvoicesDetailsMock();

    dataController.InvoiceUpdateFinance(mock);
    Assert.IsTrue(true);
}
</code></pre>
<p><strong>Contract Class</strong> is creating DB connection instance and does database calls</p>
<p>Code sample in Contract Layer is as below</p>
<pre><code>public class GradeWiseSlab : IMaintainContract
{
  

    IDbConnection _db = new DBModel().InstanceCreation();
    
    DynamicParameters dp = new DynamicParameters();
    public MaintainContractEntities MaintainContractEntities { get; set; }
    public void SaveData()
    {
        dp.Add(&quot;@N_VENDOR_ID&quot;, MaintainContractEntities.VendorId);
        dp.Add(&quot;@N_CONTRACT_SUB_TYPE_ID&quot;, MaintainContractEntities.SubContractType);
        dp.Add(&quot;@N_PAYMENT_TERM&quot;, MaintainContractEntities.PaymentTerm);
        dp.Add(&quot;@S_TRANSACTION_CURRENCY&quot;, MaintainContractEntities.TransactionCurrency);
        dp.Add(&quot;@S_DOC_NAME&quot;, MaintainContractEntities.DocNames);
        dp.Add(&quot;@S_APPROVAL_STATUS&quot;, MaintainContractEntities.ApproalStatus);
        dp.Add(&quot;@D_FROM_DATE&quot;, MaintainContractEntities.FromDate);
        dp.Add(&quot;@D_TO_DATE&quot;, MaintainContractEntities.ToDate);
        this._db.Query(Constant.SP_GRADE_WISE_SLAB, dp, commandTimeout: 0, commandType: CommandType.StoredProcedure);
}
</code></pre>
<p>How can I write test cases which shall cover all the layers i.e from controller to contract but no actual DB to touch?</p>
<p>I am not using Entity Framework, <strong>I am using Dapper library</strong>.</p>
",https://stackoverflow.com/questions/63191157/unit-testing-in-web-api-with-n-tier-without-actual-database-calls,"['unit-testing', 'asp.net-web-api', 'mstest', 'web-api-testing', 'vs-unit-testing-framework']",119,False,0,1
TypeError: undefined is not a function when unit-testing custom redux hook,"<p>I have a custom hook, that calls a saga function that in turn calls an axios api, when testing this function im getting</p>

<blockquote>
  <p>TypeError: undefined is not a function</p>
</blockquote>

<p>I just want to test if this function got called. </p>

<p><strong>postsHook.test.tsx</strong></p>

<pre><code>import { renderHook } from ""@testing-library/react-hooks"";
import usePostsHook from ""./postsHook"";
import { initCommentUpdates, getPostsInit } from ""../actions/postActions"";
import { getPosts } from ""../selectors/selectors"";
import { useSelector, useDispatch } from ""react-redux"";

describe(""usePostsHook hook"", () =&gt; {
    const [posts] = renderHook(() =&gt; usePostsHook());
    expect(posts).toHaveBeenCalledWith(1);
});
</code></pre>

<p><strong>postsHooks.tsx</strong></p>

<pre><code>import React from ""react"";
import { useDispatch, useSelector } from ""react-redux"";
import { initCommentUpdates, getPostsInit } from ""../actions/postActions"";
import { getPosts } from ""../selectors/selectors"";
function usePostsHooks() {
    const dispatch = useDispatch();
    const posts = useSelector(getPosts());
    React.useEffect(() =&gt; {
        dispatch(getPostsInit());
        console.log(""post hooks got called"");
        dispatch(initCommentUpdates());
    }, []);
    return [posts];
}

export default usePostsHooks;
</code></pre>
",https://stackoverflow.com/questions/61800737/typeerror-undefined-is-not-a-function-when-unit-testing-custom-redux-hook,"['reactjs', 'redux']",1730,True,0,1
bad request returned using postman but not in unit testing spring boot,"<p>I have a category entity with a unique field &quot;name&quot;.</p>
<p>I'm using a custom unique annotation to validate the data and it works perfectly.</p>
<p>I'm trying to test my controller on my spring boot application and i want to check if the the request returns a 400 status if the data is duplicated ( unique name ).</p>
<p>in postman it works as expected and returns the 400 status with the errors list.</p>
<p>with unit testing, it returns a 201 status with an empty body ( but in reality, returning a 201 means that the body contains the new created entity! )</p>
<p>this is my test:</p>
<pre class=""lang-java prettyprint-override""><code>    @Test
    public void testIfAdminCanCreateCategory_expect400BecauseCategoryAlreadyExist() throws Exception {
        // json
        String data = &quot;{\&quot;name\&quot; : \&quot;CATEGORY\&quot;}&quot;;
        mockMvc().with(keycloakAuthenticationToken().authorities(&quot;ROLE_admin&quot;)).perform(post(&quot;/categories&quot;).content(data).contentType(&quot;application/json&quot;))
                .andDo(print())
                .andDo(r -&gt; mockMvc().with(keycloakAuthenticationToken().authorities(&quot;ROLE_admin&quot;))
                        .perform(post(&quot;/categories&quot;).content(data).contentType(&quot;application/json&quot;))
                        .andExpect(status().isBadRequest()));
    }
</code></pre>
<p>my controller:</p>
<pre class=""lang-java prettyprint-override""><code>    @PostMapping
    @PreAuthorize(&quot;hasRole('ROLE_admin')&quot;)
    public HttpEntity&lt;MainCategory&gt; create(@Valid @RequestBody CreateMainCategory createMainCategory)
    {
        return ResponseEntity.status(HttpStatus.CREATED).body(mainCategoryService.create(createMainCategory));
    }
</code></pre>
<p>my service:</p>
<pre class=""lang-java prettyprint-override""><code>    @Override
    public MainCategory create(CreateMainCategory createMainCategory) {
        MainCategory mainCategory = new MainCategory();
        mainCategory.setName(createMainCategory.getName().toUpperCase());
        return mainCategoryRepository.save(mainCategory);
    }
</code></pre>
<p>my entity:</p>
<pre class=""lang-java prettyprint-override""><code>@Entity
@EntityListeners( AuditingEntityListener.class  )
@Data
public class MainCategory {

    @Id @GeneratedValue private Long id;

    private String name;

    @CreatedBy
    private String createdBy;

    @OneToMany(cascade = CascadeType.REMOVE, mappedBy = &quot;mainCategory&quot;)
    List&lt;Category&gt; categories;
}
</code></pre>
<p>the request from logs:</p>
<pre class=""lang-java prettyprint-override""><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /categories
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Content-Length:&quot;21&quot;]
             Body = {&quot;name&quot; : &quot;CATEGORY&quot;}
    Session Attrs = {SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@6989924: Authentication: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@6989924: Principal: user; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@40fd518f; Granted Authorities: ROLE_admin}
</code></pre>
<p>the response from logs:</p>
<pre class=""lang-java prettyprint-override""><code>MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = [Vary:&quot;Origin&quot;, &quot;Access-Control-Request-Method&quot;, &quot;Access-Control-Request-Headers&quot;, X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :400
Actual   :201
</code></pre>
",https://stackoverflow.com/questions/63428216/bad-request-returned-using-postman-but-not-in-unit-testing-spring-boot,"['spring-boot', 'unit-testing', 'spring-security', 'keycloak', 'spring-test']",654,True,-1,2
Failed lookup for key [user] in &lt;User: test&gt; exception when unit testing,"<p>I have an app that can <code>send/cancel/accept/delete</code> friend requests and I am trying to test it, however when I'm accepting a friend request and adding users to each others friends lists I am getting a <code>Failed lookup for key [user] in &lt;User: test&gt;</code> exception.</p>
<p>In my test I create a friend request object and send an accept <code>get</code> request to the view which should add each one of the users to each one of their friends lists and delete the <code>friend_request</code>.</p>
<p>Debugging shows that the error happens after this line in the view: <code>user1.friends.add(user2)</code>, so essentially <code>user2</code> is being added to <code>user1</code> friends list but adding <code>user1</code> to <code>user2</code> friends list throws the exception that was mentioned above.</p>
<p><strong>models.py</strong></p>
<pre><code>class User(AbstractBaseUser, PermissionsMixin):
    name = models.CharField('Full Name', max_length=35, unique=True, 
                                                        null=False, 
                                                        blank=False)
    friends = models.ManyToManyField(&quot;User&quot;, blank=True)

    def __str__(self):
        return self.name

class FriendRequest(models.Model)
    to_user = models.ForeignKey(User, related_name='to_user',
                                      on_delete=models.CASCADE)
    from_user = models.ForeignKey(User, related_name='from_user',
                                        on_delete=models.CASCADE)
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>from django.db import transaction

def accept_friend_request(request, pk):
    try:
        with transaction.atomic():
            from_user = User.objects.get(pk=pk)
            f_request = FriendRequest.objects.filter(
                from_user=from_user,
                to_user=request.user
            ).first()
            user1 = f_request.to_user
            user2 = from_user
            
            user1.friends.add(user2)
            print(user1.friends.all())
            
            user2.friends.add(user1)
            print(user2.friends.all())
            
            f_request.delete()
            return redirect(request.get_full_path())

    except Exception as ex:
        print(ex)
    return HttpResponse('User does not exist')
</code></pre>
<p>Here I am using the <code>transaction.atomic()</code> to prevent the exception from breaking the unittest transaction.</p>
<p><strong>tests.py</strong></p>
<pre><code>def setUp(self):
    self.client = Client()
    self.user = User.objects.create_user(email='test@gmail.com', 
                                         name='test', 
                                         password='test')
    self.user1 = User.objects.create_user(email='test1@gmail.com', 
                                          name='test1', 
                                          password='test1')
    self.client.force_login(self.user)

def test_accept_friend_request(self):
    friend_request = FriendRequest.objects.create(from_user=self.user1, 
                                                  to_user=self.user)
    self.client.get(reverse('accept_friend_request', 
                             kwargs={'pk': self.user1.pk}), follow=True)
    self.assertIn(self.user, self.user1.friends.all())
    self.assertIn(self.user1, self.user.friends.all())
</code></pre>
<p>Here is the result of running the test: (You can also see the result of the first print statement and the exception being printed)</p>
<pre><code>Ran 1 test in 1.266s

FAILED (failures=1)
Destroying test database for alias 'default'...
System check identified no issues (0 silenced).
&lt;QuerySet [&lt;User: test1&gt;]&gt;
Failed lookup for key [user] in &lt;User: test&gt;
</code></pre>
<p><strong>UPDATE</strong></p>
<p>changing Exception to IntegrityError resulted in the following error:</p>
<pre><code>raise VariableLookupError(django_elasticsearch_dsl.exceptions.VariableLookupError:
Failed lookup for key [user] in &lt;User: test&gt;
</code></pre>
<p>looks like elasticsearch-dsl has something to do with the exception here.</p>
<p><strong>UPDATE</strong></p>
<p>When debugging exception message changes to</p>
<pre><code>Failed lookup for key [name] in &lt;FriendRequest: FriendRequest object (1)&gt;
</code></pre>
",https://stackoverflow.com/questions/64767359/failed-lookup-for-key-user-in-user-test-exception-when-unit-testing,"['python', 'django', 'django-testing']",370,True,0,1
How to access objects of exported functions for unit testing using jest,"<p>How to access objects of exported functions for unit testing using jest(node JS) Basically I'm looking for a way to access objects of exported functions and test them
Please help</p>

<pre><code>//function.js
async function createTempUsageStatisticsTable(athenaExpress) {
let athenaQueryParam = {
    sql: getSqlQueries.CREATE_DEVICE_USAGE_STATS_TEMP_TABLE_QUERY,
    db: ""testdb""
};
try {
    await athenaExpress.query(athenaQueryParam);
}
catch (error) {
    console.error;
}
}
module.exports = {
  createTempUsageStatisticsTable: createTempUsageStatisticsTable
};

//function.test.js
const index = require('./function')
//require a test to check if sql has 
//getSqlQueries.CREATE_DEVICE_USAGE_STATS_TEMP_TABLE_QUERY

//require a 2nd test to check if db is testdb
</code></pre>
",https://stackoverflow.com/questions/59873601/how-to-access-objects-of-exported-functions-for-unit-testing-using-jest,"['javascript', 'node.js', 'jestjs']",260,True,0,1
How to return an array for unit testing with JUnit and Mockito?,"<p>I am testing an application that will stop unless it can split a <code>String</code> into a <code>String[]</code>. I am using JUnit and Mockito to test the application. I set up a default value and the mock behavior as follows.</p>

<p><code>
String[] exampleStringList = {""exampleElement"", ""exampleElement""};
when(example.Call()).thenReturn(exampleStringList);
</code></p>

<p>This creates the error <code>java: no suitable method found for thenReturn(java.Util.String[])</code>. I tried to resolve the issue by substituting <code>String[]</code> with <code>List&lt;String&gt;</code> and then adding the necessary elements. This created the same error as above. </p>

<p>TL;DR; I need to return a <code>String[]</code> with elements using JUnit for testing purposes but thenReturn is not compatible. How can I use JUnit and Mockito to return a <code>String[]</code> array to the test?</p>
",https://stackoverflow.com/questions/62071608/how-to-return-an-array-for-unit-testing-with-junit-and-mockito,"['java', 'junit', 'mockito']",1181,False,0,1
Angular unit testing with karma: Session Storage &quot;cannot read property of undefined&quot;,"<p>I have a service that stores basic user ""config"" info in session storage when the user logs in. I then call the service throughout the application to return the config when needed. </p>

<pre><code>export class ClientConfigService {
  response: LoginConfig = initialClientConfig;
  private configResponse = new BehaviorSubject(this.response);
  configData = this.configResponse.asObservable();

  constructor(private apiService: ApiService) { }

  setSessionStorage(data: LoginConfig) {
    sessionStorage.setItem('client', JSON.stringify(data));
    this.configResponse.next(data);
  }

  getClientConfig(clientId: string) {
    const clientSetup =  { startUrl: `${environment.apiUrl}/${clientId}` };

    return this.apiService.post(`yd-core/npb/start`, clientSetup).subscribe((data: LoginConfig) =&gt; {
      this.configResponse.next(data);
    });
  }

  getPageData() {
    const sessionConfig: LoginConfig = JSON.parse(sessionStorage.getItem('config'));

    return sessionConfig.client.config;
  }

  getClientId() {
    const sessionConfig: LoginConfig = JSON.parse(sessionStorage.getItem('config'));

    return sessionConfig.client.clientId;
  }

  getCurrentUser() {
    const sessionConfig: LoginConfig = JSON.parse(sessionStorage.getItem('config'));

    return sessionConfig.user;
  }
}
</code></pre>

<p>When I run ng test I get many instances of <code>TypeError: Cannot read property 'client' of null</code></p>

<p>I know I need to mock session storage.. which I'm attempting here with no effect</p>

<pre><code>import { TestBed } from '@angular/core/testing';

import { ClientConfigService } from './client-config.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { ApiService } from './api.service';
import { initialClientConfig } from '../models/user';

describe('ClientConfigService', () =&gt; {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  beforeEach(() =&gt; {
    window.sessionStorage.setItem('client', JSON.stringify({client : {} })); 
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterModule.forRoot([]),
      ],
      providers: [
        ApiService
      ]
    })
  .compileComponents();
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('should be created', () =&gt; {
    const service: ClientConfigService = TestBed.get(ClientConfigService);
    expect(service).toBeTruthy();
  });
});

</code></pre>
",https://stackoverflow.com/questions/61853933/angular-unit-testing-with-karma-session-storage-cannot-read-property-of-undefi,"['angular', 'unit-testing', 'karma-jasmine']",1479,True,0,3
How to reference to the project in WPF app for unit testing,"<p>I am using Win10, VS Community 2019, latest .NET Core WPF app. I have a very simple WPF app. I would like to test it's ViewModel. I kept MVVM model and keep view and ViewModel separated. Now I would like to unit test the ViewModel. But I can't refer to my project's ViewModel. I have a simple code for as follows:-</p>

<pre><code>namespace Multiples.ViewModel
{
class MultiplesViewModel
{
    public MultiplesViewModel()
    {

    }

    public long GetMultiples(long input)
    {
        long total = 0;
        for (long i = 1; i &lt; input; ++i)
        {
            if (i % 3 == 0 || i % 5 == 0)
            {
                total += i;
            }
        };
        return total;
    }
  }
 }
</code></pre>

<p>Later I add a reference to the unit test project. As you can see in the following pic. 
I can't reference MultiplesViewModel. </p>

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

<p>So how do I add to MultiplesViewModel for the unit testing? </p>
",https://stackoverflow.com/questions/61439451/how-to-reference-to-the-project-in-wpf-app-for-unit-testing,"['c#', 'wpf', '.net-core', 'xunit']",307,True,-1,1
Unit testing stored procedure and functions in .NET Core and SQL Server,"<p>Problem: how to unit test stored procedure and function?</p>

<p>I have seen different posts about it and still don't know what is the right way. </p>

<p>What I tried: I created a project in Visual Studio to upload the database schema (containing my stored procedure and related function). From there I create another project with a unit test. I unfortunately however find it trivial and a bit useless.</p>

<p>My stored procedure is not big deal but I would still like to know if there is a way to unit test it properly.</p>

<p>Stored procedure:</p>

<pre><code>CREATE PROCEDURE update_player 
    @Username   NVARCHAR (250),
    @Luck       INT,
    @DiceNumber INT
AS
    UPDATE [dbo].[Player]
    SET [Coins] = dbo.CalculatePlayerCoins(@Luck, @DiceNumber)
    WHERE [Username] = @Username 
 GO
</code></pre>

<p>My function:</p>

<pre><code>CREATE FUNCTION CalculatePlayerCoins 
    (@Luck INT, @DiceNumber INT)  
RETURNS INT
AS    
BEGIN  
    DECLARE @ret INT;

    SELECT 
        @ret = @Luck * @DiceNumber * (SELECT Value FROM getRandomValue)

    IF (@ret IS NULL)   
        SET @ret = 0;  

    RETURN @ret;  
END; 
</code></pre>

<p><code>getRandomValue</code> is a view that returns a random value.</p>

<p>I would like to use xUnit to test this if possible. Otherwise if you could point me to the right direction would be awesome. Thanks in advance!</p>
",https://stackoverflow.com/questions/61162777/unit-testing-stored-procedure-and-functions-in-net-core-and-sql-server,"['sql-server', 'function', 'unit-testing', 'stored-procedures']",904,True,0,1
unit testing in web api with N tier without actual database calls,"<p>I am writing Unit Tests for My Web API application ,created with .net Core. I use MSTest with MOQ for mocking.</p>
<p>It has many layers as below.</p>
<p><strong>Controller =&gt; Manager classes =&gt; Facade classes =&gt; Contract class</strong></p>
<p>I am providing entity in controller that I have mocked.</p>
<pre><code>[TestMethod]
public void InvoiceUpdateFinanceTest_Success()
{
    var mock = mockFactory.OutstandingInvoicesDetailsMock();

    dataController.InvoiceUpdateFinance(mock);
    Assert.IsTrue(true);
}
</code></pre>
<p><strong>Contract Class</strong> is creating DB connection instance and does database calls</p>
<p>Code sample in Contract Layer is as below</p>
<pre><code>public class GradeWiseSlab : IMaintainContract
{
  

    IDbConnection _db = new DBModel().InstanceCreation();
    
    DynamicParameters dp = new DynamicParameters();
    public MaintainContractEntities MaintainContractEntities { get; set; }
    public void SaveData()
    {
        dp.Add(&quot;@N_VENDOR_ID&quot;, MaintainContractEntities.VendorId);
        dp.Add(&quot;@N_CONTRACT_SUB_TYPE_ID&quot;, MaintainContractEntities.SubContractType);
        dp.Add(&quot;@N_PAYMENT_TERM&quot;, MaintainContractEntities.PaymentTerm);
        dp.Add(&quot;@S_TRANSACTION_CURRENCY&quot;, MaintainContractEntities.TransactionCurrency);
        dp.Add(&quot;@S_DOC_NAME&quot;, MaintainContractEntities.DocNames);
        dp.Add(&quot;@S_APPROVAL_STATUS&quot;, MaintainContractEntities.ApproalStatus);
        dp.Add(&quot;@D_FROM_DATE&quot;, MaintainContractEntities.FromDate);
        dp.Add(&quot;@D_TO_DATE&quot;, MaintainContractEntities.ToDate);
        this._db.Query(Constant.SP_GRADE_WISE_SLAB, dp, commandTimeout: 0, commandType: CommandType.StoredProcedure);
}
</code></pre>
<p>How can I write test cases which shall cover all the layers i.e from controller to contract but no actual DB to touch?</p>
<p>I am not using Entity Framework, <strong>I am using Dapper library</strong>.</p>
",https://stackoverflow.com/questions/63191157/unit-testing-in-web-api-with-n-tier-without-actual-database-calls,"['unit-testing', 'asp.net-web-api', 'mstest', 'web-api-testing', 'vs-unit-testing-framework']",119,False,0,1
TypeError: undefined is not a function when unit-testing custom redux hook,"<p>I have a custom hook, that calls a saga function that in turn calls an axios api, when testing this function im getting</p>

<blockquote>
  <p>TypeError: undefined is not a function</p>
</blockquote>

<p>I just want to test if this function got called. </p>

<p><strong>postsHook.test.tsx</strong></p>

<pre><code>import { renderHook } from ""@testing-library/react-hooks"";
import usePostsHook from ""./postsHook"";
import { initCommentUpdates, getPostsInit } from ""../actions/postActions"";
import { getPosts } from ""../selectors/selectors"";
import { useSelector, useDispatch } from ""react-redux"";

describe(""usePostsHook hook"", () =&gt; {
    const [posts] = renderHook(() =&gt; usePostsHook());
    expect(posts).toHaveBeenCalledWith(1);
});
</code></pre>

<p><strong>postsHooks.tsx</strong></p>

<pre><code>import React from ""react"";
import { useDispatch, useSelector } from ""react-redux"";
import { initCommentUpdates, getPostsInit } from ""../actions/postActions"";
import { getPosts } from ""../selectors/selectors"";
function usePostsHooks() {
    const dispatch = useDispatch();
    const posts = useSelector(getPosts());
    React.useEffect(() =&gt; {
        dispatch(getPostsInit());
        console.log(""post hooks got called"");
        dispatch(initCommentUpdates());
    }, []);
    return [posts];
}

export default usePostsHooks;
</code></pre>
",https://stackoverflow.com/questions/61800737/typeerror-undefined-is-not-a-function-when-unit-testing-custom-redux-hook,"['reactjs', 'redux']",1730,True,0,1
How can I ignore some JSON and object properties during unit testing?,"<p>I have a method that is migrating old JSON structure to a new one that I would like to test, but there is one randomly generated property (UUID) that I would like to ignore.</p>
<p>The interesting part of the object looks like this:</p>
<pre><code>val expected = FooterContainer(id = UUID.fromString(&quot;11914145-9775-4675-9c65-54bbd369fb2c&quot;), title = null, flowType=ContainerType.ROWS, elements=listOf() //the rest is not important.
</code></pre>
<p>The JSON to be converted looks totally different from this object, but this is the purpose of the method - to convert it to a new model.</p>
<pre><code>val json = &quot;&quot;&quot;[{&quot;type&quot;: &quot;list&quot;, &quot;items&quot;: [{&quot;link&quot;: &quot;www.something.com&quot;, &quot;type&quot;: &quot;link&quot;, &quot;label&quot;: &quot;Some label&quot;},
            {&quot;type&quot;: &quot;text&quot;, &quot;label&quot;: &quot;Another label&quot;}, {&quot;type&quot;: &quot;text&quot;, &quot;label&quot;: &quot;Other label&quot;},
            {&quot;type&quot;: &quot;text&quot;, &quot;label&quot;: &quot;yet another label&quot;}, {&quot;type&quot;: &quot;text&quot;, &quot;label&quot;: &quot;info@something.com&quot;}]
</code></pre>
<p>et cetera.</p>
<p>The below code worked as expected:</p>
<pre><code>val gson: JsonElement = Gson().fromJson(json, JsonElement::class.java)

    // when
    val converted = with(ClientDataRepository()) {
        gson.readFooter()
    }
</code></pre>
<p>until I had to introduce a new field in <code>FooterContainer</code> object, which was <code>val id: UUID</code></p>
<p>The method <code>readFooter()</code> is generating the <code>UUID</code> randomly, which is an expected behaviour.</p>
<p>But now, I cannot just assign a random (or hardcoded, as in the example code above) <code>UUID</code> to the expected class, which is logical - two randomly generated UUIDs will never be the same.</p>
<p>when I run the test, I obviously get:</p>
<pre><code>Expected :FooterContainer(id=11914145-9775-4675-9c65-54bbd369fb2c,
Actual   :FooterContainer(id=7ba39ad0-1412-4fda-a827-0241916f8558,
</code></pre>
<p>Now, is there a possibility to ignore the <code>id</code> field for this test? It is not important from the test perspective, but the rest is.</p>
",https://stackoverflow.com/questions/63372964/how-can-i-ignore-some-json-and-object-properties-during-unit-testing,"['java', 'json', 'unit-testing', 'kotlin', 'junit4']",2204,True,0,3
@quasar/extras/mdi-v4 jest unit testing failing on Unexpected token &#39;export&#39;,"<p>I am using the new SVG images. I have created a test for a header that contains a logo, name mdiMenu.</p>
<p>import { mdiMenu } from '@quasar/extras/mdi-v4'
But everything I am running the test: I always get this error:</p>
<pre><code>SyntaxError: Unexpected token 'export'

      29 | 
      30 | &lt;script&gt;
    &gt; 31 | import { mdiMenu } from '@quasar/extras/mdi-v4'
Do somebody else have encounter this problem and how can I solve this?

This is the rest of the error message:

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 &quot;node_modules&quot;.

    Here's what you can do:
     • To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
     • If you need a custom transformation specify a &quot;transform&quot; 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 &quot;moduleNameMapper&quot; config option.        

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    C:\Users\YohnCheung\work\bitBucket\central-station\node_modules\@quasar\extras\mdi-v4\index.js:3
    export const mdiAbTesting = 'M4 2A2 2 0 0 0 2 4V12H4V8H6V12H8V4A2 2 0 0 0 6 2H4M4 4H6V6H4M22 15.5V14A2 2 0 0 0 20 12H16V22H20A2 2 0 0 0 22 20V18.5A1.54 1.54 0 0 0 20.5 17A1.54 1.54 0 0 0 22 15.5M20 20H18V18H20V20M20 16H18V14H20M5.79 21.61L4.21 20.39L18.21 2.39L19.79 3.61Z'
    ^^^^^^
</code></pre>
<p>Question was taken from:</p>
<p><a href=""https://forum.quasar-framework.org/topic/5459/quasar-extras-mdi-v4-jest-unit-testing-failing"" rel=""nofollow noreferrer"">https://forum.quasar-framework.org/topic/5459/quasar-extras-mdi-v4-jest-unit-testing-failing</a>
<a href=""https://forum.vuejs.org/t/quasar-extras-mdi-v4-jest-unit-testing-failing/89973"" rel=""nofollow noreferrer"">https://forum.vuejs.org/t/quasar-extras-mdi-v4-jest-unit-testing-failing/89973</a></p>
",https://stackoverflow.com/questions/63481304/quasar-extras-mdi-v4-jest-unit-testing-failing-on-unexpected-token-export,"['jestjs', 'quasar']",178,False,0,1
"New to unit testing, would like some input on this unit test","<p>I'm fairly new to unit-testing and would like some input on good test implementations on some functions I have.</p>
<p>For methods that takes some input, and return an output, without knowing the expected return value, how would I properly test it? I have an example below...</p>
<pre><code>int add(int a, int b) {
     return a + b;
}

int actual = add(1,2);
int expect = 1 + 2; 

TEST_ASERT_EQUAL_INT(expect, actual);
</code></pre>
<p>Assuming I'm naive and does not know <code>1 + 2 = 3</code>. Would performing the same arithmetic as the function i'm testing to get the expected value consider good practice?</p>
",https://stackoverflow.com/questions/62902600/new-to-unit-testing-would-like-some-input-on-this-unit-test,['unit-testing'],151,True,0,1
Programmatically recreate H2 database schema in SpringBoot application (not while unit testing)?,"<p>I have a SpringBoot application with in memory H2 database and Spring Data JPA.
I need to configure a <code>@Scheduled</code> job that drops and recreates the schema and loads it with fresh data from a file.</p>
<p>How can I programmatically recreate the schema in my application?</p>
",https://stackoverflow.com/questions/63924926/programmatically-recreate-h2-database-schema-in-springboot-application-not-whil,"['spring-boot', 'h2']",359,False,0,1
Unit testing in python - Can we mock an SQL query result in python?,"<p>Summary : I have a method which i would like to test. This methods involves connecting the database,extracting the result (from sql query) and saving it into a data frame.</p>
<p><strong>I would like to know, is there a way I can mock the result retrieved from the SQL query?</strong></p>
<p>I tried unittest library, created a dataframe like the one received from the SQl query. But I am unable to figure out how can I pass this variable to the method while testing.</p>
<p>Please share your insights.
<a href=""https://i.stack.imgur.com/PKgmu.png"" rel=""noreferrer"">My method is something like :</a></p>
<pre><code>    try:
        db_connect = sqlite3.connect(&quot;address_zip.db&quot;)
        db_cur = db_connect.cursor()
        db_cur.execute(&quot;&quot;&quot; Select STD_ADDRESS,STD_CITY,STD_STATE from address&quot;&quot;&quot;)
        sql_result=pd.read_sql_query(&quot;&quot;&quot; Select STD_ADDRESS,STD_CITY,STD_STATE from address&quot;&quot;&quot;,db_connect)
        df = pd.DataFrame(sql_result, columns=['STD_ADDRESS', 'STD_CITY', 'STD_STATE'])
        print(f&quot;The data from database is :\n {df}&quot;)
        db_cur.close()
        db_connect.close()
    except Exception as e:
        print(f&quot;DB exception: {e}&quot;)

        return df
</code></pre>
<p>There are several actions done on the variable &quot;df&quot; in the original code, my agenda is to mock this object <strong>df</strong>.</p>
<p>But I am unable to understand how?
Sorry this may be very basic question, I am new to python.</p>
",https://stackoverflow.com/questions/62784168/unit-testing-in-python-can-we-mock-an-sql-query-result-in-python,"['python', 'unit-testing', 'python-unittest.mock']",6401,False,5,1
ASP.NET MVC unit testing WEB API Post method: Request.RequestUri throws an exception,"<p>I want to test Web api 2 post method, which looks like this:</p>
<pre><code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public IHttpActionResult CreateEquipment(EquipmentDto equipmentDto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest();
        }

        var equipment = Mapper.Map&lt;EquipmentDto, Equipment&gt;(equipmentDto);

        unitOfWork.Equipment.Add(equipment);
        unitOfWork.Complete();

        equipmentDto.Id = equipment.Id;

        return Created(new Uri(Request.RequestUri + &quot;/&quot; + equipment.Id), equipmentDto);
    }
</code></pre>
<p>I am using Moq and NUnit to test. My SetUp method and test method look like this:</p>
<pre><code>    [SetUp]
    public void SetUp()
    {
        unitOfWork = new Mock&lt;IUnitOfWork&gt;();
        controller = new EquipmentController(unitOfWork.Object);
        Mapper.Initialize(c =&gt; c.AddProfile&lt;MappingProfile&gt;());
    }

    [Test]
    public void CreateEquipment_ModelIsValid_ReturnCreated()
    {
        var equipmentDto = new EquipmentDto();
        var equipment = Mapper.Map&lt;EquipmentDto, Equipment&gt;(equipmentDto);
        unitOfWork.Setup(uow =&gt; uow.Equipment.Add(equipment));
        unitOfWork.Setup(uow =&gt; uow.Complete());

        var result = controller.CreateEquipment(equipmentDto) as CreatedAtRouteNegotiatedContentResult&lt;EquipmentDto&gt;;

        Assert.IsNotNull(result);
    }
</code></pre>
<p>I am getting NullReferenceException in the controller's line:</p>
<pre><code>  return Created(new Uri(Request.RequestUri + &quot;/&quot; + equipment.Id), equipmentDto);
</code></pre>
<p>equipment.Id and equipmentDto are not null. The null is Request, that's why Request.RequestUri throws an exception.</p>
<p>How to set up the Request properly to avoid the exception and pass the test? I would appreciate any help.</p>
<p>I know there is a similiar question: <a href=""https://stackoverflow.com/questions/58613899/asp-net-testing-api-controller-urirequest-getencodedurl-returns-null"">ASP.NET Testing Api controller: Uri(Request.GetEncodedUrl()...) returns null</a>
But that is related to ASP.NET Core and I coulnd't find out how to resolve the problem in ASP.NET MVC.</p>
<p>EDIT:
Also tried to add this in the test method:</p>
<pre><code>           var context = new Mock&lt;HttpContextBase&gt;();
        context.Setup(x =&gt; x.Request.Url).Returns(new Uri(&quot;/Equipment/New&quot;, UriKind.Relative));
</code></pre>
<p>But it didn't help.</p>
",https://stackoverflow.com/questions/64769640/asp-net-mvc-unit-testing-web-api-post-method-request-requesturi-throws-an-excep,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing']",366,True,0,1
Where we can put sample input datas for unit testing in angular,"<p>I am creating unit test for my angular application. I want to know <strong>the better place</strong> where we can store or configure datas like user name, password ..etc for unit testing. </p>

<pre><code>it('loging with existing account', (done) =&gt; {
    authService.login('sahalXXX@gmail.com', 'secretPass')
        .subscribe(res =&gt; {
            expect(res).toBeTruthy();
            done();
        },
            err =&gt; {
                expect(err).toBeFalsy();
                done();
            });
});
</code></pre>
",https://stackoverflow.com/questions/62427642/where-we-can-put-sample-input-datas-for-unit-testing-in-angular,"['angular', 'unit-testing', 'jasmine']",13,False,0,0
Angular Unit testing a method that does not have any return statement,"<p>My method :</p>
<pre class=""lang-js prettyprint-override""><code>flyout() {
    document.getElementById(&quot;transition1&quot;).style.cssText=&quot;transform:translateX(-120%)&quot;;
    document.getElementById(&quot;transition2&quot;).style.cssText=&quot;transform:translateY(-120%)&quot;;
}
</code></pre>
<p><strong>spec.ts :</strong></p>
<pre class=""lang-js prettyprint-override""><code>it('Tesing Void function', function() {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const component = fixture.debugElement.componentInstance;
    component.flyOut();
    // How should I write expect statement
});
</code></pre>
<p>Can anyone help me how to write expect statment....</p>
<p>Thanks.!!!</p>
",https://stackoverflow.com/questions/64421371/angular-unit-testing-a-method-that-does-not-have-any-return-statement,"['angular', 'angular-unit-test']",200,False,0,1
How do i mock a global variable for Unit Testing in Jasmine?,"<p>I'm trying to test a service in my Angular app but I don't understand how I can mock a variable declared outside my method.</p>

<p>My service looks like this:</p>

<pre><code>export class MyService {
    private token: string

    public myMethod(): Promise&lt;boolean&gt; {
        if(!this.token) // do Something
        else // do Something else
    }
}
</code></pre>

<p>What am I missing?</p>
",https://stackoverflow.com/questions/60463732/how-do-i-mock-a-global-variable-for-unit-testing-in-jasmine,"['javascript', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",1355,False,0,1
"ReactJs - Unit Testing Using Mocha , Upgrading to Babel 7 from Babel 6","<p>Did an upgrade from Babel v6 - v7 @latest today, And for some of the existing unit tests using Mocha and Enzyme (pretty standard) started crashing.
Getting this error in the console </p>

<pre><code>\node_modules\reselect\lib\index.js:53
    throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']'));  
</code></pre>

<p>Further digging into the pattern of tests which are failing - Could spot that the test where have referenced i.e imported component from an index lookup is failing, If provide actual path it starts working fine.</p>

<p>By Index look mean below - All our components are categorized and then imported/exported. We have been using this pattern from 3 years now</p>

<pre>
import ABC from './common/Folder/ABC';
.
.
.
import XYZ from './common/Folder/XYZ';

export {
ABC,
.
.
XYZ
}
</pre>

<p>The error happens when in Unit Test file we import like below</p>

<pre><code>1.import { ABC } from 'componentIndex';
</code></pre>

<p>If direct path is provided starts working</p>

<pre><code>2. import { ABC } from '../../ABC';
</code></pre>

<p>Please let me know if for any questions you might have in this context.</p>

<p>Any suggestion what I might be missing that is causing this error. Any babel plugin ? Thanks !</p>
",https://stackoverflow.com/questions/62098863/reactjs-unit-testing-using-mocha-upgrading-to-babel-7-from-babel-6,"['reactjs', 'babeljs', 'babel-loader']",41,False,0,1
Service Layer Unit testing with Sinon.js - Error &quot;x&quot; is not a constructor,"<p>I have followed the medium guide :
<a href=""https://medium.com/@tehvicke/integration-and-unit-testing-with-jest-in-nodejs-and-mongoose-bd41c61c9fbc"" rel=""nofollow noreferrer"">https://medium.com/@tehvicke/integration-and-unit-testing-with-jest-in-nodejs-and-mongoose-bd41c61c9fbc</a> trying to develop a test suite. My code is exactly like his but I am having the <strong>TypeError: Tournament is not a constructor</strong></p>

<p>I put some code, so you can see what I am trying to do.</p>

<p><strong>TournamentService.js</strong></p>

<pre><code>const createTournament = (Tournament) =&gt; (tournamentObj) =&gt; {
  const {name, creator} = tournamentObj;
  const newTournament = new Tournament({name, creator});
  return newTournament.save();
};
</code></pre>

<p><strong>TournamentService.test.js</strong></p>

<pre><code>const TournamentService = require(""../TournamentService"");
const sinon = require(""sinon"");

describe(""create Tournament test"", () =&gt; {
  it(""creates a tournament"", () =&gt; {
    const save = sinon.spy();
    console.log(""save "", save);
    let name;
    let creator;

    const MockTournamentModel = (tournamentObject) =&gt; {
      name = tournamentObject.name;
      creator = tournamentObject.creator;
      return {
        ...tournamentObject,
        save,
      };
    };

    const tournamentService = TournamentService(MockTournamentModel);
    const fintoElemento = {
      name: ""Test tournament"",
      creator: ""jest"",
    };

    tournamentService.createTournament(fintoElemento);
    const expected = true;
    const actual = save.calledOnce;

    expect(actual).toEqual(expected);
    expect(name).toEqual(""Test tournament"");
  });
});
</code></pre>
",https://stackoverflow.com/questions/61953371/service-layer-unit-testing-with-sinon-js-error-x-is-not-a-constructor,"['javascript', 'node.js', 'mongoose', 'jestjs', 'sinon']",233,True,0,1
Why is module not found only when doing unit testing with pytest?,"<p>I'm having a problem running unit tests. I have a project structure like this:</p>
<p>Given this directory</p>
<pre><code>who-said-what/
    |
    |_ wave_encoder.py
    | 
    |_ tests/
        |_ test_wave_encoder.py
</code></pre>
<p>where <code>test_wave_encoder.py</code> looks like this:</p>
<pre><code>from wave_encoder import *

class TestEncoder():
    def test_plot_no_fit1(self):
        encoder = WaveEncoder()
        self.assertRaises(ValueError, encoder.plot_signal)

    def test_plot_no_fit2(self):
        encoder = WaveEncoder()
        self.assertRaises(ValueError, encoder.plot_transform)

    def test_plot_no_fit3(self):
        encoder = WaveEncoder()
        self.assertRaises(ValueError, encoder.plot_components)

</code></pre>
<p>If I run this test file individually, no issues. However, if I try to run pytest from any directory in the project:</p>
<pre><code>pytest -v --cov ./tests 
# or
pytest -v --cov .
</code></pre>
<p>I get a <code>ModuleNotFoundError: No module named 'wave_encoder'</code>.</p>
<p>However, if I move <code>test_wave_encoder.py</code> to the parent directory, it does work (there are other errors, but that's a different question).</p>
<p>I don't really want a bunch of test files in the parent directory. How do I sort this out?</p>
",https://stackoverflow.com/questions/63273804/why-is-module-not-found-only-when-doing-unit-testing-with-pytest,"['python', 'unit-testing', 'pytest', 'pytest-cov']",388,True,0,1
how to refer to a function when unit testing with NodeJS / Mocha,"<p>I'm making my first test with Mocha.</p>

<p>Dummy test is passing, but when I want to refer to my actual function that is in another file, it won't find it:</p>

<pre><code>ReferenceError: main is not defined
</code></pre>

<p>I have a single index.js with :</p>

<pre><code>async function main() {
    function comparer(otherArray) {
        return function (current) {
            return otherArray.filter(function (other) {
                return other.prm === current.prm &amp;&amp; other.conso_prod === current.conso_prod
            }).length === 0;
        }
    }
}

module.exports = main();
</code></pre>

<p>and in my test.js file, I do:</p>

<pre><code>const {expect} = require('chai');

describe('Sum numbers', () =&gt; {
    it('Compare 2 existing array', () =&gt; {
        const meters = []
        const perimeter = []
        const onlyInMeters = meters.filter(main.comparer(perimeter));
        expect(onlyInMeters).to.equal([]);
    });
});
</code></pre>

<p>But when I refer to <code>main.comparer</code>, it can't find it:</p>

<pre><code>ReferenceError: main is not defined
</code></pre>

<p>What am I forgetting? Sorry, I'm a NodeJS Noob!</p>
",https://stackoverflow.com/questions/62466966/how-to-refer-to-a-function-when-unit-testing-with-nodejs-mocha,"['node.js', 'mocha.js']",48,True,0,1
Unit testing ASP.NET Core 3.1 MVC controller - value cannot be null. (Parameter &#39;provider&#39;),"<p>I've recently started working with .NET Core 3.1 after coming from a .NET background and just trying to get up to speed with Unit Testing an MVC controller in the new framework.</p>
<p>In .NET creating an MVC website used to give the option of adding a Unit Test project whereas Core doesn't; so I have followed some guides and have put this simple test together in MSTest for the <code>HomeController</code> index view.</p>
<p>HomeController.cs:</p>
<pre><code>public class HomeController : Controller
{
    public IActionResult Index()
    {
        return this.View();
    }
}
</code></pre>
<p>HomeControllerTests.cs:</p>
<pre><code>[TestMethod]
public void WhenIndexIsExecutedAsyncThenContentShouldBeReturned()
{
    // arrange
    var httpContext = new DefaultHttpContext();
    var controller = new HomeController()
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = httpContext
            }
        };

    var actionContext = new ActionContext
        {
            HttpContext = httpContext
        };

    // act
    var result = controller.Index().ExecuteResultAsync(actionContext);

    // assert
    Assert.IsNotNull(result);
    Assert.IsNull(result.Exception);
}
</code></pre>
<p>I get an error:</p>
<blockquote>
<p>Value cannot be null. (Parameter 'provider')</p>
</blockquote>
<p>And I do not know what is causing the error.</p>
",https://stackoverflow.com/questions/65339974/unit-testing-asp-net-core-3-1-mvc-controller-value-cannot-be-null-parameter,"['c#', 'asp.net-mvc', 'asp.net-core', 'mstest']",931,True,2,1
How to eliminate @Configuration classes with security enabled in Spring Boot unit testing,"<p>I am on a new microservice which is working fine and all the test cases were also working fine. Recently, the Spring Boot microservice is enabled with spring security with sso. Microservice is working fine but test cases are getting failed because of security. I have a class which needs to eliminated at run time during spring boot unit test. I provide below the code.</p>
<pre><code>@Configuration
@Slf4j
public class CloudSecurityConfig {
    private String host = &quot;some host&quot;;
    private String port = System.getenv(&quot;redis.port&quot;);
    private String password = System.getenv(&quot;redis.password&quot;);
    private String ssl = System.getenv(&quot;redis.ssl&quot;);
    
    @Bean
    JedisPoolConfig jedisPoolConfig(@Value(&quot;${redis.pool.maxactive}&quot;) int maxActive,
            @Value(&quot;${redis.pool.maxidle}&quot;) int maxIdle, @Value(&quot;${redis.pool.minidle}&quot;) int minIdle) {
        .... Other code
        return jedisPoolConfig;
    }
    
    @Bean
    JedisConnectionFactory jedisConnectionFactory() throws Exception {
            .... Other code
        
        return jedisConFactory;
    }

    @Bean
    @Primary
    public RedisTemplate&lt;String, CtmUser&gt; redisTemplate() throws Exception {
        .... Other code
        return redisTemplate;
    }
}
</code></pre>
<p>I have also tried with this link <a href=""https://stackoverflow.com/questions/39729752/java-spring-boot-test-how-to-exclude-java-configuration-class-from-test-context"">Java Spring Boot Test: How to exclude java configuration class from test context</a>. But it is not working. I get the following error details.</p>
<pre><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate&lt;?, ?&gt;' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1717) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1273) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
    ... 84 common frames omitted
</code></pre>
<p>The above is coming from the class <code>CloudSecurityConfig</code>. I think, if I am able to remove this configuration, everything will work fine.</p>
<p>The above error is followed by the below error:</p>
<pre><code>Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customAuthenticationProvider': Unsatisfied dependency expressed through field 'template'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate&lt;?, ?&gt;' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>
<p>I have tried with the following options.</p>
<pre><code>//@EnableMongoRepositories
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration()
@SpringBootTest(classes = { ValidationApplication.class, TestMongoConfiguration.class })
//@ImportAutoConfiguration(classes = {ValidationApplication.class,TestMongoConfiguration.class})
//@EnableAutoConfiguration(exclude={ DataSourceAutoConfiguration.class, RedisAutoConfiguration.class,
//        RedisRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class })

//@EnableAutoConfiguration(exclude={ DataSourceAutoConfiguration.class, RedisAutoConfiguration.class,
//      RedisRepositoriesAutoConfiguration.class, MongoAutoConfiguration.class, SecurityAutoConfiguration.class })

//@EnableAutoConfiguration(exclude={ CloudSecurityConfig.class })

//@TestPropertySource(inheritProperties = false, properties = 
//        &quot;spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration&quot;)
//@TestConfiguration()
//@ConditionalOnProperty(name = &quot;test&quot;, havingValue=&quot;test&quot;)
@ActiveProfiles(&quot;test&quot;)
@ComponentScan(basePackages = {&quot;com.a.b.c.d&quot;}
, excludeFilters = {
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {SecurityCloudConfig.class})})
public class CheckTest {

    @Autowired
    private MyController controller;
    
    @Test
    void testAllBeforeEntry() {
        ResponseEntity&lt;?&gt; re = controller.getValdiations();
        boolean flag = re.getStatusCode().is2xxSuccessful();
        assertEquals(true, flag);
    }

}
</code></pre>
",https://stackoverflow.com/questions/64957520/how-to-eliminate-configuration-classes-with-security-enabled-in-spring-boot-uni,"['java', 'spring', 'spring-boot', 'junit4']",273,False,2,1
"While Unit Testing a .Net core 3.1 Background Service, unable to resolve IConfiguration","<p>I'm trying to write unit test case for the BackgroundService <code>Worker.cs</code>. I have read <a href=""https://stackoverflow.com/questions/51224146/integration-test-for-hosted-service-net-core"">Stack Overflow Question</a></p>

<p>But still I get the error that </p>

<blockquote>
  <p>""Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'AutoClueArchiver.Worker'.</p>
</blockquote>

<pre><code>public WorkerTests()
{
    _config = new ConfigurationBuilder()
            .AddJsonFile(""appsettings.json"", true, true)
            .AddJsonFile(""appsettings.Development.json"", true, true)
            .AddJsonFile(""appsettings.local.json"", true, true)
            .AddJsonFile(""\\\\charon.cmiprog.com\\devinet\\Configuration\\"" + ""ApiEndpoints.json"", false, true)
            .AddJsonFile(""ApiEndpoints.local.json"", true, true)
            .AddJsonFile(""\\\\charon.cmiprog.com\\devinet\\Configuration\\"" + ""Kafka.json"", false, true)
            .AddEnvironmentVariables().Build();
         _mockedKafkaTopicConsumerManager =new Mock&lt;IKafkaTopicConsumerManager&gt;();
         _mockedMessageProcessor=new Mock&lt;IMessageProcessingCapable&gt;();
}

[Fact]
public async Task ExecuteAsync_Test()
{            
     IServiceCollection services=new ServiceCollection();
     services.AddSingleton&lt;IConfigEntriesClientService, ConfigEntriesClientServiceInjectable&gt;();
     services.AddSingleton(typeof(IProducer), s =&gt; new KafkaProducer(s.GetRequiredService&lt;IProducer&lt;string, string&gt;&gt;(), s.GetRequiredService&lt;IConfiguration&gt;().GetValue&lt;string&gt;(""Shared:Kafka:TopicSuffix"")));
     services.AddSingleton(typeof(IProducer&lt;string, string&gt;), c =&gt; new ProducerBuilder&lt;string, string&gt;(KafkaConfigs(c)).Build());
     services.AddHttpClient();
     services.AddScoped&lt;IPolicyApiClient, PolicyApiClient&gt;();
     services.AddTransient&lt;IFilterMessages, MessageFilter&gt;();
     services.AddTransient&lt;IArchiveAutoClues, Archiver&gt;();
     services.AddTransient&lt;IFileSystem, FileSystem&gt;();
     services.AddTransient&lt;ISaveDocument, DocumentManager&gt;();
     services.AddTransient&lt;IKafkaTopicConsumerManager, KafkaTopicConsumerManager&gt;();
     services.AddTransient&lt;IMessageProcessingCapable, ConsumerInitializer&gt;();
     services.AddTransient&lt;Consumer&gt;();
     services.AddTransient&lt;IExceptionPublisher, ExceptionPublisher&gt;();
     services.AddTransient&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
     services.AddScoped(sp =&gt; new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
     services.AddHttpClient&lt;IBaseApiClient, BaseApiClient&gt;().ConfigurePrimaryHttpMessageHandler(
     sp =&gt; new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }
            );

     var worker=services.AddHostedService&lt;Worker&gt;();
     var serviceProvider=services.BuildServiceProvider();
     var backgroundService = serviceProvider.GetService&lt;IHostedService&gt;() as Worker;
     await backgroundService?.StartAsync(CancellationToken.None);
     await Task.Delay(1000);
     await backgroundService?.StopAsync(CancellationToken.None);
     //await backgroundService.ExecuteAsync(new CancellationToken()); 
     //Any way to access ExecuteAsync here since I get protection level error as 
     //ExecuteAsync is protected
     _mockedKafkaTopicConsumerManager.Verify(c=&gt;c.StartConsumption
     (It.IsAny&lt;CancellationToken&gt;(), 
     _mockedMessageProcessor.Object,
                It.IsAny&lt;string&gt;(),
                It.IsAny&lt;string&gt;(),
                It.IsAny&lt;List&lt;string&gt;&gt;(),
                It.IsAny&lt;string&gt;(),
                It.IsAny&lt;int&gt;()),Times.Once);
}
</code></pre>
",https://stackoverflow.com/questions/60387013/while-unit-testing-a-net-core-3-1-background-service-unable-to-resolve-iconfig,"['c#', 'unit-testing', '.net-core', 'background-service']",3601,True,2,2
TypeError: Cannot read property &#39;apply&#39; of undefined in NodeJS using JEST unit testing,"<p>I am new to jest unit testing as well as NodeJS and i'm trying to test my API using the following code.</p>

<pre><code>const request = require('supertest');
const quick_registration = require('../../../routes/register/quick_registration_of_user')

describe('Quick Registration of users', () =&gt; {
    beforeAll(() =&gt; {
        con.connect();
    });

    describe(""GET / "", () =&gt; {
        test(""It should respond with an array of students"", async () =&gt; {
          const response = await request(quick_registration).get(""/api/quickregistration"");
          expect(response.status).toBe(200);
        });
      });
})
</code></pre>

<p>But the test keep failing and throws me an error</p>

<pre><code> FAIL  tests/routes/register/quick_registration_of_user.test.js
  Quick Registration of users
    GET /
      × It should respond with an array of students (20ms)

  ● Quick Registration of users › GET /  › It should respond with an array of students

    TypeError: Cannot read property 'apply' of undefined

      at node_modules/express/lib/router/index.js:635:15
      at next (node_modules/express/lib/router/index.js:260:14)
      at Function.handle (node_modules/express/lib/router/index.js:174:3)
      at Server.router (node_modules/express/lib/router/index.js:47:12)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.649s, estimated 2s
Ran all test suites.
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>
",https://stackoverflow.com/questions/60011710/typeerror-cannot-read-property-apply-of-undefined-in-nodejs-using-jest-unit-t,"['node.js', 'api', 'unit-testing', 'jestjs']",1447,True,2,1
Unit testing Controller Action when Response property is assigned inside of an action,"<p>I saw the very same issue in this <a href=""https://stackoverflow.com/questions/35319501/how-to-unit-test-a-controller-action-using-the-response-property-in-asp-net-5-m"">post</a> but none of the solutions works now in ASP.Net Core 2.2. When I debug the unit test the Response property is still null and thus the test fails. 
I have been reading the asp.net core docs for an answer how to mock the <code>ControllerContext</code> so that the Response property has a value but I couldn't find anything working.</p>

<p>Here is the line inside the action that makes troubles:</p>

<pre><code>Response.Headers.Add(""Access-Control-Expose-Headers"", ""Content-Range"");
</code></pre>

<p>So what I have ended up with in the unit test set up is:</p>

<pre><code>        var routeData = new RouteData();
        routeData.Values.Add(""controller"", ""Home"");

        var headerDictionary = new HeaderDictionary();
        var response = new Mock&lt;HttpResponse&gt;();
        response.SetupGet(r =&gt; r.Headers).Returns(headerDictionary);

        var httpContext = new Mock&lt;HttpContext&gt;();
        httpContext.SetupGet(a =&gt; a.Response).Returns(response.Object);

        var actionContext = new ActionContext(
            httpContext.Object,
            routeData, 
            new ControllerActionDescriptor());

        _controller.ControllerContext = new ControllerContext(actionContext);
</code></pre>
",https://stackoverflow.com/questions/60464043/unit-testing-controller-action-when-response-property-is-assigned-inside-of-an-a,"['c#', 'unit-testing', 'asp.net-core', 'asp.net-web-api', 'asp.net-core-2.2']",796,True,2,2
How to do UnitOfWork + Repository patterns with entity framework core and unit testing,"<p>I'm running into an issue while unit testing where if I run multiple tests at once, the <code>DbContext</code> will lose track of records I've added during unit tests and I think this may have to do with how services are registered in my <code>ServiceCollection</code>.</p>
<p>I have the following setup:</p>
<p>IUnitOfWork:</p>
<pre><code>    public interface IUnitOfWork : IDisposable
    {
        IUserRepository Users { get; }

        int Complete();
    }
</code></pre>
<p>UnitOfWork</p>
<pre><code>    public class UnitOfWork : IUnitOfWork
    {
        private readonly MyDbContext _context;

        public IUserRepository Users { get; }

        public UnitOfWork(MyDbContext context,
                          IUserRepository userRepository)
        {
            _context = context;

            Users = userRepository;
        }

        public void Dispose() =&gt; _context.Dispose();

        public int Complete() =&gt; _context.SaveChanges();
    }
</code></pre>
<p>UserRepository</p>
<pre><code>    public class UserRepository : Repository&lt;User&gt;, IUserRepository
    {
        public UserRepository(MyDbContext context) : base(context) { }

        public MyDbContext MyDbContext =&gt; Context as MyDbContext;

        public Task&lt;User?&gt; GetUserDetailsAsync(int userID)
        {
            var user = MyDbContext.Users.Where(user =&gt; user.Id == userID)
                                                  .Include(user =&gt; user.Emails)
                                                  .Include(user =&gt; user.PhoneNumbers).FirstOrDefault();

            return Task.FromResult(user);
        }
    }
</code></pre>
<p>Here is my base test:</p>
<pre><code>    public abstract class BaseTest : IDisposable
    {
        protected ServiceProvider ServiceProvider { get; }

        private MyDbContext MyDbContext { get; }

        protected IUnitOfWork UnitOfWork { get; }

        public BaseTest()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddScoped&lt;IUserService, UserService&gt;()
                             .AddScoped&lt;IUnitOfWork, UnitOfWork&gt;()
                             .AddScoped(typeof(IRepository&lt;&gt;), typeof(Repository&lt;&gt;))
                             .AddScoped&lt;IOrganizationRepository, OrganizationRepository&gt;()
                             .AddScoped&lt;IExercisePostRepository, ExercisePostRepository&gt;()
                             .AddScoped&lt;IUserRepository, UserRepository&gt;()
                             .AddTransient&lt;IRestClient, RestClient&gt;()
                             .AddAutoMapper(typeof(Startup).Assembly)
                             .AddDbContext&lt;MyDbContext&gt;(options =&gt;
                                                                  options.UseInMemoryDatabase(&quot;Core&quot;)
                                                                         .EnableSensitiveDataLogging());
            ServiceProvider = serviceCollection.BuildServiceProvider();
            SpotcheckrCoreContext = ServiceProvider.GetRequiredService&lt;MyDbContext&gt;();
            MyDbContext.Database.EnsureCreated();
            UnitOfWork = ServiceProvider.GetRequiredService&lt;IUnitOfWork&gt;();
        }

        public void Dispose()
        {
            MyDbContext.Database.EnsureDeleted();
            UnitOfWork.Dispose();
        }
    }
</code></pre>
<p>Sample test:</p>
<pre><code>    public class UserServiceTests : BaseTest
    {
        private readonly IUnitOfWork UnitOfWork;

        private readonly IUserService Service;

        public UserServiceTests()
        {
            UnitOfWork = ServiceProvider.GetRequiredService&lt;IUnitOfWork&gt;();
            Service = ServiceProvider.GetRequiredService&lt;IUserService&gt;();
        }

        [Fact]
        public async void GetUserAsync_WithValidUser_ReturnsUser()
        {
            var user = new User
            {
                FirstName = &quot;John&quot;,
                LastName = &quot;Doe&quot;
            };
            UnitOfWork.Users.Add(user);
            UnitOfWork.Complete();

            var result = await Service.GetUserAsync(user.Id);
            Assert.Equal(user.Id, result.Id);
        }
}
</code></pre>
<p>If I run this test by itself, then it will correctly pass and I can see the user in the repository. However if I run it with other tests and debug, then that user is lost once I inspect UnitOfWork.Users in the repository but I do see it in the UnitOfWork.Users in the test.</p>
<p>What is the correct approach here?</p>
<p>Edit 1:
Tried some other changes but no luck yet. Adjusted <code>UnitOfWork</code> to take in the interfaces of each repository and registering them in <code>BaseTest</code> as scoped services. Also tried marking <code>BaseTest</code> as implementing <code>IDisposable</code> and then executing:</p>
<pre><code>        public void Dispose()
        {
            MyDbContext.Database.EnsureDeleted();
            UnitOfWork.Dispose();
        }
</code></pre>
<p>In the service layer I'll see the Users just fine but as soon as I step into the repository layer I'll lose the Users :/ I have a suspicion it is related to dependency injection <code>AddScoped</code> vs <code>AddTransient</code> and how all of that works with running multiple unit tests.</p>
<p>Edit 2:
Tried some more things...Used <code>IClassFixture&lt;BaseTest&gt;</code> on each test class and then ensured that each test class implemented <code>IDisposable</code> and in there I would ensure the Context database was deleted; also ensured in the test class constructor that it was created. With this I ended up with the following error:</p>
<p><code>The instance of entity type cannot be tracked because another instance with the same key value for {'Id'} is already being tracked</code></p>
<p>And so I added <code>.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)</code> but the problem still persisted.</p>
<p>This is very annoying to setup.</p>
",https://stackoverflow.com/questions/65431800/how-to-do-unitofwork-repository-patterns-with-entity-framework-core-and-unit-t,"['.net-core', 'entity-framework-core', 'xunit']",129,True,1,1
Unit testing in Typescript with Dependency Injection using Inversify with mocha and chai,"<p>I created typescript project using inversify and unit tests using mocha and chai. </p>

<pre><code>@injectable()
export class SomeClass{

// Used in Constructor injection
readonly object1:TypeObjectClass; 

// Property Injection 
(@inject(TYPE2)
readonly someObject1:TypeSomeObjectClass1; 

constructor(@inject(TYPE) object1: TypeObjectClass) {

this.object1=object1

}

public someMethod(){

this.object1.DoSomething();
this.someObject1.DoAnything();

}
}
</code></pre>

<p>I wrote a unit test for the above class</p>

<p>Unit Test</p>

<pre><code>let chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
let expect = chai.expect;

describe('Test Interaction Controller APIs', () =&gt; {

 let object1: IMock&lt;TypeObjectClass&gt;;
 let someObject: IMock&lt;TypeSomeObjectClass1&gt;;
let someClass: SomeClass;

beforeEach(()=&gt;{
//Mock objects
 object1= Mock.ofType&lt;object1&gt;();
 someObject= Mock.ofType&lt;TypeSomeObjectClass1&gt;();
// Constructor injected. 
SomeClass=new SomeClass(object1.object)

})

}

</code></pre>

<p>How do I inject <code>someObject1</code> in my unit test since this is property injection? </p>
",https://stackoverflow.com/questions/61519759/unit-testing-in-typescript-with-dependency-injection-using-inversify-with-mocha,"['typescript', 'mocha.js', 'chai', 'inversifyjs']",3229,True,1,1
How to unit testing the filter result of a graphql query in Gatsby?,"<p>I'm working on a website built with Gatsby. To consume the data (coming from an airTable table), I've created a custom hook (useData) that performs a GraphQL query, using useStaticQuery. I need to filter this data according to their status (those that have Status = &quot;open&quot;); so, I've created a filter in the query for it, like this:</p>
<pre><code>    useStaticQuery(graphql`
    query {
      allAirtable(
        filter: { table: { eq: &quot;Positions&quot; }, data: { Title: { ne: null }, Status: { eq: &quot;open&quot; } } }
      ) {
        nodes {
          data {
            Title
            Location
            Status
            ID
          }
        }
      }
    }
  `);
</code></pre>
<p>The hook useData, looks like this:</p>
<pre><code>import { useStaticQuery, graphql } from 'gatsby';
import { useTranslateNodes } from './useTranslateNodes';

export default function useData() {
  const queryData = useStaticQuery(graphql`
    query {
      allAirtable(
        filter: { table: { eq: &quot;Positions&quot; }, data: { Title: { ne: null }, Status: { eq: &quot;open&quot; } } }
      ) {
        nodes {
          data {
            Title
            Location
            Status
            ID
          }
        }
      }
    }
  `);
  const {
    allAirtable: { nodes },
  } = queryData;

  const positions = useTranslateNodes({ nodes, table: 'Positions' });

  return { positions };
}
</code></pre>
<p><em>(The useTranslateNodes hook, maps the array from the query and returns a better structured array. This is not really important for the issue)</em></p>
<p>The problem is when I test the query result (I want to be sure that the hook is doing it's job, and is returning the positions with Status = &quot;open&quot;), because according to the <a href=""https://www.gatsbyjs.com/docs/testing-components-with-graphql/"" rel=""nofollow noreferrer"">Gatsby docs</a>, I have to mock the data from the query, but that's not the real data! And it makes no sense to me... I also try using the <a href=""https://www.gatsbyjs.com/plugins/gatsby-plugin-testing/"" rel=""nofollow noreferrer"">gatsby-plugin-testing</a>, to get the real data from the query, but in the end, still taking the mock data (because without it, it doesn't work).</p>
<p>My question is: How can I do a unit test for the filter of the query? I mean, I wanna test that the filter is doing its job!</p>
<p>I hope I have provided the necessary information to resolve this issue. I've been reading related issues here, but still without a concrete solution. I'm a testing newbie and I'm a bit confused about it, so thanks for the help you can provide!</p>
",https://stackoverflow.com/questions/64838885/how-to-unit-testing-the-filter-result-of-a-graphql-query-in-gatsby,"['javascript', 'unit-testing', 'jestjs', 'graphql', 'gatsby']",87,False,1,0
How to change the value of a python function variable for unit testing,"<p>Given the following hypothetical code, how can I change the value of the variables <code>discount</code> and <code>is_active</code> so I can test the function <code>price_discount</code> for different expected return values?</p>

<p><code>discounts.py</code></p>

<pre><code>import active_member

#returns a 20% discount value for active members 
def price_discount(price, membership_id):
    discount = 0.2
    is_active = active_member(membership_id)
    if is_active:
        price_discount = price * discount
    else:
        price_discount = 0

    return price_discount
</code></pre>

<p><code>test_discounts.py</code></p>

<pre><code>import discounts

def test_price_discount():
    test = discounts.price_discount(50.00, 'D01910')
    assert test == some_expected_value
</code></pre>
",https://stackoverflow.com/questions/61063521/how-to-change-the-value-of-a-python-function-variable-for-unit-testing,"['python', 'unit-testing']",1267,False,1,1
Unit Testing UseState when its Setter function is passed to a Child Component,"<p>Below I have a an example of UseState hook where its setter function (<strong>setInputs</strong>) is passed down to a child component (<strong>LoginForm</strong>).</p>
<p>I am having trouble with Unit Testing where I cannot simulate a change to <code>setInputs</code> and thereby cannot assert that the dispatch is called.</p>
<p>How can I simulate a change to the <code>setInputs</code> prop in order to update the <code>inputs</code> state in my Test?</p>
<p><strong>Component:</strong></p>
<pre><code>const Login = () =&gt; {
  const [inputs, setInputs] = useState({ email: '' });

  const handleSubmit = event =&gt; {
    event.preventDefault();

    if (!inputs.email) {
      return;
    }
    // Cannot Assert this
    dispatch(requestAuthentication(inputs.email));
  };

  return (
    &lt;LoginForm
      setInputs={setInputs}
      handleSubmit={handleSubmit}
    /&gt;
  );
};

export default Login;
</code></pre>
<p>**Login Form **</p>
<p>Is a basic form than onChange of an input calls the following function</p>
<pre><code>const handleInputChange = event =&gt; {
    event.persist();

    props.setInputs(input =&gt; ({
      ...input,
      [event.target.name]: event.target.value,
    }));
  };
</code></pre>
<p><strong>Unit Test:</strong></p>
<pre><code>it('should return if no email is entered', () =&gt; {
    useDispatch.mockImplementation(() =&gt; jest.fn());
    useSelector.mockImplementation(() =&gt; jest.fn());

    requestAuthentication.mockImplementation((data, callback) =&gt; {
      callback();
    });

    const wrapper = shallow(
      &lt;Login&gt;
        &lt;LoginForm {...props} /&gt;
      &lt;/Login&gt;
    );

    wrapper
      .find('LoginForm')
      .props()
      .handleSubmit({
        preventDefault: () =&gt; {},
      });
    expect(requestAuthentication).not.toHaveBeenCalled();
  });
</code></pre>
",https://stackoverflow.com/questions/65135555/unit-testing-usestate-when-its-setter-function-is-passed-to-a-child-component,"['javascript', 'jestjs', 'use-state']",376,False,1,0
"When unit testing (with Mockito), should I &quot;implement&quot; the internal logic when mocking?","<p>Edit:
Sorry, my example is not very proper, I changed it a little.</p>

<p>I'm not sure if the title shows my question properly.<br>
For example, I have functions:</p>

<pre><code>class Dependency {
    // create an element with id and data, add it into a list and return the element
    public Element addElement(int id, data d) throws SomeException;

    // remove an element from the list and return it
    public Element removeElement(int id) throws SomeException;
}
</code></pre>

<p>Then I can mock it like:</p>

<pre><code>private Element mockElement(int id, data dt) {
    Element e = mock(Element.class);
    when(e.getId()).thenReturn(id);
    when(e.getData()).thenReturn(dt);
    return e;
}

private Dependency mockDependency() {
    List l = new List();
    Dependency dependency = mock(Dependency.class);    

    // should I ""implement"" the internal logic when mocking?
    when(dependency.addElement(intCaptor.capture(), dataCapture.capture())).thenAnswer(a-&gt;{
        int id = intCaptor.getValue();
        data dt = dataCaptor.getValue();
        if (id &lt; 0) { throw someException; }
        Element e = mockElement(id, dt);
        l.add(e);
        return e;
    };

    when(dependency.removeElement(intCaptor.capture())).thenAnswer(a-&gt;{
        int id = intCaptor.getValue();
        if (id &lt; 0) { throw someException; }
        Element e = l.findElementInListById(id);
        if (e == null) { return null; }
        l.remove(e);
        return e;
    };
    return dependency;
}

...

@Test
public void test() {
    ...
    Dependency dependencyMock = mockDependency();
    MyClass c = new MyClass(dependencyMock);

    // it calls dependency.addElement()
    c.addElement(1, data)

    // it calls dependency.removeElement()
    assertEquals(1, c.removeElement(1).getId());
    ...
}    
</code></pre>

<p>This does work, but I wonder if it is a good idea to do so. All the examples I can find online about Mockito are basically simple when().then() statements. Can anyone please give me some advice?</p>
",https://stackoverflow.com/questions/61175833/when-unit-testing-with-mockito-should-i-implement-the-internal-logic-when-m,"['java', 'unit-testing', 'mockito']",144,False,1,1
How to perform unit testing with databases in PHP Unit 8.0 or greater,"<p>I am running a PHP project and I am using PHPUnit for unit testing. Up until recently I used PHPUnit 4.0 with DBUnit as an extension for database testing. I changed now to PHPUnit 8.0 but could not find a suitable database testing extension to test my backend functions with a test database connected. Also the documentation of PHPUnit does not contain any hint for database testing.</p>

<p>What module/extension replaces DBUnit for PHPUnit 8.0 or higher?</p>

<p>Thanks</p>

<p>Christian</p>
",https://stackoverflow.com/questions/61975330/how-to-perform-unit-testing-with-databases-in-php-unit-8-0-or-greater,"['database', 'phpunit', 'dbunit']",195,False,1,0
"Unit Testing with Mockk, java.lang.ClassCastException: PhoneValidationKt$isPhoneValid$1 cannot be cast to kotlin.jvm.functions.Function1","<p>Need some help in Unit testing my Kotlin funtion as follows, as i am new to unit testing, i had tried but failed,</p>

<p>My Kotlin top level function as follows,</p>

<pre><code>package com.reprator.phone
//PhoneValidation.kt
const val PHONE_LENGTH = 10

fun isPhoneValid(
phoneNumber: String, successBlock: (() -&gt; Unit) = {},
failBlock: (Int?.() -&gt; Unit) = {}
) =
when {
    phoneNumber.isEmpty() -&gt;
        failBlock(R.string.phone_validation_mobile_empty)
    phoneNumber.length &lt; PHONE_LENGTH -&gt;
        failBlock(R.string.phone_validation_mobile)
    else -&gt; successBlock.invoke()
}
</code></pre>

<p>My Unit test code for the above method is as follows,</p>

<pre><code>@Test
fun `Invalid Phone Number`() {
    mockkStatic(""com.reprator.phone.PhoneValidationKt"")

    val fn: (Int?) -&gt; Unit = mockk(relaxed = true)

    val result = R.string.phone_validation_mobile
    every {
        isPhoneValid(""904186605"", failBlock = captureLambda())
    } answers {
        secondArg&lt;(Int?) -&gt; Unit&gt;()(result)
    }

    isPhoneValid(""904186605"")

    verify { fn.invoke(result) }
}
</code></pre>

<p>The following is the error, i get while unit testing the code, as follows,</p>

<pre><code>java.lang.ClassCastException: com.reprator.phone.PhoneValidationKt$isPhoneValid$1 cannot be cast to kotlin.jvm.functions.Function1

at com.reprator.phone.PhoneValidationKtTest$Invalid Phone Number$2.invoke(PhoneValidationKtTest.kt:31)
at com.reprator.phone.PhoneValidationKtTest$Invalid Phone Number$2.invoke(PhoneValidationKtTest.kt:11)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2149)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2126)
at io.mockk.FunctionAnswer.answer(Answers.kt:19)
at io.mockk.impl.stub.AnswerAnsweringOpportunity.answer(AnswerAnsweringOpportunity.kt:13)
at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:54)
at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:263)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:25)
at io.mockk.proxy.jvm.advice.Interceptor.call(Interceptor.kt:20)
at com.reprator.phone.PhoneValidationKt.isPhoneValid(PhoneValidation.kt:15)
at com.reprator.phone.PhoneValidationKt.isPhoneValid$default(PhoneValidation.kt:7)
at com.reprator.phone.PhoneValidationKtTest.Invalid Phone Number(PhoneValidationKtTest.kt:26)
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.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>

<p>The following are the links, that i referred to try those unit testing as follows,</p>

<p><a href=""https://stackoverflow.com/questions/53808565/cast-exception-when-mocking-kotlin-lambda-callbacks-in-mockk?rq=1"">Link 1</a>
<a href=""https://stackoverflow.com/questions/53671695/how-to-mock-and-verify-lambda-expression-in-kotlin"">Link 2</a>
<a href=""https://stackoverflow.com/questions/53911556/mockk-verify-lambda-argument"">Link 3</a>
<a href=""https://stackoverflow.com/questions/53673292/how-to-call-a-lambda-callback-with-mockk"">Link 4</a></p>
",https://stackoverflow.com/questions/60928461/unit-testing-with-mockk-java-lang-classcastexception-phonevalidationktisphone,"['unit-testing', 'lambda', 'mocking', 'mockk', 'kotlintest']",3522,True,1,1
What to assert or verify while unit testing the BackgroundService in .Net core,"<p>I have a linked question <a href=""https://stackoverflow.com/questions/60387013/while-unit-testing-a-net-core-3-1-background-service-unable-to-resolve-iconfig/60387252#60387252"">here</a>. I read <a href=""https://stackoverflow.com/questions/56644654/how-can-i-write-unit-test-for-my-background-service"">this</a> and I'm trying to mock the dependencies in my Hosted Service. But I'm confused as to assert or verify what. I'm thinking to verify that <code>StartConsumption</code> on <code>Mock Kafka Topic Consumer Manager</code> gets invoked. But to set it up, it returns <code>void</code>. I'm not able to determine how to set up the predicate for the mock.</p>

<pre><code>services.AddSingleton(Mock.Of&lt;IKafkaTopicConsumerManager&gt;(_ =&gt; 
    _.StartConsumption(
       It.IsAny&lt;CancellationToken&gt;(),
       It.IsAny&lt;IMessageProcessingCapable&gt;(),
       It.IsAny&lt;string&gt;(),
       It.IsAny&lt;string&gt;(),
       It.IsAny&lt;List&lt;string&gt;&gt;(),
       It.IsAny&lt;string&gt;(),
       It.IsAny&lt;int&gt;())==void
    ));
</code></pre>

<p>But at <code>void</code> it shows up invalid expression term. Below is my Worker.cs which is the <code>Hosted Service</code>.</p>

<pre><code>protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
    _consumerManager.StartConsumption(
            cancellationToken,
            _messageProcessor,
            _config.GetSection(""Kafka:Servers"").Get&lt;string&gt;(),
            _config.GetSection(""ConsumerGroup"").Get&lt;string&gt;(),
            _config.GetSection(""Topics"").Get&lt;List&lt;string&gt;&gt;(),
            _config.GetSection(""Kafka:TopicSuffix"").Get&lt;string&gt;(),
            _config.GetSection(""ConsumerThreads"").Get&lt;int&gt;());
}
</code></pre>
",https://stackoverflow.com/questions/60390350/what-to-assert-or-verify-while-unit-testing-the-backgroundservice-in-net-core,"['c#', 'unit-testing', '.net-core', 'background-service']",255,True,1,1
Unit testing NgRx effect (invoking other effect) to ensure service method called twice,"<p>I am using ngrx 8.3.0 and want to test my effects class. Part of it goes like this:</p>
<pre><code>    @Effect()
    onSubmit$ = this.actions.pipe(
        ofType&lt;RequestSubmission&gt;(SubmissionActionType.REQUEST_SUBMISSION),
        switchMap(request =&gt; {
            return this.service
                .submit(request.content.slice((request.iteration - 1) * 2,request.iteration * 2))
                .pipe(map(s =&gt; SubmissionAction.submissionAccepted(request.content, s, request.iteration)),
                    catchError(error =&gt; of(SubmissionAction.submissionFailed(error.status)))
                );
        })
    );

    @Effect()
    submissionAccepted$ = this.actions.pipe(
        ofType&lt;SubmissionAccepted&gt;(SubmissionActionType.SUBMISSION_ACCEPTED),
        map(request =&gt;
            request.iteration * 2 &lt; request.content.length
                ? SubmissionAction.requestSubmission(request.content, request.iteration + 1)
                : SubmissionAction.submissionCompleted()
        )
    );
</code></pre>
<p>As you can see the second effect listens for an action that is called in the first effect. Also (if a condition is met) the second effect calls the action that the first effects listens to. This way we loop through the array <code>content</code> and call the service function <code>submit</code> in batches of 2 elements each time until the array reaches its end.</p>
<p>I now want to test that with a content of length 3, the <code>submit</code> function of my service gets called two times. So far I have the following:</p>
<pre><code>    it('should call submit method twice', async () =&gt; {
        const countSpy = spyOn(service, 'submit').and.callThrough();

        actions$ = new ReplaySubject(1);
        const content = ['a80b04a8','155b5a51','a19d0a7a'];
        actions$.next(SubmissionAction.requestSubmission(content, 1));

        await effects.onSubmitReference$.subscribe();
    
        expect(countSpy).toHaveBeenCalledTimes(2);
    
    });
</code></pre>
<p>Unfortunately, the spy detects that the function was called once only.</p>
<p>I also though of subscribing to the second effect independently before expecting the function to have been called twice</p>
<pre><code>
actions$.next(SubmissionAction.submissionAccepted(content,{result: []}, 1));
await effects.submissionAccepted$.subscribe();

</code></pre>
<p>But I get the same result. Does anyone know if the subscription of the first effect in the test should invoke the second effect automatically or not?
Thanks in advance for your time.</p>
",https://stackoverflow.com/questions/64799656/unit-testing-ngrx-effect-invoking-other-effect-to-ensure-service-method-called,"['angular', 'unit-testing', 'jestjs', 'ngrx']",308,False,1,1
"Unit testing error with act and useState, Making an API call in useEffect","<p>I have a react functional component where onload of the App I am smoking an API call which I have wrapped in useEffect and when the data is received I am updating the useState variable.
While writing a unit test case for the below component using jest and react testing library I am receiving act error and useState variable error.
Code:</p>
<pre><code>import React, { useState, useEffect } from &quot;react&quot;;
import TextField from &quot;@material-ui/core/TextField&quot;;
import Media from &quot;./card&quot;;
import Alert from &quot;@material-ui/lab/Alert&quot;;
import fetchData from &quot;../API&quot;;
const Dashboard = () =&gt; {
  const [searchInput, setSearchInput] = useState(null);
  const [receipeNotFound, setReceipeNotFound] = useState(false);

  useEffect(() =&gt; {
    fetchData(
      `https://www.themealdb.com/api/json/v1/1/random.php`,
      randomReceipe
    );
  }, []);

  const randomReceipe = (result) =&gt; {
    result.meals ? setSearchInput(result.meals[0]) : setSearchInput(null);
  };

  const searchData = (value) =&gt; {
    if (value) {
      setSearchInput(null);
      setReceipeNotFound(false);
      fetchData(
        `https://www.themealdb.com/api/json/v1/1/search.php?s=${value}`,
        searchRecepie
      );
    } else {
      setSearchInput(null);
    }
  };

  const notFound = (status) =&gt; {
    setReceipeNotFound(status);
    setSearchInput(null);
  };

  const searchRecepie = (result) =&gt; {
    result.meals ? setSearchInput(result.meals[0]) : notFound(true);
  };

  return (
    &lt;div&gt;
      &lt;TextField
        data-testid=&quot;searchInput&quot;
        id=&quot;standard-basic&quot;
        label=&quot;Search&quot;
        onBlur={(event) =&gt; searchData(event.currentTarget.value)}
      /&gt;
      {receipeNotFound ? (
        &lt;Alert data-testid=&quot;alert&quot; severity=&quot;error&quot;&gt;
          Receipe not found!
        &lt;/Alert&gt;
      ) : null}
      {Boolean(searchInput) ? (
        &lt;Media data-testid=&quot;mediaLoading&quot; loading={false} data={searchInput} /&gt;
      ) : (
        &lt;Media data-testid=&quot;Media&quot; loading={true} data={{}} /&gt;
      )}
    &lt;/div&gt;
  );
};

export default Dashboard;
</code></pre>
<p>Test:</p>
<pre><code>import React from &quot;react&quot;;
import Dashboard from &quot;./dashboard&quot;;
import ReactDOM from &quot;react-dom&quot;;
import {
  render,
  screen,
  act,
  waitFor,
  fireEvent,
} from &quot;@testing-library/react&quot;;
import { randomMockWithOutVideo, randomMockWithVideo } from &quot;./API.mock&quot;;
global.fetch = jest.fn();
let container;

describe(&quot;Card &quot;, () =&gt; {
  test(&quot;Should renders data when API request is called with meals data&quot;, async (done) =&gt; {
    jest.spyOn(global, &quot;fetch&quot;).mockResolvedValue({
      json: jest.fn().mockResolvedValue({ meals: [randomMockWithVideo] }),
    });
    const { getByTestId, container } = render(&lt;Dashboard /&gt;);
    expect(global.fetch).toHaveBeenCalledTimes(1);
    expect(global.fetch).toHaveBeenCalledWith(
      `https://www.themealdb.com/api/json/v1/1/random.php`
    );
  });

  afterEach(() =&gt; {
    jest.restoreAllMocks();
  });
});
</code></pre>
<p>error:
Warning: An update to Dashboard inside a test was not wrapped in act(...).</p>
<pre><code>  When testing, code that causes React state updates should be wrapped into act(...):

  act(() =&gt; {
    /* fire events that update state */
  });
  /* assert on the output */
</code></pre>
<blockquote>
<p>19 |     result.meals ? setSearchInput(result.meals[0]) : setSearchInput(null);
|                    ^</p>
</blockquote>
",https://stackoverflow.com/questions/65000304/unit-testing-error-with-act-and-usestate-making-an-api-call-in-useeffect,"['reactjs', 'jestjs', 'react-testing-library']",1908,False,1,1
How to mock or setup current_user in sinatra using Pundit for unit testing?,"<p>In my <code>app.rb</code> file i have the following setup for <code>current_user</code></p>

<pre><code>class Application &lt; Sinatra::Base
    include Pundit
    use JWTAuthorization    
    def current_user
        env[:user]
    end

    delete '/users/:user_id' do
      user = User.find(params[:user_id])
      no_data! unless user

      authorize user, :edit?
      user.destroy
      response = {status: 200, data:'success, user deleted.'}
      json response
    end
end
</code></pre>

<p>The problem is I need to setup the <code>current_user</code> for my unit testing. Otherwise the test will throw an error inside <code>authorize user, :edit?</code> or any other <code>Pundit</code> authorization code because <code>current_user</code> will return <code>nill</code>. 
How can I setup <code>env[:user]</code> inside my spec?</p>

<p>Is there a way i can mock <code>env[:user]</code> with a value using rspec or use <code>rack_env={}</code> to setup?</p>

<p>This is what i tried so far in my spec file without success:</p>

<pre><code>  before(:each) do
    @user = User.create(name: 'Oswaldinho',email: 'waldinho@com.com',role: 'user')
  end

  it 'deletes an existing user ' do
      delete ""/users/#{@user.id}"", params={}, rack_env={user: @user}
      expect(last_response).to be_ok
  end 
</code></pre>
",https://stackoverflow.com/questions/60664653/how-to-mock-or-setup-current-user-in-sinatra-using-pundit-for-unit-testing,"['ruby', 'rspec', 'sinatra', 'rack', 'pundit']",248,False,1,0
Grails 3 Controller Unit Testing: Domain class validation not working in a ControllerUnitTest,"<p>I'm upgrading an inherited Grails 2 app to 3.3.10. We have controller methods that rely on Domain class validation to control logic flow, but we can't get DomainClass validation to work in ControllerUnitTests when running in Grails 3</p>

<p>For example,
<code>Gift</code> and <code>RecipientAddress</code> are DomainClasses and <code>RecipientAddress.hasErrors()</code> is used to validate against the RecipientAddress constraints.</p>

<pre><code>    def confirmAddress() {
        Gift gift = Gift.get(params.giftId)
        if (!gift) {
            render(view: ""index"", model: [invalid: true])
            return
        }

        recipientAddress = recipientAddressService.storeAddressInformation(params, gift)
        if (recipientAddress.hasErrors()) {
            render(view: ""index"", model: getAddressErrorModel(gift, recipientAddress))
            return;
        } else {
            return [
                    recipientAddress    : recipientAddress,
                    gift                : gift
            ]
        }
    }
</code></pre>

<p>In the following test, when I debug the controller method it does everything expected but <code>recipientAddress.hasErrors()</code> always returns <code>true</code> and the test fails.</p>

<p>ie:</p>

<pre><code>@Transactional
class GiftDetailsControllerTest extends Specification implements ControllerUnitTest&lt;GiftDetailsController&gt; {

    @Shared
    @AutoCleanup
    SimpleMapDatastore dataStore = new SimpleMapDatastore([ConnectionSource.DEFAULT, ""reporting""],
            RecipientAddress, Gift)

    def setup() {
        controller.recipientAddressService = Mock(RecipientAddressService)
    }

    void ""test RecipientAddress Bad PhoneNumber""() {
        given:
        RecipientAddress recipientAddress = new RecipientAddress(
                phone: '123-456-789'
        )

        UnitTestDataFactory dataFactory = UnitTestDataFactory.getDataFactory()
        Gift gift = dataFactory.getMockGift()
        gift.save()

        params.giftId = gift.id

        when:
        recipientAddress.validate()
        controller.confirmAddress()

        then:
        recipientAddress.hasErrors()
        recipientAddress.getErrors().getFieldError('phone')
        1 * controller.recipientAddressService.storeAddressInformation(params, gift) &gt;&gt; recipientAddress
        view == '/giftDetails/index'
    }
}
</code></pre>

<p>Implementing <code>DataTest</code> ie: <code>...implements ControllerUnitTest&lt;GiftDetailsController&gt;, DataTest {</code> fixes the DomainClass validation, but breaks the controllers ability to get the saved Gift.</p>

<p>Is there a way get DomainClass validation working in a ControllerUnit test? </p>

<hr>

<h1>Fix</h1>

<p>Implemented DataTest with mockDomains and had to remove the custom dataStore.</p>

<pre><code>@Transactional
class GiftDetailsControllerTest extends Specification implements ControllerUnitTest&lt;GiftDetailsController&gt;, DataTest {

//    @Shared
//    @AutoCleanup
//    SimpleMapDatastore dataStore = new SimpleMapDatastore([ConnectionSource.DEFAULT, ""reporting""], RecipientAddress, Gift)

    void setupSpec() {
        mockDomains RecipientAddress, Gift
    }

....

</code></pre>
",https://stackoverflow.com/questions/61901655/grails-3-controller-unit-testing-domain-class-validation-not-working-in-a-contr,"['unit-testing', 'grails', 'grails-3.0', 'grails-3.3']",165,True,1,1
"How do I test if my data changes? (Vue JS, Jest, Unit Testing)","<p>I am working on unit testing my code with Jest in my frontend Vue JS project, and one of the tests I want to write is:</p>

<pre><code>it('should show the advanced filters if user_id exists', () =&gt; {
  })
</code></pre>

<p>This is part of a created property in the Javascript code:</p>

<pre><code>this.user_id = localStorage.getItem(""user_id"");
      if (this.user_id) {
        this.renderAdvancedFilters = true;
      }
</code></pre>

<p>Also, below is part of the data that is being exported: </p>

<pre><code>export default {
  data: () =&gt; ({
    renderAdvancedFilters: false,
    user_id: localStorage.getItem(""user_id""),
</code></pre>

<p>So, renderAdvancedFilters is originally set to false, but if a user id exists, then it is set to true, and the advanced filters are then displayed. How do I write a unit test where I am showing that if a user id exists, then advanced filters is shown on the app? Since this is a created property, there is no interaction with the app to test, so I think I should just be testing the data, but I'm not sure how to.</p>

<p>Should I be mocking the data of this.user_id? If so, how do I do that?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/59635384/how-do-i-test-if-my-data-changes-vue-js-jest-unit-testing,"['unit-testing', 'vue.js', 'jestjs', 'vuetify.js']",709,True,0,1
Mismatched anonymous define() module in unit testing with Karma + Jasmine + Durandal + KnockoutJS + RequireJS,"<p>There is a problem when implementing Jasmine unit tests through Karma for Asp.Net MVC project with Durandal wrapper over KnockoutJS + RequireJS. Here is the sample code:</p>

<p><em>karma.conf.js</em></p>

<pre><code>    config.set({
        basePath: '',
        files: [            
            { pattern: '../scripts/jasmine/boot.js', included: false },
            { pattern: '../scripts/knockout-3.4.0.js', included: false },
            { pattern: '../scripts/jquery-1.9.1.js', included: false },
            { pattern: 'node_modules/**/*-min.js', included: false },
            { pattern: '../app/durandal/app.js', included:false},
            'TestScripts/test-main.js',
            'TestScripts/DefaultTestSpec.js',
        ],
        frameworks: ['jasmine', 'requirejs'],
        plugins: [
            require('amd-loader'),
            require('karma-jasmine'),
            require('karma-chrome-launcher'),
            require('karma-requirejs')
        ],
        client: {
            clearContext: false 
        },
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        singleRun: true
    });
}; 
</code></pre>

<p><em>test-main.js</em></p>

<pre><code>var TEST_REGEXP = /(spec|test)\.js$/i;
var BASE_URL = '/base/build/js';
var BASE_URL_REGEXP = /^\/base\/build\/js\/|\.js$/g;

for (var file in window.__karma__.files) {
    if (window.__karma__.files.hasOwnProperty(file)) {
        if (/Spec\.js$/.test(file)) {
            tests.push(file);
        }
    }
}
require.config({
    baseUrl: '/TestScripts',
    paths: {
        'env': 'env',
        'jquery': '../../scripts',
        'underscore': '../../node_modules/underscore/',
        'knockout': '../../scripts/',
        'require': '../../app/durandal/amd/require',
        'app':'../../app/durandal/app.js',
        },

    shim: {
        'underscore': {
            exports: '_'
        }
    },
    deps: tests,
    callback: window.__karma__.start
});
</code></pre>

<p><em>DefaultTestSpec.js</em></p>

<pre><code>define(['ViewModel'], function (InitVM) {

    describe(""MyTestSpecTest"", function () {
        it(""should be able to connect to View Model file"", function () {
            expect(vm.id()).toBe(1);
        });
    });
});
</code></pre>

<p><em>testing JS viewmodel</em> </p>

<pre><code>define(function processView(require) {
function initVM(mode, data, InterfaceName) {
this.id = ko.observable(1);
var vm = this;
        return vm;
})
return InitVM;
})
</code></pre>

<p>If there is a need to include the HTML file of the viewmodel to the test-main or path in karma.conf.js? At the time of posting the question error message is - <strong><em>Uncaught Error: Mismatched anonymous define() module: function</em></strong>
<a href=""https://i.stack.imgur.com/K8i4H.png"" rel=""nofollow noreferrer"">Uncaught Error: Mismatched anonymous define() module: function</a></p>

<p>What can be caused or is there something missing in config files?</p>
",https://stackoverflow.com/questions/59880038/mismatched-anonymous-define-module-in-unit-testing-with-karma-jasmine-dura,"['unit-testing', 'knockout.js', 'karma-jasmine', 'durandal', 'karma-requirejs']",330,False,0,1
How to handle failed asserts and abort calls with Microsofts unit testing framework?,"<p>I just moved from my catch2 testing frameworks to Microsofts native code C++ unit testing framework for the nicer integration into the IDE. </p>

<p>But my coding style is to use lots of assert statements all over the code. I cant replace them with macro calls like AssertIfTrue calls without poisoning the whole codebase with dependencies to the framework. </p>

<p>But if an assert fails the unit test runner stops with message box popup and when i press abort button the test will be reported as skipped and not as failed. This also looks like impossible behaviour for any automated continuous integration lifecycle. </p>

<p>I already tried setting a signal handler via <code>signal(SIGABRT, SignalHandler);</code> but the handler is never called. And using _set_abort_behavior to disable the message box with  <code>_set_abort_behavior( 0, _WRITE_ABORT_MSG);</code> also has no result.</p>
",https://stackoverflow.com/questions/61378525/how-to-handle-failed-asserts-and-abort-calls-with-microsofts-unit-testing-framew,"['c++', 'c', 'visual-studio', 'unit-testing', 'assert']",221,False,0,1
How to mock boto3 resource method in a while loop for unit testing,"<p>I'm trying to unit test some code that I wrote with the boto3 library and cannot seem to figure out how to do it.</p>
<p>This is the code I'm trying to test</p>
<pre><code>def handler(event, context):
    instance_id = event['instance_id']
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)

    instance.start()
    while instance.state['Name'] != 'running':
        sleep(1)
        instance.reload()
</code></pre>
<p>And here's how the test looks currently.</p>
<pre><code>@patch.object(module.boto3, &quot;resource&quot;)
def test_starts_instance(resource_mock):
    event = {&quot;instance_id&quot;: &quot;id-1234567&quot;}

    instance_mock = resource_mock.return_value.Instance.return_value
    instance_mock.state = [{&quot;Name&quot;: &quot;stopping&quot;}]

    handler(event, None)

    resource_mock.assert_called_once_with(&quot;ec2&quot;)
    instance_mock.start.assert_called_once()
    instance_mock.reload.assert_called_once()
</code></pre>
<p>I just want to change the instance.state['Name'] to 'running' when instance.reload() is called so that the test actually tests the sleep and reload calls.</p>
",https://stackoverflow.com/questions/65408874/how-to-mock-boto3-resource-method-in-a-while-loop-for-unit-testing,"['python', 'unit-testing', 'mocking', 'boto3']",697,False,0,1
Project Structure for unit testing (qtest) when using target_sources() command in sub directory,"<p>First of all, I know there are very similar questions in this forum. However, none really answer my specific case.
I have the following project structure:</p>
<pre><code>|---Project_Root
    |---CMakeLists.txt
    |---build
    |---src
    |   |---CMakeLists.txt
    |   |---many .cpp and .h files in multiple subfolders with a different CMakeLists.txt 
    |---tests
    |   |---CMakeLists.txt
    |   |---many .cpp files
</code></pre>
<p>In the Project_Root/CMakeLists.txt:</p>
<pre><code>cmake_minimum_required(VERSION 3.5)

set(SRC_DIR src)

project(
        Project
        LANGUAGES CXX
        )

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(${PROJECT_NAME} &quot;&quot;)
target_include_directories(${PROJECT_NAME} PRIVATE ${SRC_DIR})
add_subdirectory(${SRC_DIR})
</code></pre>
<p>In the src folder and subfolder CMakeLists.txt files:</p>
<pre><code>cmake_minimum_required(VERSION 3.5)

set(SRC_FILES
    Source1.cpp
    )

set(HEADER_FILES
    Source1.hpp
    )
target_sources(${PROJECT_NAME}
        PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FILES}
        ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILES}
        )
</code></pre>
<p>Now in the tests subfolder:</p>
<pre><code>project(Test LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
enable_testing()

add_executable(Test tst_test.cpp)
add_test(NAME Test COMMAND Test)

target_link_libraries(Test PRIVATE Qt5::Test)
</code></pre>
<p>In the above CMakeLists.txt I want to include the main project as a static library. I can, for example, add a new library target (say <code>Project_Lib</code>) in the root CMakeLists.txt and use once again the command:</p>
<pre><code>target_sources(Project_Lib
        PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/${SRC_FILES}
        ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILES}
        )

</code></pre>
<p>in all the subfolders.
<strong>But is there a more elegant way of doing it without having to modify all the CMakeLists.txt in the subfolders</strong>? For example, is there way to extract the source files from the <code>Project</code> target, so that it can be reused to make the <code>Project_Lib</code> target?</p>
",https://stackoverflow.com/questions/62822893/project-structure-for-unit-testing-qtest-when-using-target-sources-command-i,"['c++', 'cmake', 'project-structure', 'ctest', 'qtestlib']",515,True,1,1
Unit Testing Ag-grid in Angular : Columns not rendered on small window sizes,"<p>I am using angular with ag-grid as per <a href=""https://www.ag-grid.com/angular-grid/"" rel=""nofollow noreferrer"">documentation</a>.</p>
<p>I am facing 2 problems :</p>
<p><strong>1.</strong>  I wrote the actual code in my vscode but i am not able to successfully reproduce it in stackblitz.</p>
<p><strong>2.</strong>  My grid contains 10 columns each of width 200 , when i do a <strong>ng test --code-coverage</strong> on vscode , the tests run on chrome browser and i immediately expand it to full screen. All my tests pass. But when i resize my chrome to <strong>about 30% of screen or less</strong> and rerun my tests, it shows an error that some of the columns are not defined that is it shows length of the header array to be less than 10. <strong>And the test fails.</strong></p>
<p>What i am trying to say is that when i <strong>reduce the window size</strong> it is like first 5 columns are defined and the rest are not.</p>
<p>Is there any reason for this to happen?</p>
<p>Also please help me in setting up the stackblitz for the same.</p>
<p><strong>NOTE : I may not be able to show it as stackblitz is not properly working, however there is a console.log statement in the second test which is what i am referring to.</strong></p>
<p><a href=""https://stackblitz.com/edit/angular-testing-with-jasmine-3va3bn?file=app/app.component.spec.ts"" rel=""nofollow noreferrer"">Link for stackblitz i tried to create</a></p>
",https://stackoverflow.com/questions/63649206/unit-testing-ag-grid-in-angular-columns-not-rendered-on-small-window-sizes,"['angular', 'jasmine', 'ag-grid-angular']",822,True,1,1
Unable to get select button click in unit testing using Jasmine and Angular,"<p>Hi here i am using Angular and trying to create a unit test for the Reactive form but unable to succeed</p>

<p>what i required : How to execute button click after the form is filled both with false and truthy values using jasmine in angular.</p>

<p>what i did : I created a logic but it is not working</p>

<pre><code> it('Form check is valid or not if no values entered', () =&gt; {

    expect(component.userCreationForm.valid).toBeFalsy();
  });

  it('Form check is valid or not when values entered', () =&gt; {

    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('123456');
    expect(component.userCreationForm.valid).toBeTruthy();
  });

  it('Form Submitted should check from is submitted', () =&gt; {
    // check form is invalid
    expect(component.userCreationForm.invalid).toBeTruthy();
    let btn = fixture.debugElement.query(By.css('button[type=submit]'));
    // Check button is disabled
    expect(btn.nativeElement.disabled).toBeTruthy();
    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('testpassword');
    fixture.detectChanges();
    // check button is enabled
    expect(btn.nativeElement.disabled).toBeFalsy();

    component.onUserCreation();
    fixture.detectChanges();

    let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
    expect(success.textContent).toBe('Bubba');

 });
</code></pre>

<p>html logic</p>

<pre><code>&lt;div class=""inv-buttons""&gt;
          &lt;button mat-raised-button color=""primary"" [disabled]=""userCreationForm.invalid"" type=""submit""&gt;Create User&lt;/button&gt;
        &lt;/div&gt;
</code></pre>

<p>Below is my stackblitz : <a href=""https://stackblitz.com/edit/angular-9-material-starter-q9wxvq"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/angular-9-material-starter-q9wxvq</a></p>
",https://stackoverflow.com/questions/62078656/unable-to-get-select-button-click-in-unit-testing-using-jasmine-and-angular,"['javascript', 'angular', 'jasmine', 'karma-jasmine']",1990,True,1,1
How to test a method for toHaveBeenCalled in unit testing an Error interceptor,"<p>What I'm trying to say is that I want to see if a particular method was called or not. I've an Error Interceptor. There are 3 methods (1 public and 2 private methods). Here is the code:</p>
<p><strong>interceptor</strong></p>
<pre><code>import { ... } from '...';
...

@Injectable({ providedIn: 'root' })
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService) {}

    intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
        return next.handle(request).pipe(
            catchError(err =&gt; {
                if (err instanceof HttpErrorResponse) {
                    switch (err.status) {
                        case 400:
                        case 403:
                            // some logic
                            break;
                        case 401:
                            return this.handle401Error(request, next); // This I've to check
                        default:
                            // some logic
                    }
                }
                const error = err.error.message || err.statusText;
                return throwError(error);
            })
        );
    }

    private handle401Error(request: HttpRequest&lt;any&gt;, next: HttpHandler) { // will be called in case: 401
        // some logic
    }

    private addToken(request: HttpRequest&lt;any&gt;, token: string) { // ignore this method
      // some logic
    }
}
</code></pre>
<p>Here is my spec file:</p>
<pre><code>import { throwError, defer } from &quot;rxjs&quot;;
import { ErrorInterceptor } from './error.interceptor';

describe('ErrorInterceptor', () =&gt; {
    let errorInterceptor;
    let authServiceSpy;

    beforeEach(() =&gt; {
        authServiceSpy = jasmine.createSpyObj('AuthService', ['logout']);
        errorInterceptor = new ErrorInterceptor(authServiceSpy);
    })

    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(throwError(
                {error: 
                    {message: 'test-error'}
                }
            ));
            //act
            errorInterceptor.intercept(httpRequestSpy, httpHandlerSpy)
                .subscribe(
                    result =&gt; console.log('good', result), 
                    err =&gt; { 
                        console.log('error', err);
                        expect(err).toEqual('test-error');
                        expect(errorInterceptor.handle401Error).toHaveBeenCalled();  //Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got undefined.
                    }
                );
        })
    })
})
</code></pre>
<p>When I check:</p>
<p><code>expect(errorInterceptor.handle401Error).toHaveBeenCalled();</code></p>
<p>I'm getting this error:</p>
<p><code>Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got undefined.</code></p>
<p>Please correct my mistake. Here's the <a href=""https://stackblitz.com/edit/stackoverflow-q-53672234-hw9jb3"" rel=""nofollow noreferrer"">stackblitz</a>.</p>
",https://stackoverflow.com/questions/63562676/how-to-test-a-method-for-tohavebeencalled-in-unit-testing-an-error-interceptor,"['angular', 'karma-jasmine']",383,True,0,1
Unit testing method which is using a private field initialized with static method,"<p>In my class <code>TwitchService</code> I'm creating a private field <code>twitchClient</code> using <code>TwitchClientBuilder</code>. How can I approach testing method <code>sendChatMessage()</code> which is using <code>twitchClient</code>?</p>
<pre><code>public class TwitchService {

    public TwitchService(){
        twitchClient = TwitchClientBuilder.builder().build();
    }

    public void sendChatMessage(String content) throws Exception {
        if(content.isEmpty()){
            throw new Exception(&quot;Cannot send empty message!&quot;);
        }

        twitchClient.getChat().sendMessage(content);
    }
}
</code></pre>
<p>So far, I have tried mocking <code>TwitchClientBuilder.builder()</code> and <code>twitchCliendBuilder.build()</code> like this:</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class TwitchServiceTest {

    private TwitchService twitchService;

    @Mock
    private TwitchClientBuilder twitchClientBuilder;


    @Test
    public void sendChatMessage() throws Exception {

        try (MockedStatic&lt;TwitchClientBuilder&gt; twitchClientBuilderMockedStatic = Mockito.mockStatic(TwitchClientBuilder.class)){
            twitchClientBuilderMockedStatic.when(() -&gt; TwitchClientBuilder.builder()).thenReturn(mock(TwitchClientBuilder.class));

            when(twitchClientBuilder.build()).thenReturn(mock(TwitchClient.class));
            twitchService = new TwitchService(&quot;x&quot;, &quot;y&quot;);
            twitchService.sendChatMessage(&quot;test message&quot;);
        }

    }
}
</code></pre>
<p>But I get <code>NullPointerException</code> on <code>twitchClient</code> in <code>sendChatMessage()</code>
Any ideas how to properly mock fields like this?</p>
",https://stackoverflow.com/questions/64836022/unit-testing-method-which-is-using-a-private-field-initialized-with-static-metho,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",52,True,0,1
How to use the data in the test resource folder during unit testing,"<p>I have a folder in my intellij project which has some .svg files, with the path <strong>""data/system/svgfiles1""</strong></p>

<p>I'm doing unit testing for a method that uses these .svg files.<br>
When I run my test locally every test is Ok. 
But, in Jenkins I get an error.</p>

<p>The reason for this error is that I use some .svg files locally that the test needs and they are not in jenkins. </p>

<p>Now, the method defines a path where the data is placed. I commented where the path is defined. 
As you can see, the path is hard coded. </p>

<pre><code> public Optional&lt;String&gt; content(final Record content, final int sides) {
            final Optional&lt;String&gt; path = Utils.findAttachmentPathById(
                ""./data/"" + DataController.Sides[sides], // here I get the path ""data/system/svgfiles1""
                content.getId()
        );
        if (!path.isPresent()) {
            return Optional.empty();
        }
        Optional&lt;String&gt; value1 = Optional.empty();
        Optional&lt;String&gt; value2 = Optional.empty();
        try {
            value2 = Optional.of(FileUtils.readFileToString(new File(path.get()), StandardCharsets.UTF_8));
        } catch (IOException ioException) {
            logger.error(""An exception"", ioException);
        }
        try {
            value1 = Optional.of(Record.format(value2.get(), content.getData()));
        } catch (Exception exception) {
            logger.error(""An exception"", exception);
        }
        return value1;
    }
</code></pre>

<p>Now I created a resource folder in the tests where I added these .svg files. 
The test method is this: </p>

<pre><code>   @Test
    public void exportZipPlateSvgContentTest() {
        // prepare
        Record record = new Record(recordValues); // record values are only some string values
        record.setId(1L);

        // expected
        Optional&lt;String&gt; expected = Optional.of(values) 

        // test
        Optional&lt;String&gt; result = platesService.content(record, 1); // this is the method under test 

        // run
        assertEquals(expected, result 
    }
</code></pre>

<p>As you can see in the test method. The path is not given as a parameter. The path is hard coded in the <strong>content</strong> method. </p>

<p>Since the path is hard coded in the method. Is it possible for the method to use a different path during testing? </p>

<p>Like, when I test it to say use the data from ""test/resources/data/svgfiles1""?</p>

<p>I would really appreciate any input. Please let me know to clarify anything. </p>
",https://stackoverflow.com/questions/60606576/how-to-use-the-data-in-the-test-resource-folder-during-unit-testing,"['java', 'junit']",281,False,0,1
"Getting repetitive iterations while solving sinon, unable to do unit testing in nodejs","<p>I am trying to do unit testing in Nodejs using sinon.</p>
<p>And I have installed the following libraries -</p>
<p><a href=""https://i.stack.imgur.com/tPjUU.png"" rel=""nofollow noreferrer"">1</a> npm i mocha</p>
<p>[2] npm i chai</p>
<p>[3] npm i sinon</p>
<p>And here is my code -</p>
<p><strong>unitTest-app.js</strong></p>
<pre><code> var sinon = require('sinon');


it('calls the original function', function(){

   var callback = sinon.fake();
   var proxy = once(callback);


   proxy();

   assert(callback.called);

   });



it('calls the original function only once', function () {
   var callback = sinon.fake();
   var proxy = once(callback);

    proxy();
    proxy();

     assert(callback.calledOnce);
     // ...or:
    // assert.equals(callback.callCount, 1);
   });
</code></pre>
<p><strong>unitTest.js</strong></p>
<pre class=""lang-js prettyprint-override""><code>function once(fn) {
  var returnValue,
    called = false;
  return function() {
    if (!called) {
      called = true;
      returnValue = fn.apply(this, arguments);
    }

    return returnValue;
  };
}
</code></pre>
<p>Unable to run the unit tests.</p>
<p>when running the command  -</p>
<pre><code>npm run test
</code></pre>
<p>Getting error -</p>
<p><a href=""https://i.stack.imgur.com/tPjUU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tPjUU.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/64852147/getting-repetitive-iterations-while-solving-sinon-unable-to-do-unit-testing-in,"['javascript', 'angular', 'unit-testing', 'mocha.js', 'sinon']",48,False,0,1
How to use Doctrine Fixture to load test database for PHP unit testing?,"<p>I am trying to set a database environment to test my Doctrine ORM Entity classes, without changing my real database.</p>
<p>I followed <a href=""https://symfony.com/doc/current/testing/database.html"" rel=""nofollow noreferrer"">Symfony's documentation</a>, but when I run <code>php bin/console doctrine:fixtures:load</code> I get the warning:</p>
<blockquote>
<p>Careful, database &quot;graph&quot; will be purged. Do you want to continue? (yes/no) [no]:</p>
</blockquote>
<p>This is despite the fact that I have set an environment variable in my <code>.env.test</code> file:</p>
<blockquote>
<p>DATABASE_URL=mysql://testUser:testPassword@127.0.0.1/graph_test</p>
</blockquote>
<p>Edit: here is the entire <code>.env.test</code> file:</p>
<pre><code># define your env variables for the test env here
KERNEL_CLASS='App\Kernel'
APP_SECRET='$ecretf0rt3st'
SYMFONY_DEPRECATIONS_HELPER=999999
PANTHER_APP_ENV=panther

# Database test
DATABASE_URL=mysql://testUser:testPassword@127.0.0.1/graph_test
</code></pre>
<p>I tried to change my <code>test/bootstrap.php</code> file but I get the same warning.</p>
<p>Is there a way to tell doctrine to take the <code>DATABASE_URL</code> value from the <code>.env.test</code> file? Any help will be appreciated.</p>
<p>PS
There is no need for more than one test .env file.</p>
",https://stackoverflow.com/questions/62852779/how-to-use-doctrine-fixture-to-load-test-database-for-php-unit-testing,"['php', 'symfony', 'doctrine-orm', 'phpunit', 'phpdotenv']",2401,True,0,3
Unit testing a simple javascript function used in my React app with Cypress,"<p>I'm using Cypress to test my React application. So far, I love it, but I'd like to unit test some basic functions, including this <code>range</code> function:</p>
<pre><code>const range = (start, end) =&gt; {
  const ans = [];
  for (let i = start; i &lt; end; i++) {
    ans.push(i);
  }
  return ans;
};
</code></pre>
<p>I've tried importing the function into a <code>cypress/integration/helpers.spec.js</code> but it doesn't work:</p>
<pre><code>import { range } from 'utils/helpers';

context('Helpers', () =&gt; {
  it('range', () =&gt; {
    expect(range(3).toLocaleString.equal([0, 1, 2]));
    expect(range(1, 3).toLocaleString.equal([1, 2]));
  });
});
</code></pre>
<p>Cypress throws the following error:</p>
<blockquote>
<p>Cannot find module 'utils/helpers'</p>
</blockquote>
<p>Any tips for importing a functions into Cypress? Is Cypress even the correct choice for testing this simple function or should I use a different testing framework? I'd prefer to use Cypress if possible so I can use a single testing framework.</p>
",https://stackoverflow.com/questions/64832135/unit-testing-a-simple-javascript-function-used-in-my-react-app-with-cypress,"['javascript', 'cypress']",287,True,0,1
Jest: unit testing creation of an excel document after http call Blob response,"<p>I am working on a react application, using Jest</p>

<p>I have to download an excel that I get as a Blob from an HTTP call 
I have to respect a coverage of 90% unit tests, and I am in trouble with this portion of code:</p>

<pre><code>downloadExcel = () =&gt; {
  templateService.getTemplate().then(
    response =&gt; {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement(""a"");
      link.href = url;
      link.setAttribute(""download"", ""Project_register_template_PMB.xlsx"");
      document.body.appendChild(link);
      link.click();
    },
    error =&gt; {
      this.setState({
        errors: { api: `API error:${error}, please contact an administrator` }
      });
    }
  );
};
</code></pre>

<p>Here is my template service: </p>

<pre><code>const getTemplate = async () =&gt; {
  const options = {
    responseType: ""blob"",
    headers: handleHeaders()
  };
  return await axios.get(downloadUrl, options).catch(handleResponse);
};

const uploadTemplate = async formData =&gt; {
  return await axios.post(uploadUrl, formData, { headers: handleHeaders() });
};

export const templateService = { getTemplate, uploadTemplate };
</code></pre>

<p>I am a very recent react developer and maybe I am doing it wrong, I would be glad to change my code by following any piece of advice</p>

<p>Thank you for your help</p>
",https://stackoverflow.com/questions/59715038/jest-unit-testing-creation-of-an-excel-document-after-http-call-blob-response,"['html', 'reactjs', 'unit-testing', 'jestjs', 'blob']",4192,True,0,1
Unit testing with Jasmine Marbles does not cover code in Code Coverage report,"<p>When I use Jasmine marbles for unit testing margeMap and switchMap, those specific blocks don't cover in code coverage report.</p>

<p>Is there a way to unit test margeMap and switchMap blocks so that they would be covered in code coverage report?</p>
",https://stackoverflow.com/questions/60275916/unit-testing-with-jasmine-marbles-does-not-cover-code-in-code-coverage-report,"['angular', 'jasmine', 'karma-coverage', 'jasmine-marbles']",81,False,0,0
How to replace a dll library for unit testing in C# Visual Studio?,"<p>I have developed a plug-in that uses a dll from a third party (third_party.dll). I have created unit tests for this plug-in, but I cannot run them using the third_party.dll, because it requires the application running.</p>

<p>I have created a dll (my_mock_up.dll) that simulates the API of the third_party.dll</p>

<p>To run the tests copy the source code to the unit test project and replace the occurrences of </p>

<pre><code>using ThirdParty.XXX.YYY.ZZZ
</code></pre>

<p>with</p>

<pre><code>using MyMockUp.XXX.YYY.ZZZ
</code></pre>

<p>but the process is manual and not very efficient. What would be a better approach? Is there a way to run unit tests for a plug-in with the host application running? Does VisualStudio have a functionality or a package for it? I could modify the code of the plug-in to accommodate the unit testing if that is also an option.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/60305277/how-to-replace-a-dll-library-for-unit-testing-in-c-visual-studio,"['c#', 'visual-studio', 'unit-testing', 'dll']",171,False,0,0
How to create output in a shell function for unit testing with bats?,"<p>After setting up a bats test framework that can test shell scripts in some directory, I am trying to expand the bats tests to test a shell function that is written in another shell file named <code>passive_function.sh</code>.</p>
<h2>Test setup</h2>
<p>I created a <a href=""https://github.com/a-t-0/shell_unit_testing_template"" rel=""nofollow noreferrer"">template repository</a> to perform shell testing. It contains a file called <code>test_other_shell.bats</code> in folder <code>/test/</code> with content:</p>
<pre><code>#!./test/libs/bats/bin/bats

load 'libs/bats-support/load'
load 'libs/bats-assert/load'

@test &quot;running the file in /src/active_function.sh.&quot; {
    run ./src/active_function.sh 9 33
    assert_output 42
}
</code></pre>
<p>And I created a file called <code>main.sh</code> with content:</p>
<pre><code>#!/bin/sh
some_active_function() {
    sum=&quot;$1 + $2&quot; | bc -l
    echo &quot;$sum&quot;
}

some_active_function
</code></pre>
<h2>Test result</h2>
<p>Running the bats test from terminal fails with output:</p>
<pre><code> ✗ running the file in /src/active_function.sh.
   (from function `assert_output' in file test/libs/bats-assert/src/assert.bash, line 239,
    in test file test/test_active_function.bats, line 8)
     `assert_output 42' failed
   
   -- output differs --
   expected : 42
   actual   : 
   --
</code></pre>
<h2>Function verification</h2>
<p>I manually verified this function returns <code>42</code> by running:</p>
<pre><code>source ./src/active_function.sh; some_active_function 9 33
</code></pre>
<p>from terminal, which prints:</p>
<pre><code>42
42
</code></pre>
<h2>Question</h2>
<p>How can I write a bats test that tests a shell function which returns the addition of input 2 integer numbers?</p>
<p>E.g. if I call <code>somefunc 3 5</code> the test pass if the function returns <code>8</code>, and fail otherwise.</p>
",https://stackoverflow.com/questions/64732746/how-to-create-output-in-a-shell-function-for-unit-testing-with-bats,"['shell', 'unit-testing', 'bats-core']",988,True,0,2
setTimeout error when unit testing a custom node in Node-RED using Jest,"<p>I've noticed that in general testing custom nodes in Node-RED is not done using Jest - I don't think there is a particular reason but it's what I'm the most familiar with so I'm trying it anyway.</p>

<p>My test setup looks like</p>

<pre><code>const n = require('../src/index.js');

describe('custom node', () =&gt; {
  const nodeType = 'custom node';

  beforeAll(done =&gt; {
    helper.startServer(done);
  });

  afterEach(() =&gt; {
    helper.unload();
  });

  afterAll(done =&gt; {
    helper.stopServer(done);
  });

  it('should be loaded', () =&gt;
    new Promise((resolve, reject) =&gt; {
      const flow = [{ id: 'n1', type: nodeType, name: 'test name' }];

      helper.load(n, flow, () =&gt; {
        const n1 = helper.getNode('n1');
        try {
          expect(n1).toBeTruthy();
          expect(n1).toHaveProperty('name', 'test name');
          resolve();
        } catch (e) {
          reject(e);
        }
      });
    }));
});
</code></pre>

<p>and the error produced is</p>

<pre><code>console.error node_modules/jest-jasmine2/build/jasmine/Env.js:289
      Unhandled error
    console.error node_modules/jest-jasmine2/build/jasmine/Env.js:290
      TypeError: setTimeout(...).unref is not a function
          at Immediate.&lt;anonymous&gt; (/dev/custom_nodes/node-red-contrib-x/node_modules/stoppable/lib/stoppable.js:43:39)
          at processImmediate (internal/timers.js:439:21)
          at process.topLevelDomainCallback (domain.js:126:23)
</code></pre>
",https://stackoverflow.com/questions/59646936/settimeout-error-when-unit-testing-a-custom-node-in-node-red-using-jest,"['javascript', 'unit-testing', 'jestjs', 'node-red']",1051,True,0,1
Checking local variable while unit testing on a component in Angular gives error,"<p>Suppose there are 2 components : AppComponent and TestComponent. I am calling TestComponent using it's directive in the HTML template of AppComponent. Now TestComponent has an @Input() property ( let it be myTitle ).</p>

<p>I am doing unit testing for TestComponent only. For title, i am passing a random value in the test itself. Here is the code for the same :</p>

<p>app.component.html </p>

<pre><code>&lt;span&gt;&lt;app-test [myTitle]=""title""&gt;&lt;/app-test&gt;&lt;/span&gt;
</code></pre>

<p>app.component.ts</p>

<pre><code>@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent{
    title = {name: 'hello-world'};
}
</code></pre>

<p>test.component.html</p>

<pre><code>&lt;p&gt;test works!!{{myTitle.name}}&lt;/p&gt;
&lt;button (click)=""onClick()""&gt;Click Please !!!&lt;/button&gt;
</code></pre>

<p>test.component.ts</p>

<pre><code>@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit{
    @Input() myTitle;
    filter;
    constructor(){

    }

    ngOnInit():void{
        this.myTitle.name = ""Hi!!"";
    }
    onClick(){
       this.filter=""GokuSSj3"";
    }
}
</code></pre>

<p>test.component.spec.ts</p>

<pre><code>describe('Test component',() =&gt;{
    let temp;
    let component: TestComponent;
    let fixture: ComponentFixture&lt;TestComponent&gt;;

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

    beforeEach(()=&gt;{
        temp = {name: ""Heloooo""};
       fixture = TestBed.createComponent(TestComponent);
       component = fixture.componentInstance;
    });

    it('should check First',()=&gt;{
       component.myTitle = temp;
       console.log(component.myTitle.name);
       console.log(temp.name);

       fixture.detectChanges();

       console.log(component.myTitle.name);
       console.log(temp.name);
       expect(component.myTitle.name).toEqual(temp.name);
    });

    it('should check whether onClick is called on button click or not and also the value of filter',()=&gt;{
       component.myTitle = temp;
       spyOn(component,'onClick');
       fixture.detectChanges();

       let btn = fixture.debugElement.query(By.css('button'));
       btn.triggerEventHandler('click',null);

       fixture.whenStable().then(()=&gt;{
          expect(component.onClick).toHaveBeenCalled();
          expect(component.filter).toEqual(""GokuSSj3"");
    });
});
</code></pre>

<p>The second test case shows the error : Expected undefined to equal 'GokuSSj3'. Why is it so? Even though onClick has been called.</p>

<p>I am new to this community, so please help me improve the question if there are any fails.</p>
",https://stackoverflow.com/questions/61176688/checking-local-variable-while-unit-testing-on-a-component-in-angular-gives-error,"['angular', 'typescript', 'unit-testing']",3229,True,0,1
I have problem with Unit testing for check Registration in .Net MVC model,"<pre><code>public class AccountControllerTest
{
    private  IMapper _mapper;
    private  UserManager&lt;User&gt; userManager;
    private  SignInManager&lt;User&gt; _signInManager;


    [TestMethod]
    public void AccountController_Register_UserRegistered()
    {
        var accountController = new AccountController(_mapper,userManager,_signInManager);

        var registerViewModel = new UserRegistrationModel
        {
            Email = ""H@o2.pl"",
            Password = ""Hej123@"",
            FirstName = ""Hania"",
            LastName =""Kowalska""

        };


        var result = accountController.Register(registerViewModel).Result;
        Assert.IsTrue(result is RedirectToRouteResult);
        Assert.IsTrue(accountController.ModelState.All(kvp =&gt; kvp.Key != """"));
    }
</code></pre>

<p>And my AccountController.cs :</p>

<pre><code>public class AccountController : Controller
{

    private readonly IMapper _mapper;
    private readonly UserManager&lt;User&gt; _userManager;
    private readonly SignInManager&lt;User&gt; _signInManager;

    public AccountController(IMapper mapper, UserManager&lt;User&gt; userManager, SignInManager&lt;User&gt; signInManager)
    {
        _mapper = mapper;
        _userManager = userManager;
        _signInManager = signInManager;
    }

    [HttpGet]
    public IActionResult Register()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task&lt;IActionResult&gt; Register(UserRegistrationModel userModel)
    {
        if (!ModelState.IsValid)
        {
            return View(userModel);
        }

        var user = _mapper.Map&lt;User&gt;(userModel);

        var result = await _userManager.CreateAsync(user, userModel.Password);
        if (!result.Succeeded)
        {
            foreach (var error in result.Errors)
            {
                ModelState.TryAddModelError(error.Code, error.Description);
            }

            return View(userModel);
        }

        await _userManager.AddToRoleAsync(user, ""Visitor"");

        return RedirectToAction(nameof(HomeController.Index), ""Home"");
    }
</code></pre>

<p>I have the error on line in AccountController when I Debug Test :</p>

<pre><code>var user = _mapper.Map&lt;User&gt;(userModel);
</code></pre>

<p>Error:(Object reference not set to an instance of an object.)</p>
",https://stackoverflow.com/questions/61662407/i-have-problem-with-unit-testing-for-check-registration-in-net-mvc-model,"['c#', 'unit-testing']",35,False,0,0
"Unit testing JavaScript which calls a function only if it exists, with Jest","<p>For code like this:</p>
<pre><code>export const addMediaQueryEventListener = (media, onChange) =&gt; {
  if (root.matchMedia) {
    const mediaQueryList = root.matchMedia(media);
    ...
</code></pre>
<p>How can you test both code 'branches' with Jest, i.e. when <code>root.matchMedia</code> is falsy as well as when it exists?</p>
<p>I can mock <code>matchMedia</code> to be a function and assert that it's called OK. But to test the other way around in order to get 100% test coverage, I'd need to mock <code>matchMedia</code> to be falsy, but also assert that it hasn't been called as a function.</p>
<p>Is there a way to mock the <em>property</em> <code>matchMedia</code> to be falsy whilst also spying on <code>matchMedia</code> as a function? Or would this function need to be rewritten to make it testable?</p>
",https://stackoverflow.com/questions/64145802/unit-testing-javascript-which-calls-a-function-only-if-it-exists-with-jest,"['javascript', 'unit-testing', 'jestjs']",222,False,0,1
"TypeError: list indices must be integers or slices, not str on Unit Testing","<p>I have the error as <code>&quot;TypeError: list indices must be integers or slices, not str &quot;</code> while running a unit test on the following function. The following function is used to call the model that is saved in Google AI Platform. However, the data input has to be base64 serialized, hence, I include the get_serialized_example(raw) function within the tfx_test(request). Any help and advice are appreciated. Thanks in advance!</p>
<pre><code>def tfx_test(request):
    
    #User Inputs
    project = request.project
    model = request.model
    signature = request.signature
    version = request.version
    
    #Data inputs Base64 encoder 
    
    def get_serialized_example(raw):
        return tf.train.Example(
                features=tf.train.Features(
                  feature={&quot;value&quot;:
                              tf.train.Feature(bytes_list=tf.train.BytesList(value=[raw]))
                          }
                    )
                ).SerializeToString()


    b64_country_code = base64.b64encode(get_serialized_example(request.country_code)).decode('utf-8')
    
    b64_project_type = base64.b64encode(get_serialized_example(request.project_type)).decode('utf-8')
    
    # ml.googleapis.com
    service = googleapiclient.discovery.build('ml', 'v1')
    name = 'projects/{}/models/{}'.format(project, model)

    if version is not None:
        name += '/versions/{}'.format(version)

    response = service.projects().predict(
        name=name,
        body={
            'signature_name': signature,
            'instances': [
                    {
                       &quot;examples&quot;:{&quot;b64&quot;: b64_country_code,
                                   &quot;b64&quot;: b64_project_type}
                    }]
        }
    ).execute()

    if 'error' in response:
        raise RuntimeError(response['error'])

    return response['predictions']
</code></pre>
<p><strong>UNIT TESTING</strong></p>
<p>def test_safety_kfp_custom(self):</p>
<pre><code>self.request = TestScenario.populated_request(Test.test1)
self.response = tfx_test(self.request)

self.assertEqual(0.35915321111679077, self.response[&quot;predictions&quot;])
</code></pre>
<p><strong>Data Input for tfx_test function</strong></p>
<pre><code>class request():
    project = &quot;xxx&quot;
    model = &quot;xxx&quot;
    signature = &quot;xxx&quot;
    country_code = b&quot;UK&quot;
    project_type = b&quot;PT&quot;
    version = 'xxx'
</code></pre>
",https://stackoverflow.com/questions/62549037/typeerror-list-indices-must-be-integers-or-slices-not-str-on-unit-testing,"['python', 'python-3.x', 'base64']",126,False,0,1
Unit testing a controller action which calls a private method that uses HTTPClient,"<p>I am a newbie to C# and TDD. I am developing a product in which I need to write unit tests for some HTTP API calls. Below is how a controller looks like:</p>

<pre><code>public class CommunicationController : ControllerBase
{
 private readonly IHttpClientFactory _clientFactory;
 private readonly AppSettings _appSettings;

 public CommunicationController(IHttpClientFactory clientFactory, IOptions&lt;AppSettings&gt; appSettings)
 {
  _clientFactory = clientFactory;
  _appSettings = appSettings.Value;
 }

 [HttpPost]
 public async Task&lt;IActionResult&gt; PostEntity([FromBody] Entity entity)
 {
  if (entity.foo == null)
  {
   NoActionsMessage noActionsMessage = new NoActionsMessage
   {
    Message = ""No actions performed""
   };
   return Ok(noActionsMessage);
  }

  var accessTokenDatails = await GetAccessTokenDetailsAsync();
  var callUrl = ""http://someUrlGoesHere"";

  var json = JsonConvert.SerializeObject(entity);
  var content = new System.Net.Http.StringContent(json, Encoding.UTF8, ""application/json"");
  var request = new HttpRequestMessage(HttpMethod.Put, new Uri(callUrl))
  {
   Content = content
  };
  request.Headers.Add(""accessToken"", accessTokenDatails.AccessToken);

  return await InvokeHttpCall(request);
 }


 private async Task&lt;AccessTokenDetails&gt; GetAccessTokenDetailsAsync()
 {
  var appId = _appSettings.AppId;
  var appSecret = _appSettings.AppSecret;
  var refreshToken = _appSettings.RefreshToken;

  var request = new HttpRequestMessage(HttpMethod.Get, new Uri(""sometokenproviderUrl""));

  request.Headers.Add(""applicationId"", appId);
  request.Headers.Add(""applicationSecret"", appSecret);
  request.Headers.Add(""refreshToken"", refreshToken);

  var client = _clientFactory.CreateClient();

  var response = await client.SendAsync(request);

  if (response.IsSuccessStatusCode)
  {
   var responseStream = response.Content.ReadAsStringAsync();

   // [ALERT] the failing line in unit test - because responseStream.Result is just a GUID and this the the problem
   var result = JsonConvert.DeserializeObject&lt;AccessTokenDetails&gt;(responseStream.Result);

   return result;
  }
  else
  {
   throw new ArgumentException(""Unable to get  Access Token"");
  }
 }
}
</code></pre>

<p>This POST method which is calling a private method. By calling this post method with appropriate entity given:
 1. Should make a call to the token provider service and get the token
 2. Using the token, authenticate the service to add the entity</p>

<p><code>AccessTokenDetails</code> class looks is below:</p>

<pre><code>public sealed class AccessTokenDetails
{
 [JsonProperty(""accessToken"")]
 public string AccessToken { get; set; }

 [JsonProperty(""endpointUrl"")]
 public Uri EndpointUrl { get; set; }

 [JsonProperty(""accessTokenExpiry"")]
 public long AccessTokenExpiry { get; set; }

 [JsonProperty(""scope"")]
 public string Scope { get; set; }
}
</code></pre>

<p>Now when it comes to unit testing (I am using XUnit) I have a test method like below:</p>

<pre><code>public async Task Entity_Post_Should_Return_OK()
{
 / Arrange - IHttpClientFactoryHttpClientFactory
 var httpClientFactory = new Mock&lt;IHttpClientFactory&gt;();
 var mockHttpMessageHandler = new Mock&lt;HttpMessageHandler&gt;();
 var fixture = new Fixture();

 mockHttpMessageHandler.Protected()
  .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(""SendAsync"", ItExpr.IsAny&lt;HttpRequestMessage&gt;(), ItExpr.IsAny&lt;CancellationToken&gt;())
  .ReturnsAsync(new HttpResponseMessage
  {
   StatusCode = HttpStatusCode.OK,
   Content = new StringContent(fixture.Create&lt;string&gt;),
  });

 var client = new HttpClient(mockHttpMessageHandler.Object);
 client.BaseAddress = fixture.Create&lt;Uri&gt;();
 httpClientFactory.Setup(_ =&gt; _.CreateClient(It.IsAny&lt;string&gt;())).Returns(client);

 // Arrange - IOptions
 var optionsMock = new Mock&lt;IOptions&lt;AppSettings&gt;&gt;();
 optionsMock.SetupGet(o =&gt; o.Value).Returns(new AppSettings
 {
  AppId = ""mockappid"",
  AppSecret = ""mockappsecret"",
  RefreshToken = ""mockrefreshtoken""
 });

 // Arrange - Entity
 AddActionEntity entity = new Entity();
 entity.foo = ""justfoo"";

 // Act  
 var controller = new CommunicationController(httpClientFactory.Object, optionsMock.Object);
 var result = await controller.PostEntity(entity);

 // Assert  
 Assert.NotNull(result);
 Assert.IsAssignableFrom&lt;OkObjectResult&gt;(result);
}
</code></pre>

<p>This particular test case is failing in the when calling the <code>PostEntity</code> method as it failed to deserialize the <code>responseStream.Result</code> in the <code>GetAccessTokenDetailsAsync()</code> private method, to <code>AccessTokenDetails</code> in this unit test. The deserialization failed as the value of <code>responseStream.Result</code> is just a GUID string.</p>

<p>Can anyone please tell me that I am getting into a ""dependency inversion"" problem and tell me a way to overcome this?</p>

<p>I am thinking of separating the <code>GetAccessTokenDetailsAsync</code> to a different class, something like <code>AccessTokenProvider</code> and mock it to over come it - will it be a good approach? what could be a best approach to solve this problem.</p>
",https://stackoverflow.com/questions/61455068/unit-testing-a-controller-action-which-calls-a-private-method-that-uses-httpclie,"['c#', 'unit-testing', 'moq']",896,True,0,1
Inner private method undefined while unit testing a public method - Jest &amp; TypeScript,"<p>I'm trying to unit test a public method that itself uses a private method.</p>
<p>Here is my class:</p>
<pre><code>class MyService {    
  public publicMethod(): boolean { 
    return this.privateMethod();
  }
    
  private privateMethod(): boolean {
    return true;
  }
}

export default new MyService();
</code></pre>
<p>Here is my test:</p>
<pre><code>describe('test', () =&gt; {
  const method = myService.publicMethod;
  it('Should return true', () =&gt; {
    expect(method()).toBe(true);
  });
});    
</code></pre>
<p>Running this test leads to this TypeScript error:</p>
<pre><code>● test › Should return true

    TypeError: Cannot read property 'privateMethod' of undefined

      xx | 
      xx |   public publicMethod(): boolean {
    &gt; xx |     return this.privateMethod();
         |                 ^
      xx |   }
      xx | 
      xx |   private privateMethod(): boolean {
</code></pre>
<p>I've spent hours looking for a solution but can only find &quot;workarounds&quot;.</p>
<p>Anyone encountered this problem before?
Thanks for your help.</p>
",https://stackoverflow.com/questions/64101202/inner-private-method-undefined-while-unit-testing-a-public-method-jest-types,"['typescript', 'jestjs']",626,False,0,2
AWS Laravel Unit Testing - The security token included in the request is invalid,"<p>I am doing unit testing for my AWS Cloudfront code using <code>phpunit</code>, if I am not testing the code in the command line, my code works perfectly fine. But if I am testing it in the command line, I am getting this error: <code>The security token included in the request is invalid.</code> I read somewhere that i need to work on <a href=""https://laravel.com/docs/8.x/mocking"" rel=""nofollow noreferrer"">Laravel &quot;mock&quot;</a>, but I can't seem to make that work.</p>
<p>Here is my code:</p>
<pre><code>$this-&gt;instance(CloudFrontService::class, \Mockery::mock(CloudFrontService::class, function ($mock) {
    $mock-&gt;shouldReceive('invalidate')-&gt;with(&quot;test.txt&quot;)-&gt;once();
}));

$r = app(CloudFrontService::class)-&gt;invalidate(&quot;test.txt&quot;);

$this-&gt;assertTrue($r);
</code></pre>
<p>Any guidance is greatly appreciated. Thank you!</p>
",https://stackoverflow.com/questions/64981138/aws-laravel-unit-testing-the-security-token-included-in-the-request-is-invalid,"['php', 'laravel', 'amazon-web-services', 'phpunit', 'amazon-cloudfront']",352,False,0,0
How to use translation with component to make it useful for unit testing,"<p>Most of the components looks like as follows:</p>

<pre><code>import React, { Component } from ""react"";
import { withTranslation } from ""react-i18next"";

class XYZ extends Component {
    constructor(props) {
    super(props);
    this.state = {
    };
  }

  .....
  .....


  render() {
    const { t } = this.props;

    return (

        ..... 
    );
  }
}

export default withTranslation()(XYZ);
</code></pre>

<p>or, like below, in case of function components:</p>

<pre><code>export const XYZ = withTranslation()(({ t, ...props }) =&gt; {
  ....
  return (
    .....
  );
});
</code></pre>

<p>I wanted to use enzyme shallow as it would only unit test the XYZ component than its child components but with it I face a problem as the first level of component is translation and it doesn't go to Child components inside XYZ. So, I am thinking I may not be writing the components properly. What do you suggest is the right way to write this class and function component so that testing would be easy. </p>
",https://stackoverflow.com/questions/59773903/how-to-use-translation-with-component-to-make-it-useful-for-unit-testing,"['reactjs', 'jestjs', 'enzyme']",155,True,0,1
How to do unit testing on inline styling of a component in reactjs?,"<p>I have a function named as <code>BsButtons</code> and inside that I have Button which has an inline styling. I am trying to write a unit test to check whether the particular Button has a particular style or not. </p>

<p><strong>BsButtons.jsx</strong></p>

<pre><code>import React from 'react';
import { Button } from 'semantic-ui-react';
export const BsButtons = (props) =&gt; {
     const { buttonstyle } = props || {}; 
    return(
        &lt;div&gt;
            &lt;Button style={{...buttonstyle,backgroundColor:'#7B4259', boxShadow:'0 3px 0px rgba(123, 66, 89, 0.15)',borderRadius:20, fontWeight:200}} {...props} /&gt;
        &lt;/div&gt;
    );};
</code></pre>

<p><strong>BsButton.test.js</strong></p>

<pre><code>import React from 'react' ;
import { renderer, create } from 'react-test-renderer' ;
import Enzyme, { shallow, mount } from ""enzyme"";
import BsButtons from '../../src/components/ButtonComponents/BsButtons';
import Adapter from ""enzyme-adapter-react-16"";
import { Button } from 'semantic-ui-react';

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

const tree = create(&lt;BsButtons/&gt;).toJSON();
it('Should have Background color as #7B4259', () =&gt; {
        expect(tree.find(Button)).to.have.style('backgroundColor','#7B4259')
    });
</code></pre>

<p>I'm getting an error that <code>tree.find is not a function</code>.</p>
",https://stackoverflow.com/questions/60202477/how-to-do-unit-testing-on-inline-styling-of-a-component-in-reactjs,"['reactjs', 'jestjs', 'enzyme']",443,False,0,1
Conflict with loading up mock data for unit testing between PyCharm and unittests,"<p>I have a Python project structure as follows.</p>

<pre>
.
├── data
├── src
│   ├── module1
│   └── module2
└── tests
    ├── base
    ├── module1
    └── module2
</pre>

<p>The <code>data</code> directory is where I put mock data for use in unit test (e.g. CSV files). If I am inside PyCharm, inside a unit test, I can use a relative path as below and use the IDE to run a unit test (using <code>unittests</code>) successfully.</p>

<pre><code>pd.read_csv('../../data/mock.csv')
</code></pre>

<p>However, outside of PyCharm, I can try to run the following command to run the unit test.</p>

<pre><code>python -m unittest tests/module1/*.py
</code></pre>

<p>I will get an error that says the file does not exists. If I change the path as follows, then running the unit test from outside PyCharm works, but running the test within PyCharm fails.</p>

<pre><code>pd.read_csv('./data/mock.csv')
</code></pre>

<p>When I inspect the unit test configuration, I notice that the <code>working directory</code> is set to <code>/Users/myusername/myproject/tests/module1</code>. If I change the working directory to <code>/Users/myusername/myproject</code>, I get the following error: <code>AssertionError: Path must be within the project</code>.</p>

<p>I even tried to move the <code>data</code> directory into <code>tests &gt; module1</code>, but the same conflict remains; now <code>pd.read_csv('./data/mock.csv')</code> works for PyCharm but fails for the terminal.</p>

<p>Any ideas on how to resolve this conflict?</p>
",https://stackoverflow.com/questions/62080049/conflict-with-loading-up-mock-data-for-unit-testing-between-pycharm-and-unittest,"['python', 'unit-testing', 'pycharm']",121,True,0,1
Is there a useful pattern for unit testing with gmock for grpc Server classes?,"<p>It's tremendously helpful that there's a tool to generate mock versions of the client stubs. Testing the server side is causing me tons of headache at the moment. Enough headache where I feel like I must be doing something fundamentally wrong.</p>

<p>I may be misreading the following, but the end2end tests, including 'mock_test' seem to be using an actual client-server connection to drive testing. They may mock out the client, or mock out the client readers/writers to see the response from the server, but it's not clear to me how to test the server in isolation.</p>

<p>What I want to be able to do: I have some Service implentation that inherits from the gRPC generated class ""Service."" suppose that service exposes an interface <code>::grpc::Status Foo(::grpc::ServerContext* context, const CommandMessage* request, ::grpc::ServerWriter&lt;CommandResponse&gt;* writer);</code> My gut for writing unit tests is saying to pass in a mock ""ServerWriter"" class and expect 'Write' is called when appropriate. But ServerWriter is marked final and can't be overridden.</p>

<p>This isn't the first place I've run into trouble with my kind of standard ways of mocking and gRPC's server stuff. The Server class, the ServerBuilder class, etc. I've wrapped so that I could put mock versions of them into tests (to validate that the correct parameters are being passed to my Server when it's being constructed, e.g.)</p>

<p>So I think I'm missing something with grpc then. I just don't know what. Am I supposed to stand up a real server in my unit tests and probe it with a mock client? How do I validate the proper server configurations are being passed, if I have to stand up a test version with test configurations? The code has interface classes and virtual methods, but then the parts that seem exposed for public use don't seem to be easily mockable as I'd expect.</p>
",https://stackoverflow.com/questions/60725860/is-there-a-useful-pattern-for-unit-testing-with-gmock-for-grpc-server-classes,"['c++', 'unit-testing', 'grpc', 'googletest', 'googlemock']",689,False,5,0
Whats the benefit or purpose of unit testing a void method like doFilter?,"<p>I am on the java tomcat stack and creating a new filter. <a href=""https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpFilter.html"" rel=""nofollow noreferrer"">https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpFilter.html</a> I am interested in unit testing it because I want to have 100% branch coverage.</p>

<p>This filter wraps the response object. We override the default behavior of the response such that whenever we call response.addCookie(cookie), we append the string ""happy"" to the cookie name:</p>

<pre><code>HappyCookieFilter implements Filter {
HappyCookieResponseWrapper happyCookieResponseWrapper;
...

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    chain.doFilter(req, happyCookieResponseWrapper.wrap(res));
}

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

<ol>
<li>Assuming the HappyCookieResponseWrapper is already unit tested, what would be the benefit of testing doFilter method?</li>
<li>How would I test the HappyCookieFilter.doFilter and what should I assert?</li>
</ol>
",https://stackoverflow.com/questions/59783797/whats-the-benefit-or-purpose-of-unit-testing-a-void-method-like-dofilter,"['java', 'unit-testing', 'tomcat']",49,True,-1,3
Unit Testing using MOQ: test if a method is called on certain conditions,"<p>I have a method which internally calls methodB but based on certain condition</p>

<pre><code>methodA(Req req)
{
if(req.Quantity &gt; 10)
{
_someIinterface.methodB(req);
}
}
</code></pre>

<p>and I have mutiple conditions where </p>

<p>quantity=1 -> methodB() wont be executed </p>

<p>quantity=5 -> methodB() wont be executed</p>

<p>quantity=11 -> methodB() will be executed</p>

<p>quantity=4 -> methodB() wont be executed</p>

<p>SO I have a test case like</p>

<pre><code>[Theory]
[JsonFileData(""TestData.json"", ""ScenarioRequest"")]
public void TestMethodB()
{
Mock&lt;SomeInterface&gt; moq= new Mock&lt;SomeInterface&gt;();
moq.Setup(x=&gt;x.methodB(It.IsAny&lt;Req&gt;())).Verifiable();
sut.methodA(req);
moq.Verify(x=&gt;x.methodB(It.IsAny&lt;Req&gt;()),Times.Once());

}
</code></pre>

<p>source of JsonFileData is from 
<a href=""https://andrewlock.net/creating-a-custom-xunit-theory-test-dataattribute-to-load-data-from-json-files/"" rel=""nofollow noreferrer"">https://andrewlock.net/creating-a-custom-xunit-theory-test-dataattribute-to-load-data-from-json-files/</a></p>

<p>So in this case the testcase 1 and 2 fail but testcase 3,4 passes even though testcase 4 has quantity 4.
Does anyone know how to test such cases?</p>
",https://stackoverflow.com/questions/60433900/unit-testing-using-moq-test-if-a-method-is-called-on-certain-conditions,"['c#', 'unit-testing', 'moq', 'xunit']",99,False,0,0
NestJs unit testing on typeorm pagination getting error queryBuilder.take(...).skip is not a function,"<p>I am trying to mock createQueryBuilder to unit test pagination part, But i am getting below error</p>

<blockquote>
  <p>queryBuilder.take(...).skip is not a function</p>
</blockquote>

<p>My Mock for createQueryBuilder </p>

<pre><code>    createQueryBuilder: jest.fn(() =&gt; ({
      delete: jest.fn().mockReturnThis(),
      innerJoinAndSelect: jest.fn().mockReturnThis(),
      innerJoin: jest.fn().mockReturnThis(),
      from: jest.fn().mockReturnThis(),
      where: jest.fn().mockReturnThis(),
      execute: jest.fn().mockReturnThis(),
      getOne: jest.fn().mockReturnThis(),
      orderBy : jest.fn().mockReturnThis(),
      take : skip =&gt; ({
       skip: 5
      }), 
  }))
</code></pre>

<p>Unit Test for Find all</p>

<pre><code>it(""Find All"", async () =&gt; {
    const pageData: PaginationDto = {
      page: 1,
      limit: 10,
      sortBy: ""id"",
      sortOrder: -1,
      relatinalData: relatinalData.no

    };
    expect(await service.getGroups(pageData)).toEqual({
      docs: [{
        groupName: ""group123"",
        description: ""Group Description"",
        roleId: 1
      },
      {
        groupName: ""group123"",
        description: ""Group Description"",
        roleId: 1
      }]
    });
});
</code></pre>

<p>Services</p>

<pre><code>import { paginate } from 'nestjs-typeorm-paginate';

async getGroups(paginationDto: PaginationDto) {
        const pageOptions = await this.databaseService.preparePageData(paginationDto, 'groups');
        const queryBuilder = this.groupModel.createQueryBuilder('groups');
        const flag = paginationDto.relatinalData;
        if (relatinalData.yes === flag) {
            queryBuilder.leftJoinAndSelect(""groups.role"", ""role"");
        }
        queryBuilder.orderBy(pageOptions.order);
        pageOptions['route'] = environment.hostname + ""groups"";
        return await paginate(queryBuilder,pageOptions);
}
</code></pre>

<p>Pagination page option Prepare function</p>

<pre><code>async preparePageData(paginationDto, modelName) {
    const sort = {};
    if (paginationDto.sortBy &amp;&amp; paginationDto.sortOrder) {
        const sortValue = paginationDto.sortBy
        const sortOrder = paginationDto.sortOrder;
        if (paginationDto.relatinalData &amp;&amp; relatinalData.yes === paginationDto.relatinalData) {
            sort[modelName + '.' + sortValue] = sortOrder;
        } else {
            sort[sortValue] = sortOrder;
        }
    }
    const options = {
        page: paginationDto.page ? Number(paginationDto.page) : constant.pageLimit,
        limit: paginationDto.limit ? Number(paginationDto.limit) : constant.limit,
        order: sort ? sort : constant.sort
    };
    return options;
}
</code></pre>

<p>Can any one please help me to mock <strong>nestjs-typeorm-paginate</strong></p>
",https://stackoverflow.com/questions/61767281/nestjs-unit-testing-on-typeorm-pagination-getting-error-querybuilder-take-s,"['unit-testing', 'jestjs', 'nestjs', 'typeorm']",4197,True,4,2
Using Visual Studio native C++ unit testing framework with strings instead of wide strings,"<p>Is there a way to configure Visual Studio native C++ unit testing framework to work with <strong>std::string</strong> instead of <strong>std::wstrings</strong> ?</p>
<pre><code>Assert::Equal&lt;class T&gt;(const T &amp; t1,const T &amp;t2)
</code></pre>
<p>requires the function</p>
<pre><code>template&lt;class T&gt; std::wstring ToSring&lt;class T&gt;(const T &amp; t) /* note the wstring here */
</code></pre>
<p>to be written/specialized by the test writer for the object to be tested (of type T). I already have this function:</p>
<pre><code>ostream &amp; operator&lt;&lt;(ostream &amp; o, const T &amp; t) /* note the ostream vs wostream */
</code></pre>
<p>I would like to re-use (build uppon a third party narrow strings library), but I don't have the wostream equivalent, and don't want to rewrite one.</p>
<p>What are my options ?</p>
",https://stackoverflow.com/questions/65415332/using-visual-studio-native-c-unit-testing-framework-with-strings-instead-of-wi,"['c++', 'unit-testing', 'visual-studio-2019', 'vs-unit-testing-framework']",438,True,3,1
How to mock a gremlin server or create in-memory graph for unit testing?,"<p>I'm using Gremlin.Net and I want to write unit tests for the functions that query the database. I want the queries to run on a mock data, to see if the result is being converted correctly to my desired format, especially with <code>Traverser.Object</code> that has a <code>dynamic</code> type.</p>

<p>Is there any way I can achieve this? Maybe run a server in code or have an in-memory instance of graph.</p>

<p>Here's a toy example:</p>

<pre class=""lang-cs prettyprint-override""><code>var query = graphTraversalSource.V(leafIds).As(""leaf"")
                .Emit(__.HasLabel(""root""))
                .As(""root"")
                .Repeat(
                    __.InE(""related_to"").OtherV()
                    .SimplePath())
                .Dedup()
                .Select&lt;Vertex&gt;(""leaf"", ""root"")
                .By(__.ValueMap&lt;string, string&gt;(true));

var res = new List&lt;MyFormat&gt;();
foreach (var t in query.Traversers)
{
    var leafInfo = t.Object[""leaf""];
    var rootInfo = t.Object[""root""];

    var tmp = new MyFormat
    {
        LeafId = leafInfo[T.Id],
        LeafLabel = leafInfo[T.Label],
        LeafProperty = leafInfo[""some_property""][0],
        RootId = rootInfo[T.Id],
        RootProperty = rootInfo[""some_other_propert""][0]
    };

    res.Add(tmp);
}

return res;
</code></pre>

<p>In the example above, <code>leafInfo</code> and <code>rootInfo</code> have <code>dynamic</code> types, so having this function run against a test graph could assert that those variables are used correctly, e.g. <code>leafInfo[""some_property""][0]</code> is assignable to <code>MyFormat.LeafProperty</code></p>
",https://stackoverflow.com/questions/60840508/how-to-mock-a-gremlin-server-or-create-in-memory-graph-for-unit-testing,"['c#', '.net', '.net-core', 'gremlin']",2042,True,3,1
Kotlin unit testing high order function in data class fails when passing lambda argument,"<pre class=""lang-kotlin prettyprint-override""><code>data class DataSample(val name: String, val exec: () -&gt; Unit = {})
</code></pre>

<p>I am trying to understand why the following test would fail:</p>

<pre class=""lang-kotlin prettyprint-override""><code>@Test
fun `testing data fails`() {
    val dataOne = DataSample(""the_same"") {
    }
    val dataTwo = DataSample(""the_same"") {
    }
    assertEquals(dataOne, dataTwo)
}
</code></pre>

<p>and the following would pass:</p>

<pre class=""lang-kotlin prettyprint-override""><code>@Test
fun `testing data pass`() {
    val dataOne = DataSample(""the_same"")
    val dataTwo = DataSample(""the_same"")
    assertEquals(dataOne, dataTwo)
}
</code></pre>

<p>The test will pass when the lambda is omitted and it fails when one is provided.</p>
",https://stackoverflow.com/questions/61980257/kotlin-unit-testing-high-order-function-in-data-class-fails-when-passing-lambda,"['kotlin', 'junit', 'junit5']",230,True,3,1
How to create KStream with a static list of records for unit testing purpose,"<p>I'm trying to write unit tests for a class which's using Kafka streams, like this:</p>

<pre><code>KStream stream = streamBuilder.stream(topic)
stream.foreach((key, value) -&gt; {
    // do some data manipulations and validations
});
</code></pre>

<p>Is there some way to add unit tests for this by creating a KStream from static data, like this to get a stream of Strings :</p>

<pre><code>arrayList.stream();
</code></pre>
",https://stackoverflow.com/questions/62004979/how-to-create-kstream-with-a-static-list-of-records-for-unit-testing-purpose,"['java', 'spring-boot', 'unit-testing', 'apache-kafka', 'apache-kafka-streams']",543,True,2,1
Is it good practice that creating a new branch for unit testing in Git?,"<p>For example I have class <code>A</code> and I have <code>feature/A</code> branch for implementing class <code>A</code> . </p>

<p>Should I create a new feature branch like <code>feature/TestA</code> for implementing unit test of class <code>A</code> ? </p>

<p>Or should I implement unit tests of class <code>A</code> in same branch <code>feature/A</code>?</p>

<p>And what is best practice of this problem?</p>
",https://stackoverflow.com/questions/60184539/is-it-good-practice-that-creating-a-new-branch-for-unit-testing-in-git,"['java', 'git', 'unit-testing', 'git-branch']",1096,True,2,1
How do I test functions with different parameters using Unity Unit testing in C?,"<p>The function add_first(int n) adds a number to a linked list and it returns 0 if successful and -1 if not.</p>
<p>The test is good but I would like to test a wider variety of situations so to test more of the same function with different parameters.</p>
<p>If I modify test_add_first and add a parameter it gives me an error because MY_RUN_TEST and RUN_TEST will only accept &quot;myfunction(void)&quot;. Therefore I have to create individual functions for each number.</p>
<p>I have this code in my test.c file and I am using Unit testing - Unity as the title says.</p>
<pre><code>#define MY_RUN_TEST(func) RUN_TEST(func, 0)

ITEM *list = NULL;

void printList(struct ITEM *node) 
{
  if(node == NULL)
  {
    printf(&quot;list is empty&quot;);
  } 
    while (node != NULL) 
    { 
        printf(&quot;%d &quot;, node -&gt; value); 
        node = node-&gt;next; 
    } 
} 

void test_add_first_1()
{
  int ret;
  ret = add_first(&amp;list, 1);
  TEST_ASSERT_EQUAL(0, ret);
}

void setUp(void)
{
    // This is run before EACH test
}

void tearDown(void)
{
  // This is run after EACH test
  printList(list);
  printf(&quot;\n&quot;);
}

int main (int argc, char * argv[])
{
    
    
    UnityBegin();
   
    MY_RUN_TEST(test_add_first_1);
    
    return UnityEnd();
}

</code></pre>
<p>So my question to be more specific is there any way to test these as something like - MY_RUN_TEST(test_add_first(n)); - n being an integer?</p>
<p>If you find something else wrong at this piece of code please tell I am just starting with Unit Testing. :)</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/64404193/how-do-i-test-functions-with-different-parameters-using-unity-unit-testing-in-c,"['c', 'unit-testing']",1025,True,1,1
Unit testing a method which calls a method returning a page of an entitiy,"<p>I would like to test the following method, for the case when I know the underlying call to findAllByMerchantId() method returns a fixed number of results (a page with fixed number of entities). </p>

<pre><code>public ListBeneficiaryResponseDTO getBeneficiariesOfMerchant(Long merchantId, Integer page, Integer pageSize,
                                                             String sortDirection, String sortField) {

    // default we are setting to added on desc sort
    Sort sort = Sort.by(Sort.Direction.DESC,""addedOn"");
    if(sortField != null &amp;&amp; sortDirection != null) {
        sort = Sort.by(Sort.Direction.fromString(sortDirection),sortField);
    }

    Pageable pageRequest = PageRequest.of(page-1, pageSize, sort);
    Page&lt;Beneficiary&gt; pageOfBeneficiaries = beneficiaryRepository.findAllByMerchantId(merchantId, pageRequest);

    List&lt;BeneficiaryResponseDTO&gt; benResonseDtoList = new ArrayList&lt;BeneficiaryResponseDTO&gt;();

    for( Beneficiary ben: pageOfBeneficiaries.getContent()) {
        benResonseDtoList.add(this.getBeneficiaryResponseDTO(ben));
    }
    ListBeneficiaryResponseDTO formattedListBen = new ListBeneficiaryResponseDTO(pageOfBeneficiaries.getTotalPages(),pageOfBeneficiaries.getTotalElements(),pageOfBeneficiaries.getNumber(),benResonseDtoList);
    return formattedListBen;
}
</code></pre>

<p>How do I mock the response of findAllByMerchantId() call, to return a fixed number of results in a page?  </p>

<p>P.S. Beginner at unit testing..</p>
",https://stackoverflow.com/questions/61630500/unit-testing-a-method-which-calls-a-method-returning-a-page-of-an-entitiy,"['java', 'unit-testing', 'mockito']",66,True,1,2
How to make a testable wrapper around Threading.Timer and replace it when unit testing?,"<p>I am struggling more than one day already with testing of my <code>System.Threading.Timer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period);</code> overload.</p>

<p>Basing on <a href=""https://stackoverflow.com/a/2367701/12603542"">this solution</a> I created my <strong>ThreadingTimer</strong>, <strong>FakeTimer</strong>, that implements <strong>ITimer</strong>:</p>

<pre><code>public interface ITimer
    {
        bool Change(int dueTime, int period);
        bool IsDisposed { get; }

        void Dispose();
    }


public class ThreadingTimer : ITimer, IDisposable
    {
        private Timer _timer;

        public ThreadingTimer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
        {
            _timer = new Timer(callback, state, dueTime, period);
        }

        public bool IsDisposed { get; set; }

        public void Dispose()
        {
            IsDisposed = true;
            Dispose();
            GC.SuppressFinalize(this);
        }


        public bool Change(int dueTime, int period)
        {
            _timer.Change(dueTime, period);

            return true;
        }
    }

public class FakeTimer : ITimer
    {
        private object state;

        public FakeTimer(TimerCallback callback, object state)
        {
            this.state = state;
        }

        public bool IsDisposed { get; set; }

        public bool Change(int dueTime, int period)
        {
            return true;
        }

        public void Dispose()
        {
            IsDisposed = true;
            Dispose();
            GC.SuppressFinalize(this);
        }
    }
</code></pre>

<p>In my service class I want to make usage of my <strong>ThreadingTimer</strong>:</p>

<pre><code>public ITimer Timer { get; set; }
private void StartUpdates()
        {
            Task.Run(() =&gt;
            {
                Timer = new ThreadingTimer(StartUpdatingVessels, null, TimeSpan.Zero, TimeSpan.FromHours(24));

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

<p>BUT when it comes to unit testing, I have no idea and understanding how to make usage and advantage of implementing of <strong>ITimer</strong> in my <strong>FakeTimer</strong>. Because if in my test will be called method <code>StartUpdates()</code>, new instance of <strong>ThreadingTimer</strong> will be created, even if already <strong>Timer</strong> prop has assigned <strong>FakeTimer</strong>:</p>

<pre><code>[Fact]
        public void SetUpdatingStarted_CalledWhenUpdatingAlreadyStarted_DisposesTimer()
        {
            _timedUpdateControl.Timer = new FakeTimer(CallbackTestMethod, null);
            bool intendedToStartUpdates = false;

            _timedUpdateControl.StartOrStopUpdates(intendedToStartUpdates); //that methid calls private method StartUpdates() and creates instance for ITimer

            //assert something
        }
</code></pre>

<p>How hould I mock it there? (I am using <strong>Moq</strong> framework in test project).</p>
",https://stackoverflow.com/questions/62331381/how-to-make-a-testable-wrapper-around-threading-timer-and-replace-it-when-unit-t,"['c#', 'unit-testing', 'timer', 'moq', 'wrapper']",540,True,1,1
how to do unit testing of classes which implement the ArcGIS API for Angular?,"<p>I'm building an Angular 8 application using the esri-loader and I'm really struggling with trying figure out the best way to mock ArcGIS JS API dependencies in my tests. I have come across very little sample code for applications built with frameworks other than dojo that use the ArcGIS JS API and also contain meaningful unit tests.  <strong>Is anyone out there doing this successfully and able to provide some guidance?</strong></p>
<p>For example, say I have a MapComponent class that looks like this:</p>
<pre><code>export class MapComponent {
mapView: MapView;

public async initializeMap(lat: number, lon: number, zoom: number) {
const [Map, MapView] = await loadModules(['esri/Map', 'esri/views/MapView']);

this.mapView = new MapView({
   zoom: zoom,
   center: [lat, lon]
  map: new Map({
    basemap: 'streets'
  })
});
}

public async addPointToMap(lat: number, lon: number) {
const [Graphic] = await loadModules(['esri/Graphic']);
 
 const point = {
   type: &quot;point&quot;,
   longitude: lon,
   latitude: lat
 };

 const markerSymbol = {
   type: &quot;simple-marker&quot;,
   color: [226, 119, 40],
   outline: {
      color: [255, 255, 255],
      width: 2
   }
 };

 const pointGraphic = new Graphic({
   geometry: point,
   symbol: markerSymbol
 });
 
 this.mapView.graphics.add(pointGraphic);
 }
}
</code></pre>
<p>I want to test the initializeMap() and addPointToMap() functions, but what is the best way to do this without actually making an http request to get the required API modules and creating concrete instances of each class I need?  A test class might look like this:</p>
<pre><code>describe('MapComponent', () =&gt; {
let fixture: ComponentFixture&lt;MapComponent&gt;;
let component;

beforeEach(async () =&gt; {
 TestBed.configureTestingModule({
  declarations: [MapComponent],
}).compileComponents();
 
fixture = TestBed.createComponent(MapComponent);
component = fixture.debugElement.componentInstance;
});

it('should initialize map', async () =&gt; {
 // calling this function will fetch the ArcGIS JS API dependencies
// and create concrete instances of Map and MapView objects - need
// to mock these      
await component.initializeMap();
expect(component.mapService.mapView).toBeTruthy();
});

it('should add a point to the map', async () =&gt; {
await component.addPointToMap(32.7, -117.1);
// assert point is created in component.mapService.mapView object
   });
 });
</code></pre>
",https://stackoverflow.com/questions/64307257/how-to-do-unit-testing-of-classes-which-implement-the-arcgis-api-for-angular,"['angular', 'arcgis', 'esri', 'arcgis-js-api']",694,False,1,1
Returning 2 different values using using a mock service while unit testing in Angular,"<p>Summary of the issue :</p>

<p><strong>How to call multiple values using the same service inside the same test spec and check to see if it works exactly as in the component?</strong></p>

<p>I am using Angular7+.</p>

<p>Let there be a component ( say A ) with a service injected into it.</p>

<p>Suppose , there is a <strong>getNumber</strong> function in the same <strong>service</strong> with 2 parameters namely <strong>( ""Key"" , ""Value"" )</strong> where ""Key"" can only be either <strong>num1</strong> or <strong>num2</strong> and ""Value"" can be any <strong>integer</strong>.</p>

<p>This function returns an object in this format : <strong>{ ""Key"" : num1 or num2 , ""Value"" : number }</strong> and this object is stored in another object ( say <strong>Total</strong> ) as its elements. Example : </p>

<pre><code>export class A implements OnInit{
 Total={""sum"":[""num1"",""num2""],""amount"":0};

 constructor(private service: SomeService) {}
    ngOnInit(){
        this.loadFunc();
    }

    private loadFunc(){
        this.service.getNumber(""num1"",12).subscribe(res =&gt;{
                Total[res.Key] = res.Value;
        },err=&gt;{
            console.log(err);
        });

        this.service.getNumber(""num2"",13).subscribe(res =&gt;{
                Total[res.Key] = res.Value;
        },err=&gt;{
            console.log(err);
        });

        this.calculate();
    }

    private calculate(){
        //For elements in Total.sum array iterate over them and store the value in any other key say amount.
        for(const keys of Total[""sum""]){
            if(Total[keys]){
                Total[""amount""] += Total[keys];
            }
        }
        console.log(Total[""amount""]);      // Outputs to 25
    }
}

So Total would become : 
Total = { ""num1"":12 , ""num2"":13 ,""sum"":[""num1"",""num2""],""amount"":25};
</code></pre>

<p>Now in <strong>unit testing</strong> the component with the service, i have a mockService stub with a getNumber function and i am doing something like this :</p>

<pre><code>mockServiceStub = jasmine.createSpyObj(['getNumber']); // done before testbed.createComponent()

// Inside Test
mockServiceStub.getNumber.and.returnValue(of({""Key"":""num1"", ""Value"":12}));
fixture.ngOnInit();
console.log(component.Total.amount); // outputs 12

mockServiceStub.getNumber.and.returnValue(of({""Key"":""num2"", ""Value"":13}));
fixture.ngOnInit();
console.log(component.Total.amount); // outputs 13
expect(component.Total.sum).toEqual(25); // throws error 'Expected 13 to equal 25'
</code></pre>

<p>I actually wanted both the values to combine i.e in my test,
i first gave a return value of 12 with "" num1 "" as key and then 13 with "" num2 "" as key, and i expected the output to be 25 ( 12 + 13 ).</p>
",https://stackoverflow.com/questions/61719672/returning-2-different-values-using-using-a-mock-service-while-unit-testing-in-an,"['angular', 'unit-testing', 'observable']",4117,True,1,2
Unit testing RestController that does return a strongly typed object not within a ResponseEntity,"<p>I have the following example of controller:</p>

<pre><code>@RequestMapping(value = ""/pickcard"", method = RequestMethod.POST)
    public Card pickCard(@RequestParam String name) {
        return _deckManager.pickCardForPlayer(name);
    }
</code></pre>

<p>as you can see this endpoint returns a Card not incapsulated in a response entity, but I still would like to assess that the result of the endpoint is successfull, for example a 200.
In my unit test I cannot say that:</p>

<pre><code>var response = deckController.pickCard(""Test"");
assertThat(response.getStatusCodeValue()).isEqualTo(200);
</code></pre>

<p>because indeed the response is not of type ResponseEntity. How can I do this assertion? Thanks in advance!</p>
",https://stackoverflow.com/questions/59593999/unit-testing-restcontroller-that-does-return-a-strongly-typed-object-not-within,"['java', 'spring', 'unit-testing', 'assert', 'spring-restcontroller']",120,False,1,1
How to incorporate both integration and unit testing in one test file using Cypress,"<p>I'm looking for best practices for setting up unit and integration tests using cypress for my react application. I wanted to know if we can combine both integration and unit testing(component based testing) in a single file. Or is there any better approach anyone can provide if we want to implement both IT and UT for our application using Cypress.</p>
",https://stackoverflow.com/questions/63932453/how-to-incorporate-both-integration-and-unit-testing-in-one-test-file-using-cypr,"['reactjs', 'unit-testing', 'integration-testing', 'cypress']",1784,False,1,2
Code coverage of SQL unit testing with tSQLt tool and integrating in Sonarqube dashboard,"<p>We're using tSQLt for SQL unit test cases and integrated with Azure DevOps for build pipeline using Redgate SQL Change Automation:build task.
Now I got result as &quot;TestResults.junit.xml&quot; and published to Tests summary. But code coverage is not showing. We want to show the this code coverage and want to integrate this coverage with in Sonarqube dashboard.</p>
<p>Kindly suggest on how could we do this. Thanks.</p>
",https://stackoverflow.com/questions/64714389/code-coverage-of-sql-unit-testing-with-tsqlt-tool-and-integrating-in-sonarqube-d,"['sql', 'sonarqube', 'tsqlt']",299,False,1,0
How to mock patch the Serializer.is_valid() method when unit testing in Django Rest Framework,"<p>I want to be able to unit test a view without connecting to the db, i can mock patch the User.save() method but a don't know how to patch serializer.is_valid() properly. It looks like is_valid method requires db connection to validate fields or something like that. Is there a way we can do this?</p>

<p>I'm using django-pytest and pytest-mock</p>

<p>here is the view a want to test</p>

<pre class=""lang-py prettyprint-override""><code>class RegistrationViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (AllowAny,)
    serializer_class = RegistrationSerializer

    def create(self, request):
        user = request.data.get('user', {})
        serializer = self.serializer_class(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
</code></pre>

<p>here is my serializer </p>

<pre class=""lang-py prettyprint-override""><code>class RegistrationSerializer(serializers.ModelSerializer):
    """"""Serializers registration request and creates a new user.""""""

    password = serializers.CharField(
        max_length=128,
        min_length=8,
        write_only=True   # can not be read by the client
    )
    token = serializers.CharField(max_length=255, read_only=True)

    class Meta:
        model = User
        fields = ['email', 'username', 'password', 'token']

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)
</code></pre>

<p>Here is my view test so far</p>

<pre class=""lang-py prettyprint-override""><code>class TestRegistrationViewSet:
    """"""
    Test cases for registrating user
    """"""

    def test_register_user_success(self, rf, mocker):
        url = reverse('registration-list')
        data = {
            ""user"": {
                'username': 'user1',
                'email': ""email@cookie.com"",
                'password': 'user1pass'
            }
        }
        request = rf.post(url, data=data, content_type='application/json')

        mocker.patch.object(User, 'save')
        response = RegistrationViewSet.as_view({'post': 'create'})(request).render()
        assert response.status_code == status.HTTP_201_CREATED
</code></pre>

<p>This is the error traceback i'm getting</p>

<pre class=""lang-py prettyprint-override""><code>
repostery\authentication\views.py:21: in create
    serializer.is_valid(raise_exception=True)
.venv\lib\site-packages\rest_framework\serializers.py:234: in is_valid
    self._validated_data = self.run_validation(self.initial_data)
.venv\lib\site-packages\rest_framework\serializers.py:433: in run_validation
    value = self.to_internal_value(data)
.venv\lib\site-packages\rest_framework\serializers.py:490: in to_internal_value
    validated_value = field.run_validation(primitive_value)
.venv\lib\site-packages\rest_framework\fields.py:830: in run_validation
    return super().run_validation(data)
.venv\lib\site-packages\rest_framework\fields.py:566: in run_validation
    self.run_validators(value)
.venv\lib\site-packages\rest_framework\fields.py:588: in run_validators
    validator(value, self)
.venv\lib\site-packages\rest_framework\validators.py:73: in __call__
    if qs_exists(queryset):
.venv\lib\site-packages\rest_framework\validators.py:21: in qs_exists
    return queryset.exists()
.venv\lib\site-packages\django\db\models\query.py:777: in exists
    return self.query.has_results(using=self.db)
.venv\lib\site-packages\django\db\models\sql\query.py:538: in has_results
    return compiler.has_results()
.venv\lib\site-packages\django\db\models\sql\compiler.py:1121: in has_results
    return bool(self.execute_sql(SINGLE))
.venv\lib\site-packages\django\db\models\sql\compiler.py:1149: in execute_sql
    cursor = self.connection.cursor()
.venv\lib\site-packages\django\utils\asyncio.py:26: in inner
    return func(*args, **kwargs)
.venv\lib\site-packages\django\db\backends\base\base.py:260: in cursor
    return self._cursor()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = &lt;django.db.backends.postgresql.base.DatabaseWrapper object at 0x00000218938FA670&gt;, name = None

    def _cursor(self, name=None):
&gt;       self.ensure_connection()
E       RuntimeError: Database access not allowed, use the ""django_db"" mark, or the ""db"" or ""transactional_db"" fixtures to enable it.

.venv\lib\site-packages\django\db\backends\base\base.py:236: RuntimeError
</code></pre>
",https://stackoverflow.com/questions/62045565/how-to-mock-patch-the-serializer-is-valid-method-when-unit-testing-in-django-r,"['python', 'django', 'django-rest-framework', 'pytest']",2310,True,1,3
Patch a dataclass attribute which is dynamically generated in its dependency in unit testing,"<p>I am new to Unit testing. I have used mocking, patching in the past but the case I have is a little bit complicated for me to create unit tests.</p>
<p>So I have a file: <code>parent.py</code> with the following data class</p>
<pre><code>import multiprocessing
from dataclasses import dataclass

@dataclass
class ParentClass:
    cpu_count: int = multiprocessing.cpu_count() 
</code></pre>
<p>I have another module <code>child.py</code> with the following data class</p>
<pre><code>from stackoverflow.parent import ParentClass
from dataclasses import dataclass

@dataclass
class ChildClass(ParentClass):
      some_attribute_1: int = 1
      some_attribute_2: int = 2
      ....
</code></pre>
<p>Finally, I have a third module <code>actual_function.py</code> that uses these data classes.</p>
<pre><code>from stack_overflow.child import ChildClass


def get_cpu_count_and_attributes(cc: ChildClass):
    return cc.cpu_count, cc.some_attribute_1 
</code></pre>
<p>Here, I want to unit test <code>print_cpu_count_and_attributes</code> function. How does patching work here? I created the following test case and it fails. The cpu_count in my system is 16 but I want to mock it with return value 8 so that it works on other machines with different number of cores</p>
<pre><code>from unittest import mock
from stack_overflow.actual_function import *
from stack_overflow.child import ChildClass


@mock.patch('stack_overflow.parent.multiprocessing.cpu_count', return_value=8)
def test_print_cpu_count_and_attributes():
    cc = ChildClass()
    assert get_cpu_count_and_attributes(cc) == (8, 1)
</code></pre>
<p>Here is the folder structure.</p>
<pre><code>stackoverflow
├── __init__.py
  ├── actual_function.py
  ├── child.py
  ├── parent.py
  └── test_function.py
</code></pre>
",https://stackoverflow.com/questions/64049192/patch-a-dataclass-attribute-which-is-dynamically-generated-in-its-dependency-in,"['python', 'unit-testing', 'testing', 'inheritance', 'python-dataclasses']",1852,True,1,1
"Angular unit testing ,&quot;You need to include some adapter that implements __karma__.start method!&quot;","<p>I am installing karma for my project,I did the following things but when I run 'npm run test-karma', then I got the following error,</p>

<blockquote>
  <p>""You need to include some adapter that implements <strong>karma</strong>.start method!""</p>
</blockquote>

<p>Package.json,</p>

<pre><code>       ""jasmine"": ""^3.3.1"",
       ""jasmine-core"": ""^3.1.0"",
        ""jasmine-spec-reporter"": ""~4.2.1"",
        ""karma"": ""~4.0.0"",
        ""karma-chrome-launcher"": ""~2.2.0"",
        ""karma-coverage-istanbul-reporter"": ""~2.0.1"",
       ""karma-jasmine"": ""~1.1.2"",
</code></pre>

<p>Karma.conf.js,</p>

<pre><code>const { join } = require('path');
const { constants } = require('karma');

module.exports = () =&gt; {
 return {
  basePath: '',
  frameworks: ['jasmine', '@angular-devkit/build-angular'],
  plugins: [
  require('karma-jasmine'),
  require('karma-spec-reporter'),
  require('karma-chrome-launcher'),
  require('karma-jasmine-html-reporter'),
  require('karma-mocha-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: {
  reports: ['json-summary', 'html', 'lcovonly', 'text-summary'],
  fixWebpackSourcePaths: true,
  thresholds: {
    emitWarning: false,
    global: {
      statements: 100,
      lines: 100,
      branches: 100,
      functions: 100
    }
  }
},
// reporters: ['mocha', 'spec', 'progress', 'kjhtml'],
reporters: ['mocha', 'kjhtml'],
mochaReporter: {

  colors: {
     success: 'green',
     info: 'bgGreen',
     warning: 'cyan',
     error: 'red'
  },
   symbols: {
    success: '👍',
    info: 'ℹ️',
    warning: '☣️',
    error: '❌'
  }
},
   port: 9876,
  colors: true,
 autoWatch: true,
 browsers: ['Chrome'],
customLaunchers: {
  Chrome_without_security: {
    base: 'Chrome',
    flags: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-gpu',
      '--remote-debugging-port=9222'
    ]
  }
},
singleRun: true
};
};
</code></pre>

<p>Test.ts,</p>

<pre><code>import 'core-js';
import 'rxjs/Rx';
import 'zone.js/dist/zone';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';
import { TestBed } from '@angular/core/testing';

import {
   BrowserDynamicTestingModule,
   platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

TestBed.initTestEnvironment(
  BrowserDynamicTestingModule,

 platformBrowserDynamicTesting()
  );

const testsContext: any = require.context('./', true, /\.spec/);

testsContext.keys().forEach(testsContext);
</code></pre>

<p>I am new to this.</p>
",https://stackoverflow.com/questions/60612127/angular-unit-testing-you-need-to-include-some-adapter-that-implements-karma,"['javascript', 'angularjs', 'jasmine', 'karma-runner', 'angular-unit-test']",575,False,1,0
Having a weird issue with Spring-boot + Rest Controller + Post Request + Kotlin + Unit testing,"<h2>The build file</h2>
<pre><code>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id(&quot;org.springframework.boot&quot;) version &quot;2.3.3.RELEASE&quot;
    id(&quot;io.spring.dependency-management&quot;) version &quot;1.0.9.RELEASE&quot;
    id(&quot;com.google.cloud.tools.jib&quot;) version &quot;2.5.0&quot;
    kotlin(&quot;jvm&quot;) version &quot;1.4.0&quot;
    kotlin(&quot;plugin.spring&quot;) version &quot;1.4.0&quot;
    kotlin(&quot;plugin.jpa&quot;) version &quot;1.4.0&quot;
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(&quot;org.springframework.boot:spring-boot-starter-data-jpa&quot;)
    implementation(&quot;org.springframework.boot:spring-boot-starter-data-rest&quot;)
    implementation(&quot;org.springframework.boot:spring-boot-starter-web&quot;)
    implementation(&quot;org.springframework.boot:spring-boot-starter-activemq&quot;)
    implementation(&quot;com.fasterxml.jackson.module:jackson-module-kotlin&quot;)
    implementation(&quot;org.flywaydb:flyway-core&quot;)
    implementation(&quot;org.jetbrains.kotlin:kotlin-reflect&quot;)
    implementation(&quot;org.jetbrains.kotlin:kotlin-stdlib-jdk8&quot;)
    developmentOnly(&quot;org.springframework.boot:spring-boot-devtools&quot;)
    runtimeOnly(&quot;org.postgresql:postgresql&quot;)
    testImplementation(&quot;org.springframework.boot:spring-boot-starter-test&quot;) {
        exclude(group = &quot;org.junit.vintage&quot;, module = &quot;junit-vintage-engine&quot;)
    }
    testImplementation(&quot;com.h2database:h2:1.4.200&quot;)
}

tasks.withType&lt;Test&gt; {
    useJUnitPlatform()
}

tasks.withType&lt;KotlinCompile&gt; {
    kotlinOptions {
        freeCompilerArgs = listOf(&quot;-Xjsr305=strict&quot;)
        jvmTarget = &quot;14&quot;
    }
}
</code></pre>
<h2>The controller</h2>
<pre><code>@RestController
@RequestMapping(&quot;/notification&quot;)
class NotificationResource(
    private val jobService: JobService
) {
    @PostMapping(&quot;/enqueue-mobile&quot;, produces = [APPLICATION_JSON_VALUE], consumes = [APPLICATION_JSON_VALUE])
    @ResponseStatus(ACCEPTED)
    fun enqueueMobile(@Valid @RequestBody mobile: Mobile): List&lt;Job&gt; = jobService.create(mobile)

    @GetMapping(&quot;/job-status/{id}&quot;, produces = [APPLICATION_JSON_VALUE])
    @ResponseStatus(OK)
    fun jobStatus(@Valid @PathVariable id: UUID): Job = jobService.fetch(id).get()
}

data class Mobile(
    val ids: List&lt;Long&gt;,
    val message: String
)
</code></pre>
<h2>Unit testing file</h2>
<pre><code>@SpringBootTest
@ActiveProfiles(&quot;test&quot;)
@AutoConfigureMockMvc
class NotificationResourceMobileTests {
    @Autowired
    lateinit var mockMvc: MockMvc

    @Test
    fun `with correct payload having one mobile id in a list and message - request returns http ok and response`() {
        val mobile = Mobile(ids = listOf&lt;Long&gt;(100, 101, 102), message = &quot;test&quot;)
        mockMvc.perform(post(urlPath).contentType(APPLICATION_JSON_VALUE).content(mobile.asJsonString()))
            .andDo(print())
            .andExpect(status().isAccepted)
    }

    companion object {
        const val urlPath = &quot;/notification/enqueue-mobile&quot;
    }
}
</code></pre>
<h2>The Request</h2>
<pre><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /notification/enqueue-mobile
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Content-Length:&quot;38&quot;]
             Body = {&quot;ids&quot;:[100,101,102],&quot;message&quot;:&quot;test&quot;}
    Session Attrs = {}

Handler:
             Type = com.notification.resource.NotificationResource
           Method = com.notification.resource.NotificationResource#enqueueMobile(Mobile)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.util.NestedServletException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Content-Type:&quot;application/json&quot;]
     Content type = application/json
             Body = {&quot;timestamp&quot;:&quot;2020-09-04T23:51:49.609645&quot;,&quot;status&quot;:400,&quot;error&quot;:&quot;Bad Request&quot;,&quot;message&quot;:&quot;'java.util.List com.notification.resource.Mobile.getIds()'&quot;,&quot;trace&quot;:&quot;java.lang.NoSuchMethodError: 'java.util.List com.notification.resource.Mobile.getIds()'\n\tat com.notification.service.JobService$create$1.invoke(JobService.kt:29)\n\tat com.notification.service.JobService$create$1.invoke(JobService.kt:19)\n\tat com.notification.resource.NotificationResource.enqueueMobile(NotificationResource.kt:25)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:652)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\n\tat org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:733)\n\tat org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:183)\n\tat com.notification.resource.NotificationResourceMobileTests.with correct payload having one mobile id in a list and message - request returns http ok and response(NotificationResourceMobileTests.kt:134)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)\n\tat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1510)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1510)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)\n\tat org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)\n\tat org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)\n\tat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)\n\tat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)\n\tat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)\n\tat org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\n\tat org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)\n\tat org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)\n\tat com.sun.proxy.$Proxy2.stop(Unknown Source)\n\tat org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\n\tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)\n\tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)\n\tat org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)\n\tat org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)\n\tat org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)\n\tat org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)\n\tat java.base/java.lang.Thread.run(Thread.java:832)\n&quot;,&quot;path&quot;:&quot;uri=/notification/enqueue-mobile&quot;}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /notification/enqueue-mobile
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Content-Length:&quot;38&quot;]
             Body = {&quot;ids&quot;:[100,101,102],&quot;message&quot;:&quot;test&quot;}
    Session Attrs = {}

Handler:
             Type = com.notification.resource.NotificationResource
           Method = com.notification.resource.NotificationResource#enqueueMobile(Mobile)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.util.NestedServletException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Content-Type:&quot;application/json&quot;]
     Content type = application/json
             Body = {&quot;timestamp&quot;:&quot;2020-09-04T23:51:49.609645&quot;,&quot;status&quot;:400,&quot;error&quot;:&quot;Bad Request&quot;,&quot;message&quot;:&quot;'java.util.List com.notification.resource.Mobile.getIds()'&quot;,&quot;path&quot;:&quot;uri=/notification/enqueue-mobile&quot;}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Status expected:&lt;202&gt; but was:&lt;400&gt;
Expected :202
Actual   :400
</code></pre>
<blockquote>
<p>Why do I get NoSuchMethodError - when I have the field in the <code>data class</code>. Note: I can test the feature after running the app and using Postman. The same fails in unit-testing.
The unit-testing with <code>mockmvc</code> is not working as expected. The same works fine for <code>get</code> methods. Any input?</p>
</blockquote>
<pre><code>java.lang.NoSuchMethodError: 'java.util.List com.notification.resource.Mobile.getIds()'
    at com.notification.service.JobService$create$1.invoke(JobService.kt:29)
    at com.notification.service.JobService$create$1.invoke(JobService.kt:19)
    at com.notification.resource.NotificationResource.enqueueMobile(NotificationResource.kt:25)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code></pre>
",https://stackoverflow.com/questions/63749303/having-a-weird-issue-with-spring-boot-rest-controller-post-request-kotlin,"['spring-boot', 'kotlin', 'spring-boot-test', 'mockmvc']",470,False,0,0
Unit Testing Service with Unit of Work with xunit .NET Core 3.1 and Moq,"<p>being fairly new to xUnit, I have an application that uses the Unit of Work pattern to return data to a service and I'm trying to unit test this service.</p>

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

<pre><code> public async Task&lt;IEnumerable&lt;CatDto&gt;&gt; GetActiveCatsAsync()
    {
        var catList = new List&lt;CatDto&gt;();
        var catEFList = await _uow.Repository&lt;Cat&gt;().GetActiveCatsAsync();
        catList.AddRange(catEFList.Select(c =&gt; new CatDto
        {
            CatId = c.CatId,
            CatName = c.CatName,
            DisplayOrd = c.DisplayOrd
        }));


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

<p>And here is the extension that this service calls:</p>

<pre><code> public static async Task&lt;List&lt;Cat&gt;&gt; GetActiveCatsAsync(this IRepository&lt;Cat&gt; repository)
    {
        return await repository.AsQueryableRepo().Items.Where(c =&gt;c.IsActive == true).OrderBy(c=&gt;c.DisplayOrd).ToListAsync();
    }
}
</code></pre>

<p>Here is the Interface used by the extension:</p>

<pre><code> internal static IQueryableRepository&lt;T&gt; AsQueryableRepo&lt;T&gt;(this IRepository&lt;T&gt; repository) where T : class
    {
        return (IQueryableRepository&lt;T&gt;)repository;
    }
</code></pre>

<p>Here is the concrete unit of work class:</p>

<pre><code> public class SQLUnitOfWork&lt;TContext&gt; : BaseUnitOfWork, ISQLUnitOfWork&lt;TContext&gt;
    where TContext : IDbContext, IDisposable
{
    public SQLUnitOfWork(TContext context) : base(context)
    {
    }
}
</code></pre>

<p>And here is where I am with a single unit test so far:</p>

<pre><code>  [Fact]
    public void GetActiveCatsAsync_ReturnsTypeIEnumerableCatDto()
    {
        var mockLogger = new Mock&lt;ILogger&lt;CatService&gt;&gt;();
        var mockUoW = new Mock&lt;ISQLUnitOfWork&gt;();

        var catServ = new CatService(mockLogger.Object, mockUoW.Object);

        var result = catServ.GetActiveCatsAsync();

        Assert.IsType&lt;Task&lt;IEnumerable&lt;CatDto&gt;&gt;&gt;(result);
    }
</code></pre>

<p>This test actually passes, but obviously the ""result"" variable has no data in it because there is no setup for the mocks. I also tried setting up:</p>

<pre><code> var mockRepo = new Mock&lt;IRepository&lt;Cat&gt;&gt;();
</code></pre>

<p>But this doesn't allow me to get at the extensions methods above. It doesn't show me the ""asQueryableRepo()"" method to provide a return value for. So I'm not sure how I can mock the return data, which would be a simple Cat object with three properties shown in the service call. I have also tried using xUnit's .ReturnAsync() and Task.FromResult() functionality.</p>

<p>After a few searches, I tried implementing xUnit.DependencyInjection, but that requires configuration in the test project's Startup.cs file. My test project (created with the Visual Studio xUnit project template) doesn't have a Startup.cs file. Did I use the wrong template?</p>

<p>I have also seen something similar to the following used:    </p>

<pre><code>      scope = new CustomWebApplicationFactory&lt;Startup&gt;().Server.Host.Services.CreateScope();
service = scope.ServiceProvider.GetRequiredService&lt;IDashboardService&gt;();
context = scope.ServiceProvider.GetRequiredService&lt;DTBContext&gt;();
</code></pre>

<p>Which also seems to reference a startup class, so I really haven't been able to get this approach working either. Do I need to start again with a project that includes a Startup.cs folder? Or can I Unit Test the code above without it? I'm still researching this, but so far I cannot find a way to mock the dependencies of the service calls and the Unit of Work elements.</p>

<p>Any suggestions or advice is greatly appreciated! Thank you!</p>

<p>UPDATE: I think I now understand the xUnit.DependencyInjection, so I added a startup.cs class, and added the references referred to on their GitHub page. I also had to install Microsoft.Extensions.Hosting package to take care of a ""does not have an implementation"" error and now my project has a startup and the test that passed above now passes. I'm hoping that I can now handle dependencies within the testing project, but I'll find out.</p>
",https://stackoverflow.com/questions/62158750/unit-testing-service-with-unit-of-work-with-xunit-net-core-3-1-and-moq,"['c#', 'unit-testing', 'moq', 'xunit', 'unit-of-work']",3002,True,0,1
Maven compile and provided scopes for unit testing of JPMS module with surefire-plugin,"<p>Trying to test my maven project (one parent pom and several modules (jpms modules)) I got annoying <code>Error occurred in starting fork</code>:</p>

<pre><code>Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M4:test (default-test) on project com.foo.plugin: There are test failures.
...
Error occurred in starting fork, check output in log
Process Exit Code: 1
org.apache.maven.surefire.booter.SurefireBooterForkException: The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
...
Error occurred in starting fork, check output in log
Process Exit Code: 1
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:690)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:285)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:248)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1217)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1063)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:889)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginM
</code></pre>

<p>A solution I found, for example, <a href=""https://stackoverflow.com/a/53440403/5057736"">here</a> suggested to set <code>&lt;forkCount&gt;0&lt;/forkCount&gt;</code> in surefire-plugin configuration. However, such solution doesn't allow to run tests on module-path, so I went to this surefire <a href=""https://issues.apache.org/jira/browse/SUREFIRE-1262"" rel=""nofollow noreferrer"">issue</a>.</p>

<p>Surefire developers (thanks to them) found out that the reason was in maven scope of the dependencies I used. In my project I have:</p>

<pre><code>         &lt;dependency&gt;
            &lt;groupId&gt;jakarta.ws.rs&lt;/groupId&gt;
            &lt;artifactId&gt;jakarta.ws.rs-api&lt;/artifactId&gt;
            &lt;version&gt;2.1.6&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt; &lt;!-- NOTE IT --&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;jakarta.xml.bind&lt;/groupId&gt;
            &lt;artifactId&gt;jakarta.xml.bind-api&lt;/artifactId&gt;
            &lt;version&gt;2.3.2&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt; &lt;!-- NOTE IT --&gt;
        &lt;/dependency&gt;
</code></pre>

<p>And they said it had to be:</p>

<pre><code>          &lt;dependency&gt;
            &lt;groupId&gt;jakarta.ws.rs&lt;/groupId&gt;
            &lt;artifactId&gt;jakarta.ws.rs-api&lt;/artifactId&gt;
            &lt;version&gt;2.1.6&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt; &lt;!-- NOTE IT --&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;jakarta.xml.bind&lt;/groupId&gt;
            &lt;artifactId&gt;jakarta.xml.bind-api&lt;/artifactId&gt;
            &lt;version&gt;2.3.2&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt; &lt;!-- NOTE IT --&gt;
        &lt;/dependency&gt;
</code></pre>

<p>And when I changed the scope my project was tested by surefire without problems. Both dependencies <code>jakarta.ws.rs-api</code> and <code>jakarta.xml.bind-api</code> are JPMS modules and are <code>required</code> by my JPMS modules. </p>

<p>So the question, is the problem in my code (<code>provided</code> is wrong if I want to run my tests for my JPMS module) or the problem is in surefire plugin?</p>
",https://stackoverflow.com/questions/61407603/maven-compile-and-provided-scopes-for-unit-testing-of-jpms-module-with-surefire,"['java', 'maven', 'maven-surefire-plugin', 'java-module']",384,True,0,1
Ag-grid unit testing: check the content of a cell rendered by a CellRenderer,"<p>How is it possible to check the content of a cell that is rendered by a <code>CellRenderer</code> class?</p>
<p>(let's say we got a <code>CellRenderer</code> that gets as input a <code>Date</code> object and displayes it in some specified format. I would like to be able to check the final value.)</p>
<p><strong>Note:</strong> The Ag-grid <a href=""https://www.ag-grid.com/javascript-grid-testing-angular/#testing-user-supplied-components"" rel=""nofollow noreferrer"">documentation</a> provides only the way of testing with a <code>CellEditor</code>.</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/63217428/ag-grid-unit-testing-check-the-content-of-a-cell-rendered-by-a-cellrenderer,"['angular', 'unit-testing', 'jestjs', 'ag-grid', 'ag-grid-angular']",1801,True,-1,1
How to send POST request multipart/form-data field as array for unit testing?,"<p>I'm trying to make unit testing for my Go application that handles form data in multipart/form-data content type using gin (PostForm and PostFormArray) like</p>
<p><code>x, y := c.PostForm(&quot;x&quot;), c.PostFormArray(&quot;y&quot;)</code></p>
<p>I have no problem on making a form field which have non-array value (PostForm) with mime/multipart library which Go provides like this</p>
<pre><code>buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)

x, _ := w.CreateFormField(&quot;x&quot;)
x.Write([]byte(&quot;This is x value&quot;))

w.Close()
</code></pre>
<p>which PostForm handles perfectly, now I'm wondering if there is any way to send a multipart/form-data field with an array as its value like <code>[]string{&quot;this is y 1&quot;, &quot;this is y 2&quot;}</code> for it to work with gin's PostFormArray. Is it possible and how do I do it? Any help would be greatly appreciated. Thanks in advance!</p>
",https://stackoverflow.com/questions/63357842/how-to-send-post-request-multipart-form-data-field-as-array-for-unit-testing,"['unit-testing', 'go', 'multipartform-data', 'go-gin']",1857,True,0,1
This function can only be invoked from LINQ to Entities error during unit testing,"<p>Hi i have problem with testing my method. I mocking my repository as a DbSet. My unit test method look that:</p>

<pre><code>public void Can_change_quantity_of_product()
    {
        //przygotowanie
        var repo = CreateDbSetMock(new List&lt;Processor&gt;
        {
            new Processor{Product_ID = 1, Quantity = 20},
            new Processor{Product_ID = 2, Quantity = 5}
        });
        var target = new ProductContext();
        target.context.Processors = repo.Object;
        //działanie
        target.SellProduct(new OrderDetails { Product_ID = 1, Quantity = 5 });
        //Asercje
        Assert.AreEqual(target.TakeProcessors.ToList()[0].Quantity, 15);
    }
</code></pre>

<p>And i get this error here:</p>

<pre><code>public IEnumerable&lt;Product&gt; TakeProcessors  //Zwraca repozutorium procesorów jako lista klas Product.
    {
        get
        {
            return (from x in context.Processors
                    select new Product
                    {
                        ProductID = x.Product_ID,
                        Title = x.Title,
                        Price = x.Price,
                        Quantity = x.Quantity,
                        FDetail = SqlFunctions.StringConvert(x.Clock, 5, 1),
                        SDetail = SqlFunctions.StringConvert((double)x.Cores),
                        TDetail = SqlFunctions.StringConvert((decimal)x.Cache),
                        OrderDetails = x.OrderDetails,
                        Promoted = x.Promoted,
                        SoldPieces = x.OrderDetails.Count() == 0 ? 0 : x.OrderDetails.Sum(y =&gt; y.Quantity),
                        Category = ""Procesory""
                    }).ToList();
        }
    }
</code></pre>

<p>What's wrong I do?</p>
",https://stackoverflow.com/questions/62450581/this-function-can-only-be-invoked-from-linq-to-entities-error-during-unit-testin,"['c#', 'entity-framework', 'linq', 'unit-testing']",86,False,0,0
"I am Get starting with unit testing with NUnit, (doesn&#39;t run the test) Why?","<p>i am starting using unit testing in visual Studio. I'm reading the Microsoft Documantation about it: <a href=""https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2019"" rel=""nofollow noreferrer"">Get started with unit testing</a>, but when i run, doesn't run the test, and show this: Program, is inaccessible due to its protection level. I dont know what i have to do now.
Can u help.</p>
<p>This is my Hello World Program</p>
<pre><code>using System;

namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine(&quot;Hello World!&quot;);
        }
    }
}

</code></pre>
<p>Unit test with NUnit</p>
<pre><code>using NUnit.Framework;
using System.IO;
using System;

namespace HelloWorldTests
{
    public class Tests
    {
        private const string Expected = &quot;Hello World!&quot;;

        [SetUp]
        public void Setup()
        {
        }
        [Test]
        public void TestMethod1()
        {
            using (var sw = new StringWriter())
            {
                Console.SetOut(sw);
                demo.Program.Main();

                var result = sw.ToString().Trim();
                Assert.AreEqual(Expected, result);
            }
        }
    }
}

</code></pre>
<p>ERROR SHOW: Error CS0122: 'Program' is inaccessible due to its protection level (CS0122) (HelloWorldTests)</p>
",https://stackoverflow.com/questions/62961673/i-am-get-starting-with-unit-testing-with-nunit-doesnt-run-the-test-why,"['c#', 'visual-studio', 'unit-testing', 'nunit']",364,True,0,3
Spring Boot test API endpoint with unit testing should return 404 instead of 400,"<p>I have the following controller on my Spring Boot application, which is connected to a <code>MongoDB</code>:</p>

<pre><code>@RestController
@RequestMapping(""/experts"")
class ExpertController {
    @Autowired
    private  ExpertRepository repository;


    @RequestMapping(value = ""/"", method = RequestMethod.GET)
    public List&lt;Experts&gt; getAllExperts() {
        return repository.findAll();
    }

    @RequestMapping(value = ""/{id}"", method = RequestMethod.GET)
    public Experts getExpertById(@PathVariable(""id"") ObjectId id) {
        return repository.findBy_id(id);
    }
</code></pre>

<p>I am trying to test the the <code>get/id</code> endpoint on my test, which I expect to give back an 404 response as shown below:</p>

<pre><code> @Test
    public void getEmployeeReturn404() throws Exception {
        ObjectId id = new ObjectId();
        mockMvc.perform(MockMvcRequestBuilders.get(""/experts/999"", 42L)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isNotFound());

    }
</code></pre>

<p>Despite that, the response that comes back is 400, which means that my request is malformed. I guess the problem lies on the id, which I am inputting on the URI? I know that mongo accepts <code>hexStrings</code> as primary keys so my question is, how could I use an id on the URI which doesnt exist on my DB so that I can get a 404 response back? Thanks in advance for your answer.</p>
",https://stackoverflow.com/questions/59898514/spring-boot-test-api-endpoint-with-unit-testing-should-return-404-instead-of-400,"['java', 'spring', 'mongodb', 'spring-boot', 'unit-testing']",298,False,0,2
How to resolve error in unit testing when we have Date comparison in Codable,"<p>I tried to use custom date strategy in json decoding using <code>Codable</code> as describe in <a href=""https://stackoverflow.com/a/28016692/3477974"">https://stackoverflow.com/a/28016692/3477974</a> . Here is the simplified implementation code:</p>

<pre><code>public extension Formatter {
    static let iso8601: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: ""en_US_POSIX"")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = ""yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX""
        return formatter
    }()
}

public extension Date {
    var iso8601: String {
        return Formatter.iso8601.string(from: self)
    }
}


public extension JSONDecoder.DateDecodingStrategy {
    static let iso8601withFractionalSeconds = custom {
        let container = try $0.singleValueContainer()
        let string = try container.decode(String.self)
        guard let date = Formatter.iso8601.date(from: string) else {
            throw DecodingError.dataCorruptedError(in: container,
                  debugDescription: ""Invalid date: "" + string)
        }
        return date
    }
}


public extension JSONEncoder.DateEncodingStrategy {
    static let iso8601withFractionalSeconds = custom {
        var container = $1.singleValueContainer()
        try container.encode(Formatter.iso8601.string(from: $0))
    }
}
</code></pre>

<p>However, when it comes to unit testing it fails although the error message shows equal value used by <code>description</code> method of date:</p>

<pre><code>    func test_jsonCodable_iso8601() {
        let dates = [Date()] // [""Feb 9, 2020 at 12:55:24 PM""]

        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601withFractionalSeconds
        let data = try! encoder.encode(dates)

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601withFractionalSeconds
        let decodedDates = try! decoder.decode([Date].self, from: data) // [""Feb 9, 2020 at 12:55:24 PM""]

        XCTAssertEqual(dates, decodedDates)
        // fails with error message: [2020-02-09 12:55:24 +0000]"") is not equal to (""[2020-02-09 12:55:24 +0000]""
    }
</code></pre>

<p>Do you have any idea what is the issue and how we can resolve it?</p>

<p>By the way, the actual decodable object is the following one where <code>publishedAt</code> is of type date:</p>

<pre><code>public struct NewsItem: Equatable {
    public let id: UUID
    public let author: String
    public let title: String
    public let description: String
    public let urlToImage: URL?
    public let publishedAt: Date
    public let content: String

    public init(id: UUID,
                author: String,
                title: String,
                description: String,
                urlToImage: URL?,
                publishedAt: Date,
                content: String) {

        self.id = id
        self.author = author
        self.title = title
        self.description = description
        self.urlToImage = urlToImage
        self.publishedAt = publishedAt
        self.content = content
    }
}

extension NewsItem: Decodable {}
</code></pre>
",https://stackoverflow.com/questions/60136982/how-to-resolve-error-in-unit-testing-when-we-have-date-comparison-in-codable,"['swift', 'unit-testing', 'date', 'codable']",617,False,-1,1
Kotlin Coroutines ViewModel Unit Testing with Mockito using Retrofit MVVM throws Null pointer Exception,"<p><br>
I tried to UnitTest my ViewModel that uses Kotlin coroutines to make Retrofit API call. 
The unit test fails with Null pointer Exception.<br>When tried the same with Retrofit RXJAva UnitTest Passes. Used Mockito Framework. <br> Plese review my code and let me know the mistake that is done in my code. <br>
Please find below ViewModel and UnitTest class files: <br>
<strong>fetchResponseFromAPI()</strong> method makes API call to fetch data
<br>
<strong>RetroCoroutineViewModel.kt</strong>:<br></p>

<pre><code> class RetroCoroutineViewModel  : ViewModel(),LifecycleObserver{

private val errorOnAPI = MutableLiveData&lt;String&gt;()
private val mutableLiveData:MutableLiveData&lt;List&lt;RetroRxModel&gt;&gt; = MutableLiveData()
var loading : MutableLiveData&lt;Boolean&gt; = MutableLiveData()

@Inject
lateinit var retrofit: Retrofit
lateinit var apiService: APIService

init {
    DaggerRetroRxComponent.create().inject(this)
    loading.value = true
    apiService = retrofit.create(APIService::class.java)
}



 val postsMutableLiveData:MutableLiveData&lt;List&lt;RetroRxModel&gt;&gt; = MutableLiveData()

**@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun fetchResponseFromAPI(){**
    viewModelScope.launch {

        try{

            val response  = apiService.fetchUserPosts()
            if(response.isSuccessful){
                postsMutableLiveData.postValue(response.body())
                loading.value = false
            }else{
                loading.value = false
                errorOnAPI.postValue(""Something went wrong::${response.message()}"")
            }



        }catch (e:Exception){
            loading.value = false
            errorOnAPI.postValue(""Something went wrong::${e.localizedMessage}"")
        }

    }

}

fun fetchPostLiveData(): LiveData&lt;List&lt;RetroRxModel&gt;&gt;  = postsMutableLiveData


override fun onCleared() {
    super.onCleared()

}


fun fetchError(): LiveData&lt;String&gt; = errorOnAPI



fun fetchLoadStatus():LiveData&lt;Boolean&gt; = loading

    private  fun onError(message: String){
       errorOnAPI.value = message
       loading.value = false


     }
     }
</code></pre>

<p><strong>RetroCoroutineViewModelTest:</strong></p>

<pre><code>@RunWith(MockitoJUnitRunner::class)
@ExperimentalCoroutinesApi
   class RetroCoroutineViewModelTest {
@get:Rule
val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()

@get:Rule
val testCoroutineRule = TestCoroutineRule()

@Mock
lateinit var retrofit: Retrofit

@Mock
lateinit var apiService: APIService

lateinit var retroCoroutineViewModel: RetroCoroutineViewModel

private lateinit var response: Response&lt;List&lt;RetroRxModel&gt;&gt;

private  var loading: Boolean = false

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

      } 



       @Test
       fun fetchRetroInfoTest_success(){
       retroCoroutineViewModel = RetroCoroutineViewModel()
        testCoroutineRule.runBlockingTest {
        var retroRxModel = RetroRxModel(""tile"", ""body"", ""1"")
        var retroRXModelList = ArrayList&lt;RetroRxModel&gt;()
        retroRXModelList.add(retroRxModel)
        response = Response.success(retroRXModelList)
        if (retrofit != null) {

            if (apiService != null) {
                Mockito.`when`(apiService.fetchUserPosts()).thenReturn(response)
                retroCoroutineViewModel.fetchResponseFromAPI()

            }
        }
        val funResponse = retroCoroutineViewModel.fetchPostLiveData()
        println(""Response::::${funResponse.value}"")

         Assert.assertEquals(1,funResponse.value?.size)
        Assert.assertEquals(loading,retroCoroutineViewModel.loading)



    }
}

}
</code></pre>

<p><br>
I observe below Exception when I try to run the unit test case: <br></p>

<p>java.lang.AssertionError: 
   Expected :1
   Actual   :null
    </p>

<pre><code>at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.rxretrofit.RetroCoroutineViewModelTest$fetchRetroInfoTest_success$1.invokeSuspend(RetroCoroutineViewModelTest.kt:75)
</code></pre>

<p><strong>Build.Gradle:</strong></p>

<pre><code>    testImplementation ""org.mockito:mockito-core:3.3.3""   
    testImplementation 'androidx.arch.core:core-testing:2.1.0'
    testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.4'
</code></pre>
",https://stackoverflow.com/questions/61533896/kotlin-coroutines-viewmodel-unit-testing-with-mockito-using-retrofit-mvvm-throws,"['android', 'kotlin', 'kotlin-coroutines', 'android-mvvm', 'mockito-kotlin']",1719,False,0,0
"What Is A Unit Testing Framework, And How Can I Use It In Java","<p>I see a lot of new programmers, specifically in Java, who do there tests something like this:</p>

<pre><code>System.out.println(myMethod(someValue));
System.out.println(expectedValue == myMethod(someValue));
</code></pre>

<p>However, there is something called a Unit Testing Framework, that will help test your code. So, what is a unit testing framework, and why do I want to use it to help ease my testing? And how can I use it in Java?</p>
",https://stackoverflow.com/questions/61763864/what-is-a-unit-testing-framework-and-how-can-i-use-it-in-java,"['java', 'testing', 'junit']",42,True,-1,1
Assert in python code &amp; unit testing that checks if there is assert statement?,"<p>I have a code with an <code>assert</code> statement in it. Also, I'm doing unit testing on that code and I want to give a condition and if there is an <code>assert</code> statement in the code the test will pass.</p>

<pre><code>def do_something(m, n):
   assert m !=0, ""m has to be greater then 1""
       .....
</code></pre>

<p>In unit testing, I want to:</p>

<pre><code>class Test_ (unittest.TestCase):
    def test_something(self):
        # if m=0
        self.assert?????(m=0, ??not sure??)
</code></pre>

<p>What to write in order to test if there is an <code>assert</code> statement to <code>m=0</code>?
I saw something about context manager? Is it related?</p>
",https://stackoverflow.com/questions/59968068/assert-in-python-code-unit-testing-that-checks-if-there-is-assert-statement,"['python', 'python-3.x', 'unit-testing']",369,False,0,2
How to use initialize a service in a controller during unit testing in grails?,"<p>I'm starting with unit testing in <strong>Grails 3.3.8</strong>, I have the <strong>ControllerSpec</strong>:</p>

<pre><code>class FooControllerSpec extends Specification implements ControllerUnitTest&lt;FooController&gt; {

      void ""test index""() {
        given:
        controller.fooService = new FooServiceImplementation()

        when:
        controller.index()

        then:
        response.json
        status == 200
      }

      void ""test show""() {
        given:
        controller.fooService = new FooServiceImplementation()

        when:
        params['id'] = '000001400'
        controller.show()

        then:
        status == 200
      }
    }
</code></pre>

<p><strong>FooService</strong> is an interface, does not have implementation.</p>

<pre><code>@Service(Foo)
interface FooService {
Foo get(Serializable id)

List&lt;Foo&gt; list(Map args)
}
</code></pre>

<p>I create a <strong>FooServiceImplementation</strong> like this:</p>

<pre><code>class FooServiceImplementation implements FooService {
 Foo get(Serializable id) {/*implementation here*/}

    List&lt;Foo&gt; list(Map args) {/*implementation here*/}
}
</code></pre>

<p>This actually works, but there is another form to initialize the service in my controller?
I want to use the FooService exactly with the implementation that grails would compile when injecting the service into the controller, this to make sure that the results during the execution will be the same as during the testing, since my FooServiceImplementation could generate different results, although I suppose you should write the implementation correctly.</p>
",https://stackoverflow.com/questions/60934184/how-to-use-initialize-a-service-in-a-controller-during-unit-testing-in-grails,"['grails', 'spock']",78,False,0,0
Angular9 unit-testing: Is it possible to MOCK Parse.initialize and still have reliable tests?,"<p>I want to test component how do I do it with Parse.initialize(appId,url) function inside my <code>Angular Service</code>?<br />
<em>This is the initialization part:</em></p>
<pre class=""lang-js prettyprint-override""><code>Parse.initialize('MY_APP_ID', 'JS_KEY');
Parse.serverURL = 'https://parseapi.back4app.com/';
</code></pre>
<p><em>This is my test part:</em></p>
<pre class=""lang-js prettyprint-override""><code>describe('StateComponent', () =&gt; {
  let component: StateComponent;
  let fixture: ComponentFixture&lt;StateComponent&gt;;
  let service: TrayStateService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [StateComponent],
      providers: [
        TrayStateService,
        { provide: NbDialogService, useValue: {} },
        { provide: NbToastrService, useValue: {} },
        ChangeDetectorRef,
        AuthSessionQuery,
        {
          provide: 'env',
          useValue: environment
        }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
    service = TestBed.inject(TrayStateService);
  }));

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

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

  it('should verify that immediate function works properly', fakeAsync(() =&gt; {
      spyOn(service, 'getAll').and.returnValue(of(MockedDataResponseArray));
      component.ngOnInit();
      tick(10);
  }));
</code></pre>
<p><em>This is the error I get:</em></p>
<blockquote>
<p>Error: You need to call Parse.initialize before using Parse.</p>
</blockquote>
",https://stackoverflow.com/questions/62413274/angular9-unit-testing-is-it-possible-to-mock-parse-initialize-and-still-have-re,"['angular', 'unit-testing', 'mocking', 'parse-javascript-sdk']",136,True,0,1
"Moq, Visual Studio Unit Testing - Tests keep skipping a method in a mocked service","<p>I'm testing a GET action method that calls a public method in a service that has been mocked.</p>

<p>The test fails. When I placed a break-point in the service method, I found that it gets skipped during execution of the test. How do I ensure that the service method doesn't get skipped?</p>

<p>I'm using Visual Studio Unit Testing Tools, Moq, Castle Windsor</p>
",https://stackoverflow.com/questions/61809268/moq-visual-studio-unit-testing-tests-keep-skipping-a-method-in-a-mocked-servi,"['c#', 'visual-studio', 'unit-testing', 'moq', 'castle-windsor']",582,True,0,1
Typescript/React unit testing libraries with ability to step through imported functions for debugging,"<p>I'm currently using Jest to unit test my React components and Typescript functions. So far, it's been a big success at reducing regressions and I am happy with the vscode Jest plugin that lets me step through the unit test code to see variable values and steps before the failure.</p>
<p>However, the plugin/Jest (not sure which) doesn't allow me to step through my imported functions/components I'm trying to test; the debugging step-through only works in the unit test file.</p>
<p>For example:</p>
<pre><code>// file.tsx (file with functionality I want to test)
export function addOne(x: number) {
  return x + 1; // can't step through this
}
</code></pre>
<pre><code>// file.test.tsx (the test file)
import addOne from './file';

....... test set up......
it('addOne adds to 3 to get 5', () =&gt; { // obviously a failing test
   const start = 3; // can only step through this file
   const result = addOne(start); // step into doesn't work here, will skip over to the expect
   expect(result).toBe(5);
});
</code></pre>
<p>This was obviously a fake example, but I can only step through the steps in <code>file.test.tsx</code> and I can't step into the <code>addOne</code> function and see what is happening inside it. I can only see what it returns. In order for me to get around this, I had to place console.logs for all the variables in the imported functionality files (file.tsx) and it has been a pain.</p>
<p>Is there a way to configure Jest (or another unit testing library for react/typescript) to be able to step through these imported functions?</p>
<p>Thanks</p>
<p><strong>Update:</strong>
I should clarify that when I mean I can't step into functions, I also mean that putting breakpoints in file.tsx doesn't work. The debugger does stop at breakpoints in file.test.tsx however, which I find strange I can't simply do the former.</p>
",https://stackoverflow.com/questions/65435006/typescript-react-unit-testing-libraries-with-ability-to-step-through-imported-fu,"['javascript', 'reactjs', 'typescript', 'unit-testing', 'jestjs']",292,False,0,1
how to do a dependancy injection with a method in micronaut for unit testing,"<p>I have a controller class:</p>
<pre><code>@Controller(&quot;/x&quot;)
class Controller {

@Get
fun index(): String {
    return &quot;test test&quot;
}

@Post
fun dopost (userid) = executelogin(login.userId)
}
</code></pre>
<p>This controller depends on the executelogin method down below:</p>
<pre><code>fun executelogin(userid) =
   do things
</code></pre>
<p>If I want to write a unit test, how would I go about using a dependancy injection to introduce a version of the executelogin method. Below is what I have so far and I am not sure if I am doing it correctly:</p>
<pre><code>@MicronautTest
class Controllertest(val method: executelogin()) {



@Inject
    lateinit var client: RxHttpClient


@Test
fun testController(){
    val request: HttpRequest&lt;String&gt; = HttpRequest.POST(&quot;/hello&quot;,&quot;test&quot;)
    val body: String = client.toBlocking().retrieve(request)

    assertNotNull(body)
    assertEquals(method,method)
    
}
}
</code></pre>
<p>Above in the unit test, I am making the executelogin method a paramter for the controllertest class, which I believe is called a method injection. I was wondering if this was the correct way to go about this or if adjustments need to be made. I apologise if some of the code does not quite make sense, I am new to micronaut and the concept of dependancy injections.</p>
",https://stackoverflow.com/questions/64814961/how-to-do-a-dependancy-injection-with-a-method-in-micronaut-for-unit-testing,"['unit-testing', 'kotlin', 'dependency-injection', 'inversion-of-control', 'micronaut']",242,True,0,1
How to resolve issue that is res.headers.get(&#39;Authorization&#39;) is undefined in Angular unit testing?,"<p>Component function:</p>

<pre><code>onSubmit() {
    this.formDataService.sendUserCredentials(this.loginForm.get('email').value, 
    this.loginForm.get('password').value)
    .subscribe(res =&gt; {
        localStorage.setItem('X-Auth-Token', res.headers.get('X-Auth-Token'));
        localStorage.setItem('Authorization', res.headers.get('Authorization'));
        localStorage.setItem('userObject', JSON.stringify(res.body));
        this.router.navigate(['dashboard']);
    }, err =&gt; {
      this.invalidCredentials = true;
    });
}
</code></pre>

<p>Service Method:</p>

<pre><code>sendUserCredentials(userEmail, userPassword) {
    const userCredentials = {
        email: userEmail,
        password: (jsSha.sha512(userPassword)).toUpperCase(),
    };

    return this.http.post(environment.BASE_URL + 'users/login', userCredentials, {
        observe: 'response',
        headers: new HttpHeaders().set('Authorization', 'dfsdf-e4vfd-ertrg')
    });
}
</code></pre>

<p>Unit test:</p>

<pre><code>it('API call inside onSubmit resolves successfully', fakeAsync(() =&gt; {
    const spy = spyOn(service, 'sendUserCredentials').and.returnValue(of('logged-in'));
    component.onSubmit();
    tick();
    expect(spy.calls.any()).toBe(true);
}));
</code></pre>

<p>I am able to pass through the line where a service method named as <code>sendUserCredentials</code> but inside that service method there is a line where I am fetching headers from the response and I am not able to resolved the issue that I am getting.</p>

<pre><code>Error: TypeError: Cannot read property 'get' of undefined
</code></pre>

<p>This error specifically occurs for the 4th line of component function.</p>
",https://stackoverflow.com/questions/60317963/how-to-resolve-issue-that-is-res-headers-getauthorization-is-undefined-in-an,"['angular', 'typescript', 'unit-testing', 'jasmine', 'angular-unit-test']",317,False,0,0
Angular 4+ unit testing error . i can not unit test because of syntax error,"<p>ERROR in src/app/campaigns/campaign-product-details/campaign-product-details.component.ts(106,14): error TS2339: Property 'disabled' does not exist on type '{ id: { toString: any; toFixed: any; toExponential: any; toPrecision: any; valueOf: any; toLocale...'.</p>
",https://stackoverflow.com/questions/62695974/angular-4-unit-testing-error-i-can-not-unit-test-because-of-syntax-error,"['angular', 'typescript', 'karma-jasmine']",48,False,-3,1
Unit Testing - XUnit - IAssemblyFixture -The following constructor parameters did not have matching fixture data,"<p>Right now, i would like to share the context entire assembly. To sort out this use-cases, i have started using IAssemblyFixture : this is how my code looks</p>
<pre><code>-- Context
public class AssemblyLevelRepoFixture
    {
}


    public class TestBaseAssemblyFixture : Xunit.Extensions.AssemblyFixture.IAssemblyFixture&lt;AssemblyLevelRepoFixture&gt;
    {
        private readonly ITestOutputHelper testOutputHelper;
        private readonly AssemblyLevelRepoFixture fixture;
    }

    public class SampleTest : TestBaseAssemblyFixture
    {
        
        public SampleTest(ITestOutputHelper testOutputHelper, AssemblyLevelRepoFixture fixture) : base (testOutputHelper, fixture)
        {
            // hellow how are you;
        }

        
        public void FirstTest()
        {
            Assert.True(true);
        }
    }
</code></pre>
<p>-- I am facing issue : The following constructor parameters did not have matching fixture data: AssemblyLevelRepoFixture fixture</p>
",https://stackoverflow.com/questions/62876024/unit-testing-xunit-iassemblyfixture-the-following-constructor-parameters-di,"['c#', 'unit-testing', '.net-core', 'moq', 'xunit']",1439,False,0,1
Insert data in h2 database through data.sql file before performing unit testing in spring boot,"<p>I want to perform unit testing in spring boot+ JPA. For that I created configuration file to create bean for dataSource, all hibernate properties, entityManagerFactory and transactionManager. Everything going perfect. Tables are getting created by model classes. but now I want to insert data in all tables of database for testing through data.sql file.
I kept data.sql file in src/main/resources but it not loading the file.
So how can I load data in h2 database before starting with unit testing. </p>

<p>This is my cofiguration file - </p>

<pre><code>
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.cfg.Environment;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@EnableJpaRepositories(basePackages = ""base_package_name"")
@EnableTransactionManagement
public class JPAConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(""org.h2.Driver"");
        dataSource.setUrl(""jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1"");
        /*dataSource.setDriverClassName(""org.hsqldb.jdbcDriver"");
        dataSource.setUrl(""jdbc:hsqldb:mem:testdb"");*/
        dataSource.setUsername(""sa"");
        dataSource.setPassword("""");

        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put(""hibernate.dialect"", ""org.hibernate.dialect.H2Dialect"");
        properties.put(""hibernate.hbm2ddl.auto"", ""create"");
        properties.put(""hibernate.show_sql"", ""true"");
        properties.put(""hibernate.format_sql"", ""false"");
        return properties;
    }

    @Bean(name=""entityManagerFactory"")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setDataSource(this.dataSource());
        lcemfb.setPackagesToScan(new String[] {""Package_to_scan""});

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        lcemfb.setJpaVendorAdapter(va);

        lcemfb.setJpaProperties(this.hibernateProperties());

        lcemfb.afterPropertiesSet();

        return lcemfb;

    }


    @Bean
    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();

        tm.setEntityManagerFactory(
            this.entityManagerFactoryBean().getObject() );

        return tm;

    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

</code></pre>
",https://stackoverflow.com/questions/60333899/insert-data-in-h2-database-through-data-sql-file-before-performing-unit-testing,"['java', 'spring-boot', 'h2', 'spring-boot-test', 'h2db']",12374,True,4,1
How to determine which is a SUT and which is a collaborator in unit testing?,"<p>I was reading a book and below is some code:</p>

<pre><code>[Fact]
public void Purchase_succeeds_when_enough_inventory()
{
    // Arrange
    var store = new Store();
    store.AddInventory(Product.Shampoo, 10);
    var customer = new Customer();

    // Act
    bool success = customer.Purchase(store, Product.Shampoo, 5);

    // Assert
    Assert.True(success);
    Assert.Equal(5, store.GetInventory(Product.Shampoo));
}

[Fact]
public void Purchase_fails_when_not_enough_inventory()
{
    // Arrange
    var store = new Store();
    store.AddInventory(Product.Shampoo, 10);
    var customer = new Customer();

    // Act
    bool success = customer.Purchase(store, Product.Shampoo, 15);

    // Assert
    Assert.False(success);
    Assert.Equal(10, store.GetInventory(Product.Shampoo));
}
</code></pre>

<p>The author says  <strong>Customer</strong> is the <strong>SUT</strong> and <strong>Store</strong> is the <strong>collaborator</strong></p>

<p>I'm a little bit confused here, the assert phase also test the Store, isn't that Store is also a SUT? </p>
",https://stackoverflow.com/questions/61361174/how-to-determine-which-is-a-sut-and-which-is-a-collaborator-in-unit-testing,"['c#', 'unit-testing', 'tdd']",867,True,4,2
"java.lang.NoClassDefFoundError: Test Module could not resolve classes of other Feature Module, Unit Testing - Kotlin - Android","<p>I have the following Project Structure:</p>
<pre><code>Main App
 --app
 --featureModule1
 --featureModule2
 --TestKit(Library module)
</code></pre>
<p>where Testkit has all dependencies including app and featureModules. The Testkit included all the unit tests related to the features in app and featuremodules.</p>
<p>When i run unit tests from Android studio(Right click-&gt; Run Test in Testkit), they run fine. However whenever i try running it from gradle command: <code>./gradlew TestKit:testInternalDebugUnitTest</code>, it throws <code>NoClassDefFoundError</code> for all the dependencies of other modules(for both app and feature modules).</p>
<p>Also i have already added implementation and testImplementation dependencies of all the modules in test module.</p>
<p>Please suggest:</p>
<ol>
<li><p>Do i need to add path of classes generated in other modules, if yes pls guide where.</p>
</li>
<li><p>Also running Test with Coverage fails with</p>
<p>java.lang.VerifyError: Bad return type</p>
</li>
</ol>
<p><em>Please suggest what am i doing wrong here.</em></p>
<p><strong>Note:</strong>
I have created a Testkit because of the multiple open issues of Roboelectric in feature modules for ex: <a href=""https://github.com/robolectric/robolectric/issues/5428"" rel=""noreferrer"">https://github.com/robolectric/robolectric/issues/5428</a></p>
<p><strong>Versions</strong>
AS: 4.0.1
gradle: 4.0.1
gradle-wrapper: 6.5
Robolectric: 4.3.1</p>
",https://stackoverflow.com/questions/63548383/java-lang-noclassdeffounderror-test-module-could-not-resolve-classes-of-other-f,"['android', 'unit-testing', 'kotlin', 'robolectric', 'androidx-test']",710,True,4,1
How to get JSDOM to work with typescript when unit testing with a Chai\Mocha setup?,"<p>I've been trying to get JSDOM to work in my typescript unit tests, but after many attempts, I keep getting the following error (or variants of the following error)</p>
<pre><code>TypeError: _jsdom.JSDOM is not a constructor
</code></pre>
<p>The code snippet is the following</p>
<pre><code>import React from 'react';

import { act } from 'react-dom/test-utils';
import { expect } from 'chai';
import { mock, instance, verify, anyOfClass } from 'ts-mockito';
import { JSDOM } from 'jsdom'
import { TestApp } from '../ts/ExampleForTestingReact';

let rootContainer: HTMLDivElement;
const { window } = new JSDOM('&lt;!doctype html&gt;&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;');
</code></pre>
<p>My package json is the following</p>
<pre><code>{
  &quot;name&quot;: &quot;app&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;private&quot;: true,
  &quot;devDependencies&quot;: {
    &quot;@babel/cli&quot;: &quot;^7.8.4&quot;,
    &quot;@babel/core&quot;: &quot;^7.9.0&quot;,
    &quot;@babel/node&quot;: &quot;^7.8.7&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.9.0&quot;,
    &quot;@babel/preset-react&quot;: &quot;^7.10.1&quot;,
    &quot;@babel/preset-typescript&quot;: &quot;^7.9.0&quot;,
    &quot;@babel/register&quot;: &quot;^7.9.0&quot;,
    &quot;@types/bootstrap&quot;: &quot;4.3.2&quot;,
    &quot;@types/chai&quot;: &quot;^4.2.0&quot;,
    &quot;@types/mocha&quot;: &quot;^7.0.2&quot;,
    &quot;@types/react&quot;: &quot;^16.9.31&quot;,
    &quot;@types/react-dom&quot;: &quot;^16.9.6&quot;,
    &quot;@types/jsdom&quot;: &quot;^16.2.3&quot;,
    &quot;babel-loader&quot;: &quot;^8.1.0&quot;,
    &quot;chai&quot;: &quot;^4.2.0&quot;,
    &quot;clean-webpack-plugin&quot;: &quot;^3.0.0&quot;,
    &quot;css-loader&quot;: &quot;^3.6.0&quot;,
    &quot;file-loader&quot;: &quot;^6.0.0&quot;,
    &quot;html-webpack-plugin&quot;: &quot;^4.3.0&quot;,
    &quot;image-webpack-loader&quot;: &quot;^6.0.0&quot;,
    &quot;mini-css-extract-plugin&quot;: &quot;^0.9.0&quot;,
    &quot;mocha&quot;: &quot;^7.1.1&quot;,
    &quot;node-sass&quot;: &quot;^4.14.1&quot;,
    &quot;optimize-css-assets-webpack-plugin&quot;: &quot;^5.0.3&quot;,
    &quot;terser-webpack-plugin&quot;: &quot;^3.0.6&quot;,
    &quot;ts-loader&quot;: &quot;^7.0.5&quot;,
    &quot;ts-mockito&quot;: &quot;^2.5.0&quot;,
    &quot;ts-node&quot;: &quot;^8.8.1&quot;,
    &quot;typescript&quot;: &quot;3.8.3&quot;,
    &quot;webpack&quot;: &quot;^4.43.0&quot;,
    &quot;webpack-cli&quot;: &quot;^3.3.12&quot;,
    &quot;jsdom-global&quot;: &quot;^3.0.2&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@fortawesome/fontawesome-free&quot;: &quot;^5.13.1&quot;,
    &quot;bootstrap&quot;: &quot;^4.3.1&quot;,
    &quot;bootstrap-table&quot;: &quot;^1.16.0&quot;,
    &quot;file-saver&quot;: &quot;^2.0.2&quot;,
    &quot;jquery&quot;: &quot;^3.3.1&quot;,
    &quot;jquery-validation&quot;: &quot;^1.17.0&quot;,
    &quot;jquery-validation-unobtrusive&quot;: &quot;^3.2.11&quot;,
    &quot;moment&quot;: &quot;^2.26.0&quot;,
    &quot;mpx-dialog&quot;: &quot;^1.1.12&quot;,
    &quot;mpx-error-boundary&quot;: &quot;^1.0.0&quot;,
    &quot;mpx-multi-language&quot;: &quot;^1.0.8&quot;,
    &quot;mpx-react-page-components&quot;: &quot;^1.0.3&quot;,
    &quot;mpx-utilities&quot;: &quot;^1.0.1&quot;,
    &quot;react&quot;: &quot;^16.13.1&quot;,
    &quot;react-dom&quot;: &quot;^16.13.1&quot;,
    &quot;tableexport.jquery.plugin&quot;: &quot;^1.10.20&quot;
  },
  &quot;babel&quot;: {
    &quot;presets&quot;: [
      &quot;@babel/preset-env&quot;,
      &quot;@babel/preset-react&quot;,
      &quot;@babel/preset-typescript&quot;
    ]
  },
  &quot;mocha&quot;: {
    &quot;extension&quot;: [
      &quot;ts&quot;,
      &quot;tsx&quot;
    ],
    &quot;spec&quot;: &quot;wwwroot/ts-tests/**/*.test.tsx&quot;,
    &quot;require&quot;: &quot;wwwroot/ts-tests/babel-register.js&quot;
  },
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;mocha&quot;,
    &quot;pack-dev&quot;: &quot;webpack --mode development&quot;,
    &quot;pack-prod&quot;: &quot;webpack --mode production&quot;,
    &quot;clean&quot;: &quot;del /Q /F .\\wwwroot\\dist\\*.*&quot;
  }
}

</code></pre>
<p>I've been trying to do the following:
<a href=""https://stackoverflow.com/a/45311836/4545812"">https://stackoverflow.com/a/45311836/4545812</a></p>
<p>Any help on the matter would be greatly appreciated!</p>
",https://stackoverflow.com/questions/62902689/how-to-get-jsdom-to-work-with-typescript-when-unit-testing-with-a-chai-mocha-set,"['reactjs', 'typescript', 'mocha.js', 'chai', 'jsdom']",8297,True,8,1
Go: How can I create an instance of type schema.ResourceData with values for unit testing?,"<p>I want to write a unit test for a method similar to this:</p>
<pre class=""lang-golang prettyprint-override""><code>package bingo

import &quot;github.com/hashicorp/terraform-plugin-sdk/helper/schema&quot;

func doStuff(d *schema.ResourceData) error {
    foo := d.Get(&quot;foo&quot;).(string)
    // ... operations using d
    return nil
}
</code></pre>
<p>Is there a way to create an instance of type <code>schema.ResourceData</code> with values in it?</p>
<p>I tried creating a &quot;blank&quot; instance of <code>ResourceData</code> and populate it via <code>.Set(...)</code>. But it doesn't work, since no schema is present:</p>
<pre class=""lang-golang prettyprint-override""><code>package bingo

import &quot;github.com/hashicorp/terraform-plugin-sdk/helper/schema&quot;

func TestDoStuff(t *testing.T) {
    d := schema.ResourceData{}
    err := d.Set(&quot;foo&quot;, &quot;bar&quot;)
    if err != nil {
      t.Errorf(&quot;failed to set value: %s&quot;, err)
      // &gt; failed to set value: Invalid address to set: []string{&quot;foo&quot;}
    }

    // test doStuff()
}
</code></pre>
",https://stackoverflow.com/questions/63613067/go-how-can-i-create-an-instance-of-type-schema-resourcedata-with-values-for-uni,"['go', 'testing', 'terraform']",464,True,3,1
"In C#, is it possible to mock out IMessageReceiver and related classes for unit testing?","<p>I have the following class I wish to create unit tests for:</p>
<pre><code>    public class ServiceBusClient {
        private readonly IMessageReceiver messageReceiver;
        private readonly int maximumMessages;

        public ServiceBusClient(IMessageReceiver messageReceiver, int maximumMessages) {
            this.messageReceiver = messageReceiver;
            this.maximumMessages = maximumMessages;
        }

        public async Task&lt;List&lt;EnergyUser&gt;&gt; ReceiveEnergyUsersAsync() {
            List&lt;EnergyUser&gt; energyUsers = new List&lt;EnergyUser&gt;();
            List&lt;string&gt; lockTokens = new List&lt;string&gt;();
            
            this.ReceiveMessages()
                .ForEach((message) =&gt; {
                    if (message.Body != null) {
                        energyUsers.Add(JsonConvert.DeserializeObject&lt;EnergyUser&gt;(Encoding.UTF8.GetString(message.Body)));
                    }
                    lockTokens.Add(message.SystemProperties.LockToken);
                });

            _ = this.messageReceiver.CompleteAsync(lockTokens);
            return await Task.FromResult(energyUsers);
        }

        private List&lt;Message&gt; ReceiveMessages() {
            return this.messageReceiver.ReceiveAsync(this.maximumMessages)
                            .GetAwaiter()
                            .GetResult()
                            .ToList();
        }
    }
</code></pre>
<p>It will be observed that it is dependent upon <code>Microsoft.Azure.ServiceBus.Core.IMessageReceiver</code>.</p>
<p>My first attempt to mock this out was to use <code>Moq</code>. I would have expected if I create a <code>new Mock&lt;IMessageReceiver&gt;()</code>, I should be able to inject it into <code>public ServiceBusClient(IMessageReceiver messageReceiver, int maximumMessages)</code>, but instead the compiler tells me &quot;Error CS1503 Argument 1: cannot convert from 'Moq.Mock&lt;Microsoft.Azure.ServiceBus.Core.IMessageReceiver&gt;' to 'Microsoft.Azure.ServiceBus.Core.IMessageReceiver&quot;....</p>
<p>Then I thought I would try to manually mock out the class:</p>
<pre><code>    internal class MockMessageReceiver : IMessageReceiver {
        public int ReceivedMaxMessgeCount { get; set; }
        public IList&lt;Message&gt; ReturnMessages { get; set; }
        Task&lt;IList&lt;Message&gt;&gt; IMessageReceiver.ReceiveAsync(int maxMessageCount) {
            this.ReceivedMaxMessgeCount = maxMessageCount;
            return Task.FromResult(this.ReturnMessages);
        }

        public IEnumerable&lt;string&gt; ReceivedLockTokens { get; set; }
        Task IMessageReceiver.CompleteAsync(IEnumerable&lt;string&gt; lockTokens) {
            this.ReceivedLockTokens = lockTokens;
            return Task.Delay(1);
        }

        // Many functions which do nothing just to satisfy the bloated interface.
}
</code></pre>
<p>This will allow me to successfully provide messages EXCEPT the messages I provide don't include SystemProperties, so ServiceBusClient will throw an error at <code>lockTokens.Add(message.SystemProperties.LockToken)</code>.</p>
<p>It turns out that the <code>Microsoft.Azure.ServiceBus.Message</code> implementation does not provide a setter for <code>public SystemPropertiesCollection SystemProperties</code>, so to set this (unless someone has a better way), I need to create my own implementation of Message:</p>
<pre><code>    public class MockMessage : Message {
        public MockMessage(byte[] body) =&gt; base.Body = body;

        public new SystemPropertiesCollection SystemProperties {
            get { return this.SystemProperties; }
            set { this.SystemProperties = value; }
        }
    }
</code></pre>
<p>Now, I can initialize SystemPropertiesCollection, BUT the problem becomes that no property in SystemPropertiesCollection actually includes a setting, so my tests will still fail.</p>
<p>Then I thought: Let's create a mock for &quot;SystemPropertiesCollection&quot; (never mind that we are starting to swim in the dangerous waters of &quot;too much mock&quot;.... but when I try to extend this class, my compiler complains because SystemPropertiesCollection is actually a sealed class, so I can't extend it.</p>
<p>So, now I'm back to square one.</p>
<p>Any ideas how I can create good unit tests for ServiceBusClient?</p>
",https://stackoverflow.com/questions/62991638/in-c-is-it-possible-to-mock-out-imessagereceiver-and-related-classes-for-unit,"['c#', 'unit-testing', 'mocking', 'azureservicebus', 'sealed-class']",2706,True,3,3
next-i18next unit testing error &#39;Cannot read property language of undefined&#39; with Link and jest,"<p><code>next-i18next</code> uses it's own <code>Link</code> component to be compatible with locale sub-paths.</p>
<p><a href=""https://github.com/isaachinman/next-i18next"" rel=""nofollow noreferrer"">https://github.com/isaachinman/next-i18next</a></p>
<p>When I try a simple snapshot test I get the error <code>Cannot read property language of undefined</code>.</p>
<p>My component:</p>
<pre><code>import React from 'react';
import { TFunction } from 'next-i18next';
import { withTranslation, Link } from '../../../i18n';

interface HeaderProps {
  readonly t: TFunction;
}

const Header = ({ t }: HeaderProps): JSX.Element =&gt; {
  return (
    &lt;&gt;
      &lt;Flex&gt;
        &lt;Box&gt;
          &lt;Link href=&quot;/&quot;&gt;{t('home')}&lt;/Link&gt;
        &lt;/Box&gt;
      &lt;/Flex&gt;
    &lt;/&gt;
  );
};

export default withTranslation('common')(Header);
</code></pre>
<p>It's snapshot test:</p>
<pre><code>import React from 'react';
import { render, screen } from '@testing-library/react';
import Header from './Header';

describe('&lt;Header/&gt;', () =&gt; {
  test('it should render correctly', () =&gt; {
    const { container } = render(&lt;Header /&gt;);
    expect(container.firstChild).toMatchSnapshot();
  });
});
</code></pre>
<p>The test runs and passes without the <code>Link</code> component as expected.</p>
<p>I have defined my <code>i18n.ts</code> as follows:</p>
<pre><code>import path from 'path';
import NextI18Next from 'next-i18next';
import { publicRuntimeConfig } from './next.config';

const { localeSubpaths } = publicRuntimeConfig;

export const nextI18next = new NextI18Next({
  browserLanguageDetection: false,
  defaultNS: 'common',
  defaultLanguage: 'en',
  fallbackLng: 'en',
  otherLanguages: ['fr'],
  localeSubpaths,
  localePath: path.resolve('./public/static/locales'),
});

export const {
  i18n,
  appWithTranslation,
  Link,
  withTranslation,
  Router,
} = nextI18next;
</code></pre>
<p>Is there anyway I can fix this error?</p>
",https://stackoverflow.com/questions/64071576/next-i18next-unit-testing-error-cannot-read-property-language-of-undefined-wit,"['reactjs', 'jestjs', 'next.js', 'i18next', 'next-i18next']",5313,True,2,2
What did Joe Armstrong refer to by &quot;there are more advanced techniques&quot; for unit testing,"<p>What did Joe Armstrong refer to by &quot;you shouldn't write test cases at all, there are more advanced techniques you can use than silly old test cases&quot; ?</p>
<p>What are those more advanced techniques?</p>
<p>source: <a href=""https://youtu.be/rmueBVrLKcY?t=3266"" rel=""nofollow noreferrer"">A Guide for the Perplexed</a></p>
<p>Additionally, he even suggests to not reuse code but to rewrite it. That goes against everything my school has taught me. So I'm wondering what is the reasoning behind this statement.</p>
",https://stackoverflow.com/questions/64111039/what-did-joe-armstrong-refer-to-by-there-are-more-advanced-techniques-for-unit,"['unit-testing', 'code-reuse']",90,True,2,1
Codeception unit testing php. Check that a function has been called with a certain parameter,"<p>I try to find the solution for the simple issue. I need to check, that  a function has been called with a certain parameter. But I can just check, that  a function has been called and return some parameter. I was searching in codeseption docs very long. Have codeception some method for this?</p>
<pre><code>   public function testSomething()
   {
      $conversation = $this-&gt;make('Class', [
         'ask' =&gt; \Codeception\Stub\Expected::once('this string will be returned')
      ]);
      $conversation-&gt;run();
   }
</code></pre>
",https://stackoverflow.com/questions/62558270/codeception-unit-testing-php-check-that-a-function-has-been-called-with-a-certa,"['php', 'unit-testing', 'testing', 'integration-testing', 'codeception']",367,True,2,2
Angular 10: Unit Testing with a HttpInterceptor that modifies the response not getting an HttpResponse,"<p>If searched around SO for answers and so far, everything I've tried produces the same missing information.</p>
<p>This is running Angular 10 with the latest version of Karma/Jasmine.</p>
<p>Essentially, I have an HTTP Interceptor that is looking at the content-type of the return object. If it's json, continue as normal, if it's html...then throw an error.</p>
<pre><code>import {
    HttpEvent,
    HttpHandler,
    HttpInterceptor,
    HttpRequest,
    HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { httpStatusCodes } from '../../../shared/enums/httpStatusCodes.enum';
import { errorResponse } from './../../../shared/models/errorResponse.model';

@Injectable()
export class WafErrorInterceptor implements HttpInterceptor {
    intercept(
        request: HttpRequest&lt;any&gt;,
        next: HttpHandler
    ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
        return next.handle(request).pipe(
            map((event: HttpEvent&lt;any&gt;) =&gt; {
                console.log(event instanceof HttpResponse);
                if (
                    event instanceof HttpResponse &amp;&amp;
                    event.headers.has('content-type') &amp;&amp;
                    event.headers.get('content-type') === 'application/json'
                ) {
                    return event;
                }

                const throwErrorResponse = new errorResponse(
                    httpStatusCodes.WAF_ERROR,
                    '99999',
                    event instanceof HttpResponse
                        ? event.body
                        : 'unknown error occurred'
                );
                throw throwErrorResponse;
            })
        );
    }
}
</code></pre>
<p>And then in my unit test I run this:</p>
<pre><code>import {
    HttpClient,
    HttpHeaders,
    HttpResponse,
    HTTP_INTERCEPTORS
} from '@angular/common/http';
import {
    HttpClientTestingModule,
    HttpTestingController
} from '@angular/common/http/testing';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { errorResponse } from './../../../shared/models/errorResponse.model';
import { WafErrorInterceptor } from './waf-error.service';

describe('WafErrorInterceptor', () =&gt; {
    let httpMock: HttpTestingController;
    let httpClient: HttpClient;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                {
                    provide: HTTP_INTERCEPTORS,
                    useClass: WafErrorInterceptor,
                    multi: true
                }
            ]
        });
        httpMock = TestBed.get(HttpTestingController);
        httpClient = TestBed.get(HttpClient);
    });

    afterEach(() =&gt; {
        httpMock.verify();
    });

    it('intercept: when no error, then subscribe returns successfully', () =&gt; {
        const testData: string = 'test';

        httpClient.get&lt;string&gt;('https://secure.testurl.com/success').subscribe(
            (data) =&gt; expect(data).toBeTruthy(),
            (error: errorResponse) =&gt; {
                console.log(error);
                fail('error should not have been called');
            }
        );
        tick();
        let req = httpMock.expectOne('https://secure.testurl.com/success');
        tick();

        let httpHeaders = new HttpHeaders();
        httpHeaders.set('content-type', 'application/json');

        const expectedResponse = new HttpResponse&lt;string&gt;({
            status: 200,
            statusText: 'OK',
            body: testData,
            headers: httpHeaders
        });

        //req.flush(expectedResponse);
        req.event(expectedResponse);
    });
});
</code></pre>
<p>I've tried flush where I just send back data, where i send back data and the headers/status. Where I send back an httpresponse, etc. Each time, when it gets into the interceptor, the interceptor doesn't see the response as of type httpresponse and the console.log always returns false.</p>
<p>I've even just created a unit test where the unit test sends in a mock object...and even that has the same issue.</p>
<p>Thoughts?</p>
<p>UPDATED:
So the below answer works for the Map, but still having issues testing the catchErrorInterceptor. The code works on my site. Our API returns an object where the errors contains an array of errors. So we grab the first one and use that.</p>
<pre><code>@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    intercept(
        request: HttpRequest&lt;any&gt;,
        next: HttpHandler
    ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
        return next.handle(request).pipe(
            catchError((error: HttpErrorResponse) =&gt; {
                let statusCode = httpStatusCodes.CONFLICT;
                let errorMessage = '';
                let errorCode = '99999';

                statusCode =
                    error.status === 0
                        ? httpStatusCodes.INTERNAL_SERVER_ERROR
                        : error.status;

                if (error.error.errors &amp;&amp; error.error.errors.length &gt; 0) {
                    errorCode = error.error.errors[0].code;
                    errorMessage = error.error.errors[0].description;
                } else {
                    errorMessage = error.message;
                }

                const throwErrorResponse = new errorResponse(
                    statusCode,
                    errorCode,
                    errorMessage
                );

                return throwError(throwErrorResponse);
            })
        );
    }
}
</code></pre>
<p>Here is one of the tests:</p>
<pre><code>    it('intercept: when delibarate 409, then error returned', (done) =&gt; {
        httpClient
            .get&lt;string&gt;('https://secure.go2bank.com/error')
            .pipe(skip(1))
            .subscribe(
                (data) =&gt; fail('should have failed with the 404 error'),
                (error: errorResponse) =&gt; {
                    expect(error).toBeTruthy(); // check if executed
                    expect(error.httpStatusCodes).toBe(
                        httpStatusCodes.CONFLICT
                    );
                    expect(error.errorCode).toBe('1007');
                    expect(error.errorMessage).toBe(
                        'Validation error Authorization'
                    );
                    done();
                }
            );

        const errorInitEvent: ErrorEventInit = {
            message: null,
            error: {
                errors: [
                    {
                        code: '1007',
                        description: 'Validation error Authorization.',
                        message: null,
                        link: null,
                        additionalinfo: null
                    }
                ]
            }),
            lineno: null,
            colno: null,
            filename: null
        };

        let error = new ErrorEvent('ERROR', errorInitEvent);

        httpMock.expectOne('https://secure.go2bank.com/error').error(error, {
            status: httpStatusCodes.CONFLICT,
            statusText: 'Conflict',
            headers: new HttpHeaders().set('content-type', 'application/json')
        });
    });
</code></pre>
<p>The result of this test is always 99999 and not 1007. So I'm getting the error, it's catching the error. But when I look at it, error.error is ErrorEvent(isTrusted: //&quot;), and it doesn't look like I have an array of Errors inside of Error.</p>
",https://stackoverflow.com/questions/63248288/angular-10-unit-testing-with-a-httpinterceptor-that-modifies-the-response-not-g,"['angular', 'unit-testing', 'karma-jasmine', 'angular-http-interceptors', 'angular-test']",7039,True,1,1
How do I mock a &quot;with connect&quot; SQL query in a Python 3 unit testing?,"<p>For a function like the below, where engine is a SQLAlchemy engine like,</p>

<pre><code>from sqlalchemy import create_engine
engine = create_engine(f'mysql+pymysql://{db_username}:{db_password}@{db_host}:{db_port}/{db_name}', pool_recycle=3600)
</code></pre>

<pre><code>def pull(engine, afield):
    query = f""SELECT col1, col2 FROM mydatabase WHERE field='{afield}'""
    with engine.connect() as conn:
        result = conn.execute(query)
    return result
</code></pre>

<p>How do I mock the query result from the ""with"" statement in a unit test?</p>
",https://stackoverflow.com/questions/61603500/how-do-i-mock-a-with-connect-sql-query-in-a-python-3-unit-testing,"['python', 'unit-testing', 'sqlalchemy', 'mocking']",1147,True,1,1
How can I setup StaticResourceExtension when unit testing a markup extension that relies on it?,"<p>I have written a custom markup extension : <code>CoalesceResourceExtension</code></p>

<pre><code>[MarkupExtensionReturnType(typeof(object))]
public class CoalesceResourceExtension : MarkupExtension
{
    public CoalesceResourceExtension(string resources)
    {
        this.Resources = resources;
    }

    public string Separator { get; set; }

    [ConstructorArgument(""resources"")]
    public string Resources { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Resources != null)
        {
            foreach (string resourceName in Resources.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    if (new StaticResourceExtension(resourceName).ProvideValue(serviceProvider) is object resource)
                    {
                        return resource;
                    }
                }
                catch { }
            }
        }

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

<p>But when I come to unit testing <code>CoalesceResourceExtension</code>, I can't seem to find a way to setup the <code>StaticResourceExtension</code> so that it will find the desired mocked resources. Is there a way I can setup things for the <code>StaticResourceExtension</code> to find my mocked resources?</p>
",https://stackoverflow.com/questions/60211344/how-can-i-setup-staticresourceextension-when-unit-testing-a-markup-extension-tha,"['c#', 'wpf', 'unit-testing', 'moq', 'markup-extensions']",229,True,1,2
"Error on mocking multiple service(SSM, SES, SNS ) with Jest - lambda nodejs function unit testing","<p>I am trying to mock multiple service in lambda  nodejs function with Jest in Jest but continue to get this error. Is there any better way to AWS lambda functions using jest?</p>
<blockquote>
<p>ReferenceError: mockSsm is not defined</p>
</blockquote>
<p>Lambda function Index.js:</p>
<pre><code>var aws = require('aws-sdk');
var ses = new aws.SES();
var sns = new aws.SNS();
var ssm = new aws.SSM();
var cognitoidentityserviceprovider = new aws.CognitoIdentityServiceProvider();
var envPath = process.env.ssm_store;
var environment = {};


exports.handler = (event, context, callback) =&gt; {
    var envReq = getParameterFromSystemManager(envPath);
    envReq.then(async (env) =&gt; {

        environment = env;

        let userName = event.userName;
        let emailId = event.emailId;
        let emailSubject = event.emailSubject;
        let message = event.message;
        let phoneNumber = event.phoneNumber;

        let lang  = await getUserLanguage(userName);
        sendEmail(emailId, emailSubject, message);
        sendSMS(phoneNumber, message);

    }).catch((err) =&gt; {
        console.log('-error', err);
    });
};


function getUserLanguage(username) {
    return new Promise((resolve, reject) =&gt; {
        cognitoidentityserviceprovider.adminGetUser(paramWithData, (errDetail, UserAttributes) =&gt; {
            if (errDetail) {
                resolve('error');
            } else {
                resolve(UserAttributes.preferredLang);
            }
        });
    });
}

function sendEmail(to, subject, message) {
    ses.sendEmail(paramWithData, function (err, data) {
        if (err) {
            console.log(err);
        } else {
            console.log(data);
        }
    });
}

function sendSMS(phone, message) {
    sns.publish(paramWithData, function (err, data) {
        if (err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
        }
    });
}


function getParameterFromSystemManager(ssmpath) {
    return new Promise((resolve, reject) =&gt; {
        ssm.getParametersByPath(paramWithData, function (err, data) {
            if (err) {
                reject(false);
            }
            else {
                resolve(data);
            }
        });
    });
}
</code></pre>
<p>Test file Index.spec.js:</p>
<pre><code>const myHandler = require('../index.js').handler;

var aws = require('aws-sdk');

const mockSsm = jest.fn();
const mockSes = jest.fn();
const mockSns = jest.fn();
const mockCognito = jest.fn();

jest.mock('aws-sdk', () =&gt; {
    return {
        SSM: jest.fn(() =&gt; ({
            getParametersByPath: mockSsm
        })),
        SES: jest.fn(() =&gt; ({
          other1: mockSes
        })),
        SNS: jest.fn(() =&gt; ({
          other2: mockSns
        })),
        CognitoIdentityServiceProvider: jest.fn(() =&gt; ({
          other3: mockCognito
        }))
    };
});

describe('myHandler', () =&gt; {
  beforeEach(() =&gt; {
    jest.restoreAllMocks();
  });
  test('should return data', async () =&gt; {
    const mResponse = { data: 'testSSMResults' };
    mockSsm.mockImplementation((params) =&gt; {
      return {
          promise() {
              return Promise.resolve(mResponse)
          }
      };
    });
    const ssmparamValue = await myFunctions.getParameterFromSystemManager('');
    expect(ssmparamValue).toEqual(mResponse);
  });
});
</code></pre>
",https://stackoverflow.com/questions/62699845/error-on-mocking-multiple-servicessm-ses-sns-with-jest-lambda-nodejs-func,"['node.js', 'unit-testing', 'aws-lambda', 'jestjs']",694,False,1,0
"Unit testing runs two tests, &quot;Cannot declare class, because the name is already in use&quot;","<p>guys. I have two Unit Tests Classes in CakePhp:</p>
<pre><code>&lt;?php
App::import('Vendor/Laravel', 'Api');
class UserApi extends LaravelApi {
</code></pre>
<p>And</p>
<pre><code>&lt;?php
App::uses('Api', 'Vendor/Laravel');
App::import('Vendor/Laravel', 'Api');
App::import('Component', 'Session');
class LaravelApiTest extends CakeTestCase {
</code></pre>
<p>When I run my unit test (I will call it AllApp.php) that should run these two tests (and some other too), I get the message</p>
<pre><code>Fatal Error Error: Cannot declare class LaravelApi, because the name is already in use in [/var/www/html/app/Vendor/Laravel/Api.php, line 9]
</code></pre>
<p>I have tried by removing one of the two App:import('Vendor/Laravel', 'Api'); and &quot;AllApp.php&quot; runs fine, but of course, the individual test I modified fails because:</p>
<pre><code>Error: Class 'LaravelApi' not found
</code></pre>
<p>I think it is because these two files are not run at the same time when I run the individual test, but when I run them with &quot;AllApp&quot; the two files are loaded and the class gets &quot;required&quot; two times (even thought I think App::import is similar to &quot;require_once&quot;). Can anyone help me with this?</p>
",https://stackoverflow.com/questions/64017975/unit-testing-runs-two-tests-cannot-declare-class-because-the-name-is-already,"['php', 'unit-testing', 'cakephp', 'phpunit', 'require']",1215,False,1,0
Is there way to spyOnProperty window.location.search using jasmine unit testing? because search is not configurable,"<p>Its throwing error: search is not configurable</p>
<pre><code>it('should have search keyword', function () {
  spyOnProperty(window.location, 'search').and.returnValue(&quot;?q=jag&quot;);
  expect(window.location.search).toBe(&quot;?q=jag&quot;);
});
</code></pre>
",https://stackoverflow.com/questions/63683149/is-there-way-to-spyonproperty-window-location-search-using-jasmine-unit-testing,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",712,True,1,1
What is the best practice for unit testing my functional component with hooks in React Native?,"<p>I've written a simple wrapper component around ScrollView that enables/disables scrolling based on the available height it's given:</p>

<pre><code>import React, {useCallback, useEffect, useRef, useState} from 'react';
import {Keyboard, ScrollView} from 'react-native';
import {deviceHeight} from '../../../platform';

export default function ScrollingForm({
  availableHeight = deviceHeight,
  children,
}) {
  const [scrollEnabled, setScrollEnabled] = useState(true);
  const [formHeight, setFormHeight] = useState(0);
  const scrollingForm = useRef(null);

  const checkScrollViewEnabled = useCallback(() =&gt; {
    setScrollEnabled(formHeight &gt; availableHeight);
  }, [availableHeight, formHeight]);

  const onFormLayout = async event =&gt; {
    await setFormHeight(event.nativeEvent.layout.height);
    checkScrollViewEnabled();
  };

  useEffect(() =&gt; {
    Keyboard.addListener('keyboardDidHide', checkScrollViewEnabled);

    // cleanup function
    return () =&gt; {
      Keyboard.removeListener('keyboardDidHide', checkScrollViewEnabled);
    };
  }, [checkScrollViewEnabled]);

  return (
    &lt;ScrollView
      ref={scrollingForm}
      testID=""scrollingForm""
      keyboardDismissMode=""on-drag""
      keyboardShouldPersistTaps=""handled""
      scrollEnabled={scrollEnabled}
      onLayout={onFormLayout}
      onKeyboardDidShow={() =&gt; setScrollEnabled(true)}&gt;
      {children}
    &lt;/ScrollView&gt;
  );
}
</code></pre>

<p>I need to write unit tests for this component. So far I have:</p>

<pre><code>import React from 'react';
import {Keyboard} from 'react-native';
import {render} from 'react-native-testing-library';
import {Text} from '../..';
import ScrollingForm from './ScrollingForm';

describe('ScrollingForm', () =&gt; {
  Keyboard.addListener = jest.fn();
  Keyboard.removeListener = jest.fn();

  let renderer;
  describe('keyboard listener', () =&gt; {
    it('renders text with default props', () =&gt; {
      renderer = render(
        &lt;ScrollingForm&gt;
          &lt;Text&gt;Hello World!&lt;/Text&gt;
        &lt;/ScrollingForm&gt;,
      );
      expect(Keyboard.addListener).toHaveBeenCalled();
    });

    it('should call listener.remove on unmount', () =&gt; {
      renderer = render(
        &lt;ScrollingForm&gt;
          &lt;Text&gt;Goodbye World!&lt;/Text&gt;
        &lt;/ScrollingForm&gt;,
      );
      renderer.unmount();
      expect(Keyboard.removeListener).toHaveBeenCalled();
    });
  });
});
</code></pre>

<p>I want to also confirm that on layout if the available height is greater than the form height, that scrollEnabled is correctly being set to false. I've tried something like this:</p>

<pre><code>it('sets scrollEnabled to false onFormLayout width 1000 height', () =&gt; {
  mockHeight = 1000;
  const {getByTestId} = render(
    &lt;ScrollingForm availableHeight={500}&gt;
      &lt;Text&gt;Hello World!&lt;/Text&gt;
    &lt;/ScrollingForm&gt;,
  );
  const scrollingForm = getByTestId('scrollingForm');

  fireEvent(scrollingForm, 'onLayout', {
    nativeEvent: {layout: {height: mockHeight}},
  });
  expect(scrollingForm.props.scrollEnabled).toBe(false);
});
</code></pre>
",https://stackoverflow.com/questions/61736612/what-is-the-best-practice-for-unit-testing-my-functional-component-with-hooks-in,"['react-native', 'jestjs', 'react-native-testing-library']",706,False,5,0
Getting Cannot read property &#39;on&#39; of undefined in Unit Testing in Angular using Karma Jasmine,"<p>In my component.ts file, I have a service named 'socketService' where I'm using socket and in component, I have the line</p>
<pre><code>this.socket = this.socketService.getSocketIOConnector(this.data.product)
this.socket.on('connected', (message: string) =&gt; {
    this.connectionMsg = message
})
</code></pre>
<p>and in my spec.ts file, I have</p>
<pre><code>beforeEach(async(() =&gt; {
  fixture = TestBed.createComponent(OndemandComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
}));
it(&quot;should check socket service&quot;, inject([SocketioService], (socketioService: SocketioService) =&gt; {
  socketioService = TestBed.get(SocketioService);
  const spy = spyOn(socketioService, &quot;getSocketIOConnector&quot;);
  expect(spy).toHaveBeenCalled();
}));
it(&quot;should create&quot;, () =&gt; {
  expect(component).toBeTruthy();
});
</code></pre>
<p>It is giving me TypeError: Cannot read property 'on' of undefined while testing near this.socket.on in component.</p>
",https://stackoverflow.com/questions/65302152/getting-cannot-read-property-on-of-undefined-in-unit-testing-in-angular-using,"['angular', 'typescript', 'unit-testing', 'socket.io', 'karma-jasmine']",1916,True,0,1
How to separate existing code into presenter vs model for implementing MVP and Unit Testing,"<p>I am trying to refactor an existing WinForms app to use the Model-View-Presenter (MVP) pattern for the first time so that I can then write Unit Tests. I have a lot of existing code like the following which does not have a UI/View to worry about but I need to write Unit Tests for this validate function without actually causing a database call. How should I split this up for Model vs Presenter classes? I am uncertain how to extract a model class from this:</p>

<pre><code>Friend Sub ValidateAmountNotEntered(exp() As String, paramString As String, exp2() As String, paramString2 As String)
    Dim SqlStmt As String = ""[Long complex parameterized query to 
        Select values From 4 tables (T1 T2 T3 T4) 
        Where T1.Column1 = ?
        And T2.Column1 In ("" &amp; paramString &amp; "")  
        And T4.Column1 In ("" &amp; paramString2 &amp; "")  ]""

    Dim com As New OdbcCommand With {
        .Connection = New OdbcConnection(CommonUtilities.GetODBCConnectionString()),
        .CommandText = SqlStmt
    }

    com.Parameters.AddWithValue(""?"", CStr(GlngNum))
    For Each parameter As String In exp2
        com.Parameters.AddWithValue(""?"", parameter.Replace(""'"", String.Empty))
    Next
    For Each parameter As String In exp
        com.Parameters.AddWithValue(""?"", parameter.Replace(""'"", String.Empty))
    Next

    Dim adap As OdbcDataAdapter = New OdbcDataAdapter(com)
    Dim rsRates As New DataSet(""dsl"")
    adap.Fill(rsRates)
    For Each iteration_row As DataRow In rsRates.Tables(0).Rows
        AddErrorItem(iteration_row.Item(""T1.Column1""), ""R"", ""Amount for "" &amp; iteration_row.Item(""T4.Column1"").Trim() &amp; ""; "" &amp; iteration_row.Item(""T3.Column1"").Trim() &amp; "" not entered"")
    Next iteration_row
End Sub
</code></pre>

<p>Can anyone guide or provide an example?</p>
",https://stackoverflow.com/questions/60795338/how-to-separate-existing-code-into-presenter-vs-model-for-implementing-mvp-and-u,"['vb.net', 'unit-testing', 'refactoring', 'mvp', 'legacy-code']",32,True,0,1
Unit testing expired JWT token Bad &quot;options.expiresIn&quot; option the payload already has an &quot;exp&quot; property,"<p>I am trying to generate an already expired JWT token for testing purpose, but I can't figure out the right way to do it.</p>
<p>How do you manage expired time in unit tests ?</p>
<p>Here is my attempt so far :</p>
<pre><code>it('should return a new token if expired', async () =&gt; {
      const candidateId = 1
      const oneHourLessFromNow = Math.floor(Date.now() / 1000) - 3600
      const payload = { sub: candidateId, exp: oneHourLessFromNow }
      const initialToken = jwtService.sign(payload)
      const decodedInitialToken = jwtService.decode(initialToken)
      console.log(decodedInitialToken)
      expect(jwtService.verify(initialToken)).toThrowError('TokenExpiredError')
    })
</code></pre>
<p>Console error :</p>
<pre><code>● AuthService › refresh › should return a new token if expired

    Bad &quot;options.expiresIn&quot; option the payload already has an &quot;exp&quot; property.

      113 |       const oneHourLessFromNow = Math.floor(Date.now() / 1000) - 3600
      114 |       const payload = { sub: candidateId, exp: oneHourLessFromNow }
    &gt; 115 |       const initialToken = jwtService.sign(payload)
          |                                       ^
      116 |       const decodedInitialToken = jwtService.decode(initialToken)
      117 |       console.log(decodedInitialToken)
      118 |       expect(jwtService.verify(initialToken)).toThrowError('TokenExpiredError')

      at Object.module.exports [as sign] (../node_modules/jsonwebtoken/sign.js:133:20)
      at JwtService.sign (../node_modules/@nestjs/jwt/dist/jwt.service.js:27:20)
      at Object.&lt;anonymous&gt; (auth/auth.service.spec.ts:115:39)

  console.error
    undefined

      44 |       return this.createToken(candidateId)
      45 |     } catch (e) {
    &gt; 46 |       console.error(e)
         |               ^
      47 |       throw new HttpException(
      48 |         ResponseMessage.INVALID_CODE,
      49 |         HttpStatus.FORBIDDEN

      at AuthService.verifySmsCode (auth/auth.service.ts:46:15)

  console.log
    { sub: 1, iat: 1602496713, exp: 1602500313 }

      at AuthService.refresh (auth/auth.service.ts:59:13)
</code></pre>
",https://stackoverflow.com/questions/64315676/unit-testing-expired-jwt-token-bad-options-expiresin-option-the-payload-alread,"['typescript', 'unit-testing', 'jestjs', 'jwt']",2901,True,0,1
TypeError: seamless immutable _1.default is not a function - React native jest unit testing (Typescript),"<p>I am trying jest unit testing for typescript based react native project.Now I am stuck on one issue when do npm test. Error mentioned below</p>
<p>● Test suite failed to run</p>
<pre><code>TypeError: seamless_immutable_1.default is not a function

  34 | 
  35 | 
&gt; 36 | export const INITIAL_STATE: ImmutableAppReducerState = Immutable({
     |                                                                 ^
  37 |   activeTab: 0,
  38 |   showTab: false,
  39 |   tabName: &quot;&quot;,
</code></pre>
<p>My actual code was follows</p>
<p>import Immutable from &quot;seamless-immutable&quot;;</p>
<pre><code>export interface AppReducerState {
  activeTab?: number | undefined;
  showTab?: boolean | undefined;
  tabName?: string | undefined;
  isDrawerOpen: boolean;
  retryAction: AnyAction[];

}

/* ------------- Initial State ------------- */

type ImmutableAppReducerState = Immutable.Immutable&lt;AppReducerState&gt;


export const INITIAL_STATE: ImmutableAppReducerState = Immutable({
  activeTab: 0,
  showTab: false,
  tabName: &quot;&quot;,
  isDrawerOpen: false,
  retryAction: [],

});
</code></pre>
",https://stackoverflow.com/questions/64216428/typeerror-seamless-immutable-1-default-is-not-a-function-react-native-jest-u,"['typescript', 'react-native', 'unit-testing', 'jestjs', 'ts-jest']",911,True,0,1
How to use double to test exception handling in unit testing in ruby on rails?,"<p>I want to test my send method logic in my Client class. I have this so far in my client_spec file. How can i raise and error and test that rescue is called and the error is logged in my spec file. 
I am new to rspec but I believe i can use a test double for logging instead of calling actual logger.</p>

<p>client_spec.rb</p>

<pre><code>describe Client do

 describe '#send' do 
   let (:subject) {Client.new}

   it 'raises and logs the exception'
       //how to test raising and logging of the error
   end
 end
end
</code></pre>

<p>client.rb</p>

<pre><code>class Client
  include HTTParty 
  base_uri ""https://www.example.com""
  format :json

  def send
    begin 
      response = HTTParty.get(url)
      if response.successful?
        response 
      else
        raise 'invalid response'
      end
    rescue HTTParty::Error =&gt; e 
      logger.warn(e.message)
    end
  end
end
</code></pre>
",https://stackoverflow.com/questions/61177090/how-to-use-double-to-test-exception-handling-in-unit-testing-in-ruby-on-rails,"['ruby-on-rails', 'ruby']",918,False,0,2
Not able to read the values from ‘App.config’ file in the Unit testing project (Nunit),"<p>I have created one ‘nunit’ project in a visual studio which contains a simple one test. There is no default ‘App.config’ file available, so I have created one ‘App.config’ file. I have marked this file ‘Copy always’ from its ‘properties’ option.</p>
<p>I have tried to read the values from 'config' file is two ways 'ConfigurationManager.AppSettings' and 'system.configuration.configurationmanager.AppSettings'. but, It is showing empty values (null values)</p>
<p>Please see my code.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Text;
using log4net;
using NUnit.Framework;
using NUnitTestProject1.Config;
using NUnitTestProject1.Helper;

namespace NUnitTestProject1.AutomationTest
{
   [TestFixture, Order(3)]
    public class ReadDataThoughExcel
    {

        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

       [Test, Order(1)]
        public void IsUserReadDataThroughExcel() {

    string data1 = ConfigurationManager.AppSettings[&quot;name&quot;];
    Console.Write(&quot;Print data &quot;+data1);
    string data2 = system.configuration.configurationmanager.AppSettings[&quot;name&quot;];
    Console.Write(&quot;Print data &quot;+data2);
  }
 }
}

like so
</code></pre>
<p>Config file code is below:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;configuration&gt;
    &lt;ApplicationSettings&gt;
        &lt;add key=&quot;name&quot; value=&quot;Configuration Example Project&quot;/&gt;
    &lt;/ApplicationSettings&gt;
&lt;/configuration&gt;

like so
</code></pre>
<p><strong>Configuration details of my project:</strong></p>
<ol>
<li><strong>Dot.Net Framework:</strong> Microsoft.NET Framework version 4.7.0</li>
<li><strong>OS:</strong> window 10</li>
<li><strong>IDE:</strong> Visual studio 2019</li>
<li>Use <strong>Nunit framework</strong> for unit testing</li>
<li><strong>NUnit3TestAdapter</strong> (Version) 3.17.0</li>
<li><strong>Microsoft.NET.Test.Sdk</strong> (Version) 16.5.0</li>
<li><strong>System.Configuration.ConfigurationManager</strong> (Version) 4.7.0</li>
<li><strong>Selenium.Support</strong> (Version) 3.141.0</li>
</ol>
<p><strong>Note:</strong> Also, I have tried to add the reference of the ‘system.configuration’ to my project by right clicking on the 'Dependency' option (showing inside the project name in visual studio), however I am not able to see the option ‘system.configuration’ in the 'Type Libraries' option.</p>
",https://stackoverflow.com/questions/64609415/not-able-to-read-the-values-from-app-config-file-in-the-unit-testing-project,"['c#', 'selenium', 'frameworks', 'dependencies', 'nunit']",1938,True,0,1
Best way to handle a model relationship status/state when unit testing in Laravel 6?,"<p>I have the following unit test in Laravel 6.x, using SQLite:</p>

<pre><code>&lt;?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Entry;
use App\EntryStatus;
use Faker\Generator as Faker;

$factory-&gt;define(Entry::class, function (Faker $faker) {
    return [
        'user_id' =&gt; 1,
        'caption' =&gt; $faker-&gt;sentence(10),
        'entry_status_id' =&gt; EntryStatus::where('name', 'pending')-&gt;first()-&gt;id,
    ];
});

$factory-&gt;state(Entry::class, 'awaiting_payment', [
    'entry_status' =&gt; EntryStatus::where('name', 'awaiting_payment')-&gt;first()-&gt;id,
]);
</code></pre>

<p>I have a test error of 'Trying to get property 'id' of non-object', which is for the following line:</p>

<pre><code>'entry_status' =&gt; EntryStatus::where('name', 'awaiting_payment')-&gt;first()-&gt;id,
</code></pre>

<p>I have a few ideas on how to fix this error, but I'm wondering what the best practice here would be in terms of unit testing and 'The Laravel way'.</p>

<p>The way I have thought about this, I have an EntryStatus table which has static statues 'pending' => 0, 'awaiting_payment' => 1, 'paid' => 2 etc. And I create a relationship within my App\Entry model > App\EntryStatus. Ideas are as follows:</p>

<ol>
<li><p>The original plan; for the unit tests, I need to seed the static EntryStatus table each time for each test. Looking at the docs, I would use something like setUp() > $this->artisan('db:seed'). But this feels like it would really slow the tests. Unless there is a way to seed the DB once before all tests are started.</p></li>
<li><p>Try and create a factory which creates static data ('pending' => 0, 'awaiting_payment' => 1) but I'd manually need to update the database seed and the factory each time to match which seems clunky.</p></li>
<li><p>Within the Laravel docs testing documents they have this example; $factory->state(App\User::class, 'delinquent', ['account_status' => 'delinquent',]). This makes me think I could just remove the relationship table EntryStatus completely and just use a string column in the Entry to represent the state. I think this would be the best solution, but I'm worried that there is a reason we use ids as statuses as I'd imagine that they are quicker in search queries. But if not, my statues will be fixed, and this seems like the most eloquent solution.</p></li>
</ol>

<p>Another option would be to store the statues as integers anyway, keeping a note of what status is what integer, but again this doesn't seem correct.</p>
",https://stackoverflow.com/questions/60579833/best-way-to-handle-a-model-relationship-status-state-when-unit-testing-in-larave,"['laravel', 'unit-testing', 'laravel-6']",199,True,0,1
Unit Testing with IMongoQueryable. System.InvalidCastException: Unable to cast object of type EnumerableQuery to type IOrderedMongoQueryable,"<p>I have following Service with method GetAll() and I wrote test testing this method.</p>
<pre><code>public partial class DocumentTypeService : IDocumentTypeService
    {
        private readonly IRepository&lt;DocumentType&gt; _documentTypeRepository;
        private readonly IMediator _mediator;

        public DocumentTypeService(IRepository&lt;DocumentType&gt; documentTypeRepository, IMediator mediator)
        {
            _documentTypeRepository = documentTypeRepository;
            _mediator = mediator;
        }

        public virtual async Task&lt;IList&lt;DocumentType&gt;&gt; GetAll()
        {
            var query = from t in _documentTypeRepository.Table
                        orderby t.DisplayOrder
                        select t;
            return await query.ToListAsync();
        }
       
    }
</code></pre>
<p>This my test method GetAllDocumentTypes():</p>
<pre><code>[TestClass()]
    public class DocumentTypeServiceTests
    {
        private Mock&lt;IRepository&lt;DocumentType&gt;&gt; _documentTypeRepositoryMock;
        private DocumentTypeService _documentTypeService;
        private Mock&lt;IMediator&gt; _mediatorMock;
        private Mock&lt;IMongoQueryable&lt;DocumentType&gt;&gt; _mongoQueryableMock;
        private List&lt;DocumentType&gt; _expected;
        private IQueryable&lt;DocumentType&gt; _expectedQueryable; 

        [TestInitialize()]
        public void Init()
        {
            _mediatorMock = new Mock&lt;IMediator&gt;();
            _documentTypeRepositoryMock = new Mock&lt;IRepository&lt;DocumentType&gt;&gt;();
            _mongoQueryableMock = new Mock&lt;IMongoQueryable&lt;DocumentType&gt;&gt;();
            _expected =  new List&lt;DocumentType&gt;
            {
                new DocumentType() {Name = &quot;name1&quot;, Description = &quot;t1&quot;, DisplayOrder = 0},
                new DocumentType() {Name = &quot;name2&quot;, Description = &quot;t2&quot;, DisplayOrder = 1}
            };
            _expectedQueryable = _expected.AsQueryable();
            _mongoQueryableMock.Setup(x =&gt; x.ElementType).Returns(_expectedQueryable.ElementType);
            _mongoQueryableMock.Setup(x =&gt; x.Expression).Returns(_expectedQueryable.Expression);
            _mongoQueryableMock.Setup(x =&gt; x.Provider).Returns(_expectedQueryable.Provider);
            _mongoQueryableMock.Setup(x =&gt; x.GetEnumerator()).Returns(_expectedQueryable.GetEnumerator());
                                  
            _documentTypeRepositoryMock.Setup(x =&gt; x.Table).Returns(_mongoQueryableMock.Object);
            _documentTypeService = new DocumentTypeService(_documentTypeRepositoryMock.Object, _mediatorMock.Object);
        }

        
        [TestMethod()]
        public async Task GetAllDocumentTypes()
        {
            var actual = await _documentTypeService.GetAll();
            Assert.AreEqual(_expected.Count, actual.Count);
        }
    }
</code></pre>
<p>Get error:</p>
<pre><code>Message: 
    Test method Grand.Services.Tests.Documents.DocumentTypeServiceTests.GetAllDocumentTypes threw exception: 
    System.InvalidCastException: Unable to cast object of type 'System.Linq.EnumerableQuery`1[Grand.Domain.Documents.DocumentType]' to type 'MongoDB.Driver.Linq.IOrderedMongoQueryable`1[Grand.Domain.Documents.DocumentType]'.
  Stack Trace: 
    MongoQueryable.OrderBy[TSource,TKey](IMongoQueryable`1 source, Expression`1 keySelector)
    DocumentTypeService.GetAll() line 38
    DocumentTypeServiceTests.GetAllDocumentTypes() line 101
    ThreadOperations.ExecuteWithAbortSafety(Action action)
</code></pre>
<p>Could you please explain me why type is not IOrderedMongoQueryable and how solve this issue? Thank you</p>
",https://stackoverflow.com/questions/63879412/unit-testing-with-imongoqueryable-system-invalidcastexception-unable-to-cast-o,"['c#', 'asp.net-core', 'moq', 'mongodb-.net-driver']",576,False,0,1
Unit testing a repository - how to deal with mocking services and dbcontext in .Net Core?,"<p>I'm attempting to unit test a relatively simple repository but I've had difficulty figuring out the best approach for dealing with the services and database contexts that the repository requires to be instantiated.</p>

<p>The repository has one public method, which returns a Member object:</p>

<pre><code>public class MemberRepository : IMemberRepository
{
    private OServiceContext _openService;
    private OpenDbContext _openDbContext;

    public MemberRepository(OServiceContext openService, OpenDbContext openDbContext)
    {
        _openService = openService;
        _openDbContext = openDbContext;
    }

    public async Task&lt;Member&gt; GetMember(int policyMemberId, int policyActivityId)
    {
        Member member = null;

        var members = await _openDbContext.PolicyMembers
            .Include(c =&gt; c.Contact)
            .SingleOrDefaultAsync(x =&gt; x.PolicyActivityKey == policyActivityId &amp;&amp; x.PolicyMemberKey == policyMemberId);

        if (members != null)
        {
            member = ConvertDataToMember(members);
        }

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

<p>The ServiceContext collates four distinct services whose purposes are relatively clear from the CTOR:</p>

<pre><code>public OServiceContext(OpenConfiguration config)
    {
        _username = config.Username;
        _password = config.Password;

        _authenticationService = new AuthenticationService(config.GetEndpointConfigurationFor(nameof(AuthenticationService)));
        _dataService = new DataService(config.GetEndpointConfigurationFor(nameof(DataService)));
        _workflowService = new WorkflowService(config.GetEndpointConfigurationFor(nameof(WorkflowService)));
        _documentService = new DocumentService(config.GetEndpointConfigurationFor(nameof(DocumentService)));

        var viewClasses = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(x =&gt; x.GetTypes())
            .Where(x =&gt; typeof(IOpenHostView).IsAssignableFrom(x) &amp;&amp; !x.IsInterface &amp;&amp; !x.IsAbstract &amp;&amp; x.IsPublic)
            .Select(x =&gt; x)
            .ToList();

        foreach (var c in viewClasses)
        {
            var attribute = c.GetCustomAttributesData()
                .FirstOrDefault(x =&gt; x.AttributeType == typeof(OpenViewAttribute));

            if (attribute == null)
                throw new NullReferenceException($""Unable to find '{nameof(OpenViewAttribute)}' on {nameof(IOpenView)} implementation $'{c.Name}'."");

            var viewName = attribute.ConstructorArguments[0].Value.ToString();
            var viewConfig = config.GetViewConfigurationFor(viewName);

            if (viewConfig == null)
                throw new NullReferenceException($""Unable to locate key for Open view '{viewName}'."");

            _viewLookup.Add(c, viewConfig.Key);
        }
    }
</code></pre>

<p>The test as it stands:</p>

<pre><code>    [Fact]
    public void MemberRepository_GetMember_ReturnsValidMember()
    {
        //Arrange

        var mockOServiceConfig = new OpenConfiguration()
        {
            Username = ""test"",
            Password = ""pass"",
            Remoting = new OpenRemotingConfiguration(),
            Endpoints = new List&lt;OpenHEndpointConfiguration&gt;(){
                new OpenEndpointConfiguration {
                    Reference = ""test"", ServiceUrl = ""test"", DatabaseKey = 1, EnableMessageLogging = true
                } },
            Views = new List&lt;OpenViewConfiguration&gt;(),
            Entities = new List&lt;OpenEntityConfiguration&gt;()
        };
        var mockOServiceContext = new Mock&lt;OServiceContext&gt;(mockOServiceConfig);
        var mockOpenDbContext = new Mock&lt;OpenDbContext&gt;();
        var mockOpenDbSet = new Mock&lt;DbSet&lt;Member&gt;&gt;();

        mockOpenDbSet.Setup(s =&gt; s.Find(It.IsAny&lt;int&gt;())).Returns(new Member());
        mockOpenDbContext.Setup(s =&gt; s.Set&lt;Member&gt;()).Returns(mockOpenDbSet.Object);

        //Act
        var memberRepository = new MemberRepository(mockOServiceContext.Object, mockOpenDbContext.Object);
        var member = memberRepository.GetMember(1, 1);

        //Assert
        Assert.NotNull(member);
        Assert.IsAssignableFrom&lt;Member&gt;(member);
    } 
}
</code></pre>

<p>This hits an error -</p>

<blockquote>
  <p>System.NullReferenceException: 'Object reference not set to an instance of an object.' config was null.</p>
</blockquote>

<p>Basically the params aren't valid for the config when sent to the AuthenticationService. But my question isn't really about fixing the error. Is going down the rabbit hole of trying to pass correct mocked params for all these services really the best approach? Surely there's a better way to mock this when all I want to actually test is a relatively trivial Get method?</p>

<p>Also I'm aware that depending on how you approach the mocked services and data, the unit test can mutate into a integration test. I'd just like to hear the thoughts of anyone who has dealt with something similar. This is honestly the first time I've tried to unit test a repository and while I've tried to consume as much as I can on the topic I would genuinely appreciate any guidance.</p>
",https://stackoverflow.com/questions/59761157/unit-testing-a-repository-how-to-deal-with-mocking-services-and-dbcontext-in,"['c#', 'unit-testing', 'asp.net-core', 'repository', 'dbcontext']",169,False,0,0
I am very new to python testing. Help this method with explanation for unit testing,"<p><strong>This function will take input and calls the login function based on input.</strong>     </p>

<pre><code>def login_features():
print(""Choose option to login"")
print(""1. BDO login"")
print(""2. GPM login"")
print(""3. Member login"")
login_input = int(input())
switcher = {
    1: bdo_login,
    2: gpm_login, # I am calling the function instance
    3: member_login
}
login = switcher.get(login_input, login_features)
login() # Executing the called function
</code></pre>
",https://stackoverflow.com/questions/59866639/i-am-very-new-to-python-testing-help-this-method-with-explanation-for-unit-test,"['python', 'unit-testing', 'mocking']",54,True,-2,1
How do I do unit testing for oracle stored procedure call in spring boot JUnit 5,"<p>I am using spring-boot-starter-data-jpa and have Oracle stored procedure calls. How do I do unit testing and code coverage for this scenario.  Below is sample code</p>
<pre><code>StoredProcedureQuery userProcedure = entityManager.createStoredProcedureQuery(&quot;STOREDPROCNAME&quot;);
String param1 = &quot;p_search_string&quot;;
String param2 = &quot;p_start_position&quot;;
String param3 = &quot;P_worday_users&quot;;


userProcedure.registerStoredProcedureParameter(param1, String.class, ParameterMode.IN);
userProcedure.registerStoredProcedureParameter(param2, String.class, ParameterMode.IN);
userProcedure.registerStoredProcedureParameter(param3, void.class, ParameterMode.REF_CURSOR);
userProcedure.setParameter(param1, searchText);

List&lt;Object[]&gt; results = userProcedure.getResultList();
</code></pre>
<ol>
<li><p>Can I use in memory db instead oracle for unit testing?</p>
</li>
<li><p>How to do  unit testing for native query?</p>
<p>@Query(value = &quot;SELECT SCHEMA.ID_SEQ.nextval FROM dual&quot;, nativeQuery = true)
public int getPkgIdSeq();</p>
</li>
</ol>
",https://stackoverflow.com/questions/64150924/how-do-i-do-unit-testing-for-oracle-stored-procedure-call-in-spring-boot-junit-5,"['java', 'spring', 'spring-boot', 'unit-testing', 'spring-data-jpa']",555,False,4,0
Unit testing for service with multiple API calls in parallel using Karma and Jasmine / Angular 8,"<p>I am trying to write unit tests (Jasmine and Karma) for a service and a component whose aim is to perform two API calls to the Star Wars API (more info at <a href=""https://swapi.co/"" rel=""nofollow noreferrer"">https://swapi.co/</a>) with two different <code>URLS</code>, to get people and starships data. Both calls are returned simultaneously with a <code>forkJoin</code>.</p>

<p>My <code>App</code> component calls the <code>ApiService</code> to perform two calls as follows:</p>

<p>APP COMPONENT:</p>

<pre><code>import {Component, OnInit} from '@angular/core';
import {ApiService} from '../services/api.service';

export class AppComponent implements OnInit {

  constructor(private apiService: ApiService) {}

onGetData() {
    this.apiService.getData().subscribe((data: any) =&gt; {

      this.peopleData = data[0];
      this.starshipData = data[1];

     });

  }
</code></pre>

<p>API SERVICE:</p>

<pre><code>import {HttpClient} from '@angular/common/http';

export class ApiService {
  constructor(private http: HttpClient) {}

  getData(): Observable&lt;any[]&gt; {
    const randomPeoplePage = Math.floor(Math.random() * 9) + 1;
    const peopleUrl = `https://swapi.co/api/people/?page=${randomPeoplePage}`;

    const randomStarshipsPage = Math.floor(Math.random() * 4) + 1;
    const starshipsUrl = `https://swapi.co/api/starships/?page=${randomStarshipsPage}`;

    const peopleProm = this.http.get(peopleUrl);
    const starshipProm = this.http.get(starshipsUrl);

    return forkJoin([peopleProm, starshipProm]);

  }
}
</code></pre>

<p>I am fairly inexperienced with testing, especially on how to test API calls properly. 
I have been trying different solutions for the past couple of days, something like this:</p>

<pre><code> it('should return an Observable', () =&gt; {
    const randomPeoplePage = Math.floor(Math.random() * 9) + 1;
    const randomStarshipsPage = Math.floor(Math.random() * 4) + 1;


    const dummyData = [
      {
        count: 87,
        next: `https://swapi.co/api/people/?page=${randomPeoplePage + 1}` || null,
        previous: `https://swapi.co/api/people/?page=${randomPeoplePage - 1}` || null,
        results: new Array(87)
      },
      {
        count: 37,
        next: `https://swapi.co/api/starships/?page=${randomStarshipsPage + 1}` || null,
        previous: `https://swapi.co/api/starships/?page=${randomStarshipsPage - 1}` || null,
        results: new Array(37)
      }
    ];

    service.getData().subscribe(data =&gt; {
      expect(data.length).toBe(2);
      expect(data).toEqual(dummyData);

      const peopleReq = httpMock.expectOne(`https://swapi.co/api/people/?page=${randomPeoplePage}`);
      const starshipReq = httpMock.expectOne(`https://swapi.co/api/starships/?page=${randomStarshipsPage}`);

      forkJoin([peopleReq, starshipReq]).subscribe(() =&gt; {
        expect(peopleReq.request.method).toBe('GET');
        expect(starshipReq .request.method).toBe('GET');
      })

      peopleReq.flush(dummyData[0]);
      starshipReq.flush(dummyData[1]);

    });


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

<p>but this test isn't passing and I am really not sure why or what should I look into. 
Do I need to test the API calls in the <code>api.service.spec.ts</code> or in the <code>app.component.spec.ts</code>? 
How do I simulate the return? Should I test them singularly?
This is an 'academic' test, therefore any hint for best practice is welcome.</p>

<p>Thanks a lot!</p>
",https://stackoverflow.com/questions/59923374/unit-testing-for-service-with-multiple-api-calls-in-parallel-using-karma-and-jas,"['angular', 'api', 'testing', 'karma-jasmine']",2591,True,2,1
Angular Unit Testing with Dynamic Component Failed with error TypeError: Cannot read property &#39;ɵcmp&#39; of undefined,"<p>list of Angular dependency </p>

<pre><code>    ""@angular/common"": ""~9.1.1"",
    ""@angular/compiler"": ""~9.1.1"",
    ""@angular/core"": ""~9.1.1"",
    ""@angular/forms"": ""~9.1.1"",
    ""@angular/platform-browser"": ""~9.1.1"",
    ""@angular/platform-browser-dynamic"": ""~9.1.1"",
    ""@angular/router"": ""~9.1.1"",
    ""@fortawesome/fontawesome-free"": ""^5.13.0""
</code></pre>

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

<pre><code>import { Component, ViewChild, OnDestroy, AfterViewInit  } from '@angular/core';
import { ComponentFactoryResolver, Type, ComponentRef, ChangeDetectorRef } from '@angular/core';
import { Subject } from 'rxjs';

import { DynamicCompDirective } from '../../directive/dynamic-comp.directive';
import { DialogRef } from '../../model/dialog.ref';

@Component({
  selector: 'app-dialog-layout',
  templateUrl: './dialogLayout.component.html',
  styleUrls: ['./dialogLayout.component.css']
})
export class DialogLayoutComponent implements AfterViewInit, OnDestroy {

  @ViewChild(DynamicCompDirective, {static: true})insertionPoint: DynamicCompDirective;

  dialogHeight: number;
  dialogWidth: number;
  backDrop: boolean = false;

  public componentRef: ComponentRef&lt;any&gt;;
  public childComponentType: Type&lt;any&gt;;

  private readonly _onClose = new Subject&lt;any&gt;();
  public onClose = this._onClose.asObservable();


  constructor(private resolver: ComponentFactoryResolver,
              private cd: ChangeDetectorRef,
              private dialogRef: DialogRef) { }

  ngAfterViewInit() {
    this.loadChildComponent(this.childComponentType);
    this.cd.detectChanges();
  }

  ngOnDestroy() {
    if (this.componentRef) {
        this.componentRef.destroy();
    }
  }

  onOverlayClicked(evt: MouseEvent) {
    if (this.backDrop) {
      this.dialogRef.close();
    }
  }

  onDialogClicked(evt: MouseEvent) {
    evt.stopPropagation()
  }

  loadChildComponent(componentType: Type&lt;any&gt;) {
    const componentFactory = this.resolver.resolveComponentFactory(componentType);
    const viewContainerRef = this.insertionPoint.container;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
  }

  close() {
    this._onClose.next();
  }

}
</code></pre>

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

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ChangeDetectorRef } from '@angular/core';
import { DialogLayoutComponent } from './dialogLayout.component';
import { DialogRef } from '../../model/dialog.ref';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ DialogLayoutComponent ],
      providers: [ { provide: DialogRef, useClass: DialogRef } ]
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p><strong>dialog.ref.ts</strong></p>

<pre><code>import { Observable, Subject } from 'rxjs';

export class DialogRef {

  constructor() {}

  private readonly _afterClosed = new Subject&lt;any&gt;();

  afterClosed: Observable&lt;any&gt; = this._afterClosed.asObservable();

  public close(result?: any): void {
    this._afterClosed.next(result);
  }

}
</code></pre>

<p>My unit testing failed with error <strong>TypeError: Cannot read property 'ɵcmp' of undefined</strong></p>

<p>No clue where this error is coming from. Already spend 2 days googling this error, but no luck. Kindly help to resolve the issue.</p>

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

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/61295161/angular-unit-testing-with-dynamic-component-failed-with-error-typeerror-cannot,"['angular-unit-test', 'angular-dynamic-components', 'angular-dependency-injection']",7856,False,2,1
How to check expected log in the middle of a running function using Jest unit testing?,"<p>I have this demo function:</p>

<pre><code>export async function myHandler(
    param1: string,
    param2: string,
    req: Request,
    next: NextFunction,

) {
    const log = req.log.prefix(`[my=prefix]`);
    let res;
    If (param1 === 'param1') {
        log(""GOT PARAM 1"");
    } else {
        res = await doSomething();
    }
    log(""GOT HERE"");
    ..
    ..
    ..
    ..
    res.setReturnStatus(200)
    }
    next();
}
</code></pre>

<p>regarding the logger, this is the request that contains it:</p>

<pre><code> const req: {
url: string;
params: {};
body: {
    device: {
        type: string;
        p1: string;
        p2: string;
        p3: string;
    };
    data: {
        sample: number;
    };
};
metric: () =&gt; jest.Mock&lt;any, any&gt;;
log: {
    (): jest.Mock&lt;any, any&gt;;
    warn(): jest.Mock&lt;...&gt;;
    error(): jest.Mock&lt;...&gt;;
    prefix(): jest.Mock&lt;...&gt;;
};
timing: () =&gt; jest.Mock&lt;...&gt;;
</code></pre>

<p>}</p>

<p>When I wrote my unit test my line is checking the return status:     <code>expect(res.status).toBeCalledWith(200);</code></p>

<p>I want to cover the first 'if' statement, which logs 'GOT PARAM 1' but can't figure out how to intercept my call in the middle.</p>

<pre><code>doSomething = jest.fn(() =&gt; Promise.resolve());
await myHandler('param1', 'param1', next); //HERE to check somehow that also was log ?
expect(res.status).toBeCalledWith(200);
</code></pre>

<p>tried to do something like : </p>

<pre><code>const spy = jest.spyOn(req.log, 'log');
</code></pre>

<p>got the error:</p>

<pre><code>Cannot spy the log property because it is not a function; undefined given instead
</code></pre>
",https://stackoverflow.com/questions/62189004/how-to-check-expected-log-in-the-middle-of-a-running-function-using-jest-unit-te,"['javascript', 'typescript', 'unit-testing', 'testing', 'jestjs']",131,True,1,1
object reference not set to instance of an object issues in unit testing of asp.net mvc,"<p>I am the beginner of writing unit tests for asp.net. I created a simple project and try to start my testing journey. However, I met two errors with the same issue:""object reference not set to instance of an object"" The first place is in the home controller as below:</p>

<pre><code>public class HomeController : Controller
{
    private readonly ILogger&lt;HomeController&gt; _logger;

    public HomeController(ILogger&lt;HomeController&gt; logger)
    {
        _logger = logger;
    } 

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
</code></pre>

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

<pre><code>public class HomeControllerUnitTests
{
     ILogger&lt;HomeController&gt; _logger;

     [Fact]
     public void Error_ActionExecutes_ReturnsAViewResult()
     {
        // Arrange
        var homeController = new HomeController(_logger);

        // Act
        var result = homeController.Error() as ViewResult;

        // Assert
        Assert.Null(result.ViewData.Model);
     }
}
</code></pre>

<p>The second place is in the Movie Controller:</p>

<pre><code>public class MoviesController : Controller
{
        private readonly MvcMovieContext _context;

        public MoviesController(MvcMovieContext context)
        {
            _context = context;
        }

        // GET: Movies
        public async Task&lt;IActionResult&gt; Index()
        {
            return View(await _context.Movie.ToListAsync());
        }
}
</code></pre>

<p>My test method is as below:</p>

<pre><code>public class MoviesControllerUnitTests
{
        private Mock&lt;MvcMovieContext&gt; _mock;

        [Fact]
        public async Task Index_ActionExecutes_ReturnsAViewResult()
        {
            // Arrange
            MoviesController controller = new MoviesController(_mock.Object);

            // Act
            var result = await controller.Index() as Task&lt;ViewResult&gt;;

            // Assert
            Assert.IsType&lt;ViewResult&gt;(result);
        }
    }
</code></pre>

<p>Please help me and thanks in advance.</p>
",https://stackoverflow.com/questions/61830362/object-reference-not-set-to-instance-of-an-object-issues-in-unit-testing-of-asp,"['asp.net', 'unit-testing', 'model-view-controller']",1576,True,1,1
Is there any way in which we can stub meteor functions using cypress for unit testing?,"<p>I am trying to stub meteor methods and API Cypress unit testing.
My api services are deployed on spring container. [produces and consumes JSON]</p>

<p>Tried using the below code for API stubbing: </p>

<pre><code>cy.server()
cy.fixture('samplejson.json').as('sample')
cy.route('POST','https://myURL/host/login', '@sample')
</code></pre>

<p>This doesn't intercept the API call as its not a XHR request (using REST APIs).</p>

<p>Also, since the meteor framework uses a definite template for its template.js file, not sure how to stub the methods with <code>cy.stub()</code>.</p>

<p>If anyone is able to successfully stub Meteor calls such as <code>Meteor.call()</code>(in client side) or <code>HTTP.call()</code>(in methods.js), please share any references or examples.</p>

<p>Thanks</p>

<p><a href=""https://i.stack.imgur.com/HDpzR.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HDpzR.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/59752446/is-there-any-way-in-which-we-can-stub-meteor-functions-using-cypress-for-unit-te,"['javascript', 'unit-testing', 'meteor', 'mocha.js', 'cypress']",191,False,1,0
Could not find &quot;store&quot; in the context of &quot;Connect(Home)&quot; in react native jest unit testing?,"<p>I am new to react native. trying to write unit test cases. but I am getting following error.</p>

<p>My test cases failing as bellow</p>

<p>Could not find ""store"" in the context of ""Connect(Home)"". Either wrap the root component in a , or pass a custom React context pr
ovider to  and the corresponding React context consumer to Connect(Home) in connect options.</p>

<p>home.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>/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-unused-vars */
import React, { Component } from 'react';
import { ActivityIndicator } from 'react-native-paper';
import {
  View, Text, FlatList, TouchableOpacity,
} from 'react-native';
import { connect } from 'react-redux';
//import { Ionicons } from '@expo/vector-icons';
import styles from './style';
import { listRepos } from '../../reducer/reducer';
import ErrorAlert from '../../common/errorAlertComponent/errorAlert';


class Home extends Component {
  componentDidMount() {
    this.props.listRepos();
  }

  FlatListItemSeparator = () =&gt; (
    &lt;View style={styles.flatListItemSeparator} /&gt;
  )

  renderItem = ({ item }) =&gt; (

    &lt;View style={styles.listRowContainer}&gt;

      &lt;TouchableOpacity onPress={() =&gt; this.props.navigation.navigate('ThumbnailViewScreen', {
        albumID: item.id,
      })} style={styles.listRow}&gt;
        &lt;View style={styles.listTextNavVIew}&gt;
          &lt;Text style={styles.albumTitle}&gt; {item.title} &lt;/Text&gt;
        &lt;/View&gt;
      &lt;/TouchableOpacity&gt;

    &lt;/View&gt;
  );

  render() {
    const { error, loading, albums } = this.props;

    if (error) {
      return &lt;ErrorAlert /&gt;;
    }

    if (loading) {
      return (
        &lt;View style={{ flex: 1, paddingTop: 30 }}&gt;
            &lt;ActivityIndicator animating={true} size='large' /&gt;
        &lt;/View&gt;
      );
    }
    return (
      &lt;View style={styles.MainContainer} &gt;
        &lt;FlatList
          styles={styles.container}
          data={albums}
          renderItem={this.renderItem}
          ItemSeparatorComponent={this.FlatListItemSeparator}

        /&gt;
      &lt;/View&gt;
    );
  }
}

const mapStateToProps = (state) =&gt; {
  const storedRepositories = state.albums.map((repo) =&gt; ({ key: repo.id.toString(), ...repo }));
  return {
    albums: storedRepositories,
    loading: state.loading,
    error: state.error,
  };
};

const mapDispatchToProps = {
  listRepos,
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);</code></pre>
</div>
</div>
</p>

<p>home.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>/* eslint-disable max-len */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
import React, { Component } from 'react';
import 'react-native';
import { shallow } from 'enzyme';
import expect from 'expect';

import renderer from 'react-test-renderer';

import __Home from '../component/HomeComponent/home';


describe('home  Screen', () =&gt; {
  it('should render home component', () =&gt; {
    const wrapper = shallow(
        &lt;__Home navigation={{ getParam: jest.fn() }} /&gt;,
    );
  });

  });</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/60488531/could-not-find-store-in-the-context-of-connecthome-in-react-native-jest-un,"['react-native', 'unit-testing', 'jestjs', 'enzyme']",1611,False,1,2
How to perform unit testing on the methods which print to console using console.log in angualr9?,"<p>I have a method defined as :</p>

<pre><code> public log(...logMsg) {
    if (isDebug)
      consoleLog('log', logMsg);
  }
</code></pre>

<p>Is there any possible way that we can conduct unit testing on this method using jasmine and karma frameworks?</p>
",https://stackoverflow.com/questions/62320351/how-to-perform-unit-testing-on-the-methods-which-print-to-console-using-console,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",343,False,0,1
How to write unit testing code for Async type method which use linq query inside it,"<p>My project is using mvc5 in repository pattern and now i've a method in my ScreenManager. Now I've
to write test code for a method which is async type and inside it uses linq query on my repository class. I already wrote a test code(see in bellow) for it but it didn't working. Please help me to get out of this problem.</p>

<p>Error:</p>

<blockquote>
  <p>Test Failed -
  ActionHistoryAsync_WhenCalled_ReturnSceeningActionViewModel Message:
  Test method
  ScreenMangerTests.ActionHistoryAsync_WhenCalled_ReturnScreenActionViewModel
  threw exception: System.InvalidOperationExcetpion: The source
  IQueryable doesn't implement.
  IDbAsyncEnumerable.Only sources that implement
  IDbAsyncEnumerable can be used for Entity Framework asynchronous
  operations. For more details see
  <a href=""http://go.microsoft.com/fwlink/?LinkId=287068"" rel=""nofollow noreferrer"">http://go.microsoft.com/fwlink/?LinkId=287068</a></p>
</blockquote>

<p><strong>I've a repository named</strong> </p>

<p><code>private readonly IScreenActionRepository _iScreenActionRepository;</code></p>

<p><strong>And I'm Passing it through my constructor.</strong></p>

<pre><code>public ScreenManager(IScreenActionRepository iScreenActionRepository)
{
  _iScreenActionRepository= iScreenActionRepository;
}
</code></pre>

<p><strong>And finally my Executable method is following</strong> </p>

<pre><code> public async Task&lt;IEnumerable&lt;ScreenActionViewModel&gt;&gt; ActionHistoryAsync(long screenId)
        {
                   var result = from a in _iScreenActionRepository.FindAll(s =&gt; s.ScreenId == screenId &amp;&amp; s.ScreenType == ""T"")                         
                         select new ScreenActionViewModel
                         {
                             Id = a.Id,
                             ScreenId = a.ScreeningId,
                             ScreeningType = a.ScreenType,
                             Description = a.Description,
                             ActionDateTime = a.ActionDateTime,
                             ActionBy = a.ActionBy,
                             RoleName = a.RoleName,
                         };

            var z = result.ToList();
            return await result.ToListAsync();
        }
</code></pre>

<p><strong>And my testing code is following</strong> </p>

<pre><code>[DataTestMethod]
public async Task ActionHistoryAsync_WhenCalled_ReturnScreenActionViewModel()
        {
    Mock&lt;IScreenActionRepository&gt; _screenActionRepositoryMock= new Mock&lt;IScreenActionRepository&gt;();
            long screenId = 1;
            var screenAction = new List&lt;ScreenAction&gt;
            {
                new ScreenAction
                {
                    ScreenId = 1,
                    ScreenType = ""TP"",
                    Description = """",
                    ActionDateTime = DateTime.Now,
                    ActionBy = 3,
                    RoleName = ""Investigator""
                }
            };           
            _screenActionRepositoryMock
                .Setup(c =&gt; c.FindAll(It.IsAny&lt;Expression&lt;Func&lt;ScreenAction, bool&gt;&gt;&gt;()))
                .Returns(new Func&lt;Expression&lt;Func&lt;ScreenAction, bool&gt;&gt;, IQueryable&lt;ScreenAction&gt;&gt;(
                    expr =&gt; screenAction.Where(expr.Compile()).AsQueryable()));

            //Act
            var result = await _manager.ActionHistoryAsync(screenId);

            //Assert
            Assert.AreEqual(result.First().ActionBy, 3);
            Assert.AreEqual(result.First().RoleName, ""Investigator"");
            Assert.AreEqual(result.First().UserFullName, userList.First().FullName);
        }
</code></pre>
",https://stackoverflow.com/questions/60294256/how-to-write-unit-testing-code-for-async-type-method-which-use-linq-query-inside,"['c#', 'entity-framework', 'linq', 'unit-testing', 'async-await']",300,False,0,0
How to delete the collection data on mongodb while doing unit testing with mocha and chai,"<p>I am stuck one issue where I am unit testing of API's with mongodb. I am using Mocha and Chai for unit testing, however I am facing issue that when I am test second case I need to empty the mongodb collection so new data will come and test automatically, but I could not find anything how to delete the collection every time before unit test code run. </p>

<p>Please see below my unit test code</p>

<p>test.js</p>

<pre><code>process.env.NODE_ENV = 'test';
let mongoose = require(""mongoose"");
let chai = require('chai');
let chaiHttp = require('chai-http');
const expect = require('chai').expect;
const request = require('supertest');

const app = require('../../../app.js');
const conn = require('../../../db/index.js');

chai.use(chaiHttp);
describe('notes', () =&gt; {
  beforeEach((done) =&gt; { //Before each test we empty the database
      Book.remove({}, (err) =&gt; { 
         done();           
      });        
  });
});


describe('GET /notes', () =&gt; {
  before((done) =&gt; {
    conn.connect()
      .then(() =&gt; done())
      .catch((err) =&gt; done(err));
  })

  after((done) =&gt; {
    conn.close()
      .then(() =&gt; done())
      .catch((err) =&gt; done(err));
  })

  it('OK, getting notes has no notes', (done) =&gt; {
    request(app).get('/notes')
      .then((res) =&gt; {
        const body = res.body;
        expect(body.length).to.equal(0); // getting error here as collection have data
        // res.should.have.status(200);

        done();
      })
      .catch((err) =&gt; done(err));
  });
</code></pre>

<blockquote>
  <p>app.js</p>
</blockquote>

<pre><code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const Note = require('./db/models/note.js').Note;

app.use(bodyParser.json());

app.get('/notes', (req, res) =&gt; {
  Note.find()
    .then((notes) =&gt; res.status(200).send(notes))
    .catch((err) =&gt; res.status(400).send(err));
});

app.post('/notes', (req, res) =&gt; {
  const body = req.body;
  const note = new Note({
    name: body.name,
    text: body.text
  });
  note.save(note)
    .then((note) =&gt; res.status(201).send(note))
    .catch((err) =&gt; res.status(400).send(err));
});

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

<p>please suggest me how can I delete the mongodb collection before the unit test?</p>

<p>Thanks in advance </p>
",https://stackoverflow.com/questions/60053457/how-to-delete-the-collection-data-on-mongodb-while-doing-unit-testing-with-mocha,"['node.js', 'mongodb', 'mocha.js', 'chai']",666,False,0,0
How do i mock the behavior of a void method when unit testing my delete service?,"<p>I'm currently unit testing the endpoints of a Spring Boot CRUD RESTful API and i have the following <strong>""Delete user by its id""</strong> endpoint that's composed of a <strong>controller</strong> and a <strong>service</strong> to implement its logic :</p>

<p>Delete controller (it's mainly calling the logic of the service and defining some guidelines) :</p>

<pre><code> @RestController
    @RequestMapping(""/users/{id}"")
    public class DeleteUserController {

        @Autowired
        DeleteUserService service;

        @DeleteMapping
        @ResponseStatus(HttpStatus.NO_CONTENT)
        public void deleteUser_whenDeleteUser(@PathVariable Long id) {
            service.deleteUser(id);
        }
    }
</code></pre>

<p>Delete service :</p>

<pre><code>@Service
public class DeleteUserService {

    @Autowired
    UserRepository repository;

    public void deleteUser(Long id) {

        repository.findById(id)
                .orElseThrow(() -&gt; new UserNotFoundException(id));

        repository.deleteById(id);
    }
}
</code></pre>

<p>While everything seems to be working fine until now, i'd be grateful if someone could tell me what i could improve in the code above. Anyways, My controllers unit test is the problem i can't seem to solve :</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(DeleteUserService.class)
public class DeleteUserControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private DeleteUserService deleteUserService;

    @Test
    public void removeUserById_whenDeleteMethod() throws Exception {
        User user = new User();
        user.setName(""Test Name"");
        user.setId(89L);

        doNothing().when(deleteUserService).deleteUser(user.getId());

        mvc.perform(delete(""/users/"" + user.getId().toString())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isNoContent());
    }
</code></pre>

<p>I'm getting a <strong><em>java.lang.AssertionError: Status</em></strong> because while the code is expecting to get a <em>204 No content</em> response status, it's receiving a <em>404 Not found</em> which means it's throwing the exception that's supposed to throw when the user doesn't exist.</p>

<p>I think the answer is in the way i need to mock the behavior of my services logic, but i have no idea how. Would appreciate if someone could help me with this one.</p>
",https://stackoverflow.com/questions/62474281/how-do-i-mock-the-behavior-of-a-void-method-when-unit-testing-my-delete-service,"['java', 'spring', 'unit-testing', 'junit', 'mocking']",1005,True,1,1
How to fix this error [Vue warn]: Unknown custom element: &lt;nuxt-link&gt; in unit testing with Jest,"<p>I have a problem running the npm run test. The error is</p>
<pre><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></pre>
<p>SidebarCMS.spect.js</p>
<pre><code>import { shallowMount } from &quot;@vue/test-utils&quot;;
import SidebarCMS from &quot;../layouts/SidebarCMS&quot;;

const factory = () =&gt; {
  return shallowMount(SidebarCMS, {});
};

describe(&quot;SidebarCMS&quot;, () =&gt; {

  test(&quot;renders properly&quot;, () =&gt; {
    const wrapper = factory();
    expect(wrapper.html()).toMatchSnapshot();
  });
});
</code></pre>
<p>Can anyone help me?</p>
",https://stackoverflow.com/questions/64603780/how-to-fix-this-error-vue-warn-unknown-custom-element-nuxt-link-in-unit-te,"['vue.js', 'nuxt.js']",2687,True,5,2
How to reduce code duplication when unit testing an HTTP request with multiple assertions in Angular?,"<p>I'm using Angular's <code>HttpClientTestingModule</code> and <code>HttpTestingController</code> for mocking HTTP requests. The <code>login</code> method of my service <code>AuthenticationService</code> does two things:</p>
<ol>
<li>Makes a <code>POST</code> request to the server. If the credentials are valid, the server returns a <code>User</code> object.</li>
<li>&quot;Logs&quot; in a user by saving the response in <code>localStorage</code>.</li>
</ol>
<p>As a result, I want to have two tests for my <code>login</code> method:</p>
<ol>
<li>Test if the user is returned</li>
<li>Test if localStorage has been set</li>
</ol>
<p>I can include both tests in a single <code>it</code> block, but I don't want to do that. I want to have one assert per unit test.</p>
<p>If I split them into different tests (as shown in the example below), there is a lot of code repetition. Is there a better way to do this?</p>
<p>Here is the relevant section of the <code>authentication.service.spec.ts</code> file.</p>
<pre><code>...

let authenticationService: AuthenticationService;
let httpTestingController: HttpTestingController;
let store = {};

// Create a mock user object for testing purposes
const mockUser: User = {
    name: 'name',
    email: 'email@example.com',
}

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [AuthenticationService],
    });
    authenticationService = TestBed.inject(AuthenticationService);
    httpTestingController = TestBed.inject(HttpTestingController);

    // Create mock localStorage
    spyOn(localStorage, 'getItem').and.callFake(key =&gt; {
      return store[key];
    });
    spyOn(localStorage, 'setItem').and.callFake((key, value) =&gt; {
      return store[key] = value + '';
    });
    spyOn(localStorage, 'removeItem').and.callFake(key =&gt; {
      delete store[key];
    });
});

describe('login', () =&gt; {
    it('should return user', () =&gt; {
      authenticationService.login('name', 'email@example.com').subscribe(
        data =&gt; {
          expect(data).toEqual(mockUser);
        }
      )
      const req = httpTestingController.expectOne('http://example.com/login');
      expect(req.request.method).toEqual('POST');
      req.flush(mockUser);
    });

    it('should set localstorage', () =&gt; {
      authenticationService.login('name', 'email@example.com').subscribe(
        data =&gt; {
          expect(localStorage.getItem('theUser')).toEqual(JSON.stringify(mockUser));
        }
      )
      const req = httpTestingController.expectOne('http://example.com/login');
      expect(req.request.method).toEqual('POST');
      req.flush(mockUser);
    });

    afterEach(() =&gt; {
      httpTestingController.verify();
    });
  });
...
</code></pre>
",https://stackoverflow.com/questions/64360918/how-to-reduce-code-duplication-when-unit-testing-an-http-request-with-multiple-a,"['angular', 'unit-testing', 'jasmine']",175,True,0,1
Jasmine unit testing: How to access property set by @input() ? Accessing it using component.propertyname returns undefined,"<p>ts file:</p>
<pre class=""lang-js prettyprint-override""><code>@input() selectedDep: WebMessagingDeployments[]
</code></pre>
<p>spec file:</p>
<pre class=""lang-js prettyprint-override""><code>beforeEach(() =&gt; {

    fixture = TestBed.createComponent(DeploymentAssignmentFormComponent);
    component = fixture.componentInstance;
    
    console.log(component.selectedDep) // returns undefined
    component.selectedDep.push(mockDepData); //this line throws error. TypeError: Cannot read property '0' of undefined
}));  
</code></pre>
",https://stackoverflow.com/questions/65283861/jasmine-unit-testing-how-to-access-property-set-by-input-accessing-it-usin,"['angular', 'karma-jasmine']",808,True,-1,1
"How to recognize what unit testing framework is used in a project in Visual Studio, .NET?","<p>I am working with a Visual Studio C# project and I need to know what unit testing framework is it using, but there is no one to ask about it.</p>

<p>How could I check it?</p>
",https://stackoverflow.com/questions/59746989/how-to-recognize-what-unit-testing-framework-is-used-in-a-project-in-visual-stud,"['c#', 'visual-studio', 'unit-testing', 'automated-tests', 'visual-studio-2019']",699,True,0,3
How to implement DbContext as an interface? Final goal is to use Moq for Unit testing,"<p>This is my non-working code so far. I have done all research that my understanding allows.
I might be missing something silly. I am new to c# and .Net environment.</p>
<p>Everything is good with the LibraryContext class. The problem is that I can not make use of the interface. When I load it to as services in Startup.cs and then call it in the controllers it gives errors. Updating the question with <code>Startup.cs</code> and <code>BooksController.cs</code> snippets.</p>
<p>First error is in <code>LibraryContext.cs</code>:</p>
<p><code>LibraryContext' does not implement interface member 'ILibraryContext.SaveChangesAsync()' [LibraryApi]. </code></p>
<p>And then in <code>BooksController.cs</code> :</p>
<p><code>'ILibraryContext' does not contain a definition for 'Entry' and no accessible extension method 'Entry' accepting a first argument of type 'ILibraryContext' could be found (are you missing a using directive or an assembly reference?) [LibraryApi]csharp(CS1061) </code></p>
<p>...</p>
<p><code>LibraryContext.cs</code></p>
<pre><code>public interface ILibraryContext : IDisposable
  {
    public DbSet&lt;Reader&gt; Readers { get; set; }
    public DbSet&lt;Book&gt; Books { get; set; }

    Task&lt;int&gt; SaveChangesAsync();
  }


  public class LibraryContext : DbContext, ILibraryContext
  {
    public LibraryContext(DbContextOptions&lt;LibraryContext&gt; options)
          : base(options)
    {
    }

    public virtual DbSet&lt;Reader&gt; Readers { get; set; }
    public virtual DbSet&lt;Book&gt; Books { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity&lt;Book&gt;().ToTable(&quot;Book&quot;);
      modelBuilder.Entity&lt;Reader&gt;().ToTable(&quot;Reader&quot;);
    }
  }
</code></pre>
<p><code>Startup.cs</code></p>
<pre><code>    {
      services.AddScoped&lt;ILibraryContext&gt;(provider =&gt; provider.GetService&lt;LibraryContext&gt;());
    ...
    }
</code></pre>
<p><code>BooksController.cs</code></p>
<pre><code>  {
    private readonly ILibraryContext _context;

    public BooksController(ILibraryContext context)
    {
      _context = context;
    }
...
</code></pre>
",https://stackoverflow.com/questions/65164344/how-to-implement-dbcontext-as-an-interface-final-goal-is-to-use-moq-for-unit-te,"['c#', 'asp.net', 'entity-framework-core']",348,True,0,2
How to write iOS Unit Testing in SwiftUI when switching from background thread to main thread,"<p>Once my background operation completed i need to call handleError function. Since isToast, errorMessage are published variables i need to put in main thread. I wrote a func for test test__Failure() but before simulateRequestFailure complete, this line is executed in function  XCTAssertTrue(self.viewModel.isToast). How to put wait, delay for few seconds</p>

<pre><code>@Published var isToast: Bool = false
@Published var eMessage: String = """"
</code></pre>

<pre><code>func handleError() {
        DispatchQueue.main.async {
            self.isToast = true
            self.eMessage = “Test message”
        }
    }
</code></pre>

<pre><code>func test__Failure() {
         // Some simulate response which call handleError    
         self.simulateRequestFailure()
        XCTAssertTrue(self.vm.isToast)

    }
</code></pre>
",https://stackoverflow.com/questions/61366006/how-to-write-ios-unit-testing-in-swiftui-when-switching-from-background-thread-t,"['ios', 'swift', 'swiftui', 'xctest']",610,True,0,1
What is the correct way to mock HttpClient and return an observable in angular unit testing?,"<p>I have been working on this for an embarrassingly long period of time. I am trying to write a unit test for an angular app that mocks out HttpClient and returns an observable for the code being tested.</p>
<p>My test looks like this</p>
<pre><code>  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [ ProjectComponent ],
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [
        HttpClient
      ]
    })
    .compileComponents();
  });

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

    var service = TestBed.get(HttpClient);

    var obs = Observable.create( observer =&gt; {
      observer.next({'hi':'hi'});
      observer.complete();
    });
    spyOn(service, 'get').and.returnValue(obs);
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
</code></pre>
<p>My code to test looks like this.</p>
<pre><code>  ngOnInit(): void {
    console.log('starting');
    const x = this.http.get('http://localhost:8080/project')
      x.subscribe((response: any) =&gt; {
        console.log('$$$$$$');
        console.log(response);
        this.projects = response;
      }, e =&gt; {
        console.log(e);
      });
  }
</code></pre>
<p>As you can see I want the observable to be returned by the get method as a mocked response. If i debug the variable x in the ngOninit method I see that the observable comes in there. But the subscribe function is never called. What is the matter with this? How can I get the subscribe function to be called? Am I creating/mocking the observable in the wrong way? ... Thanks in advance.</p>
",https://stackoverflow.com/questions/64964871/what-is-the-correct-way-to-mock-httpclient-and-return-an-observable-in-angular-u,"['angular', 'rxjs']",1598,False,-1,1
Is there a way where we can test Postgres Jsonb queries using embedded database for Unit Testing?,"<p>I want to unit test In Java Spring-boot Postgres native query for jsonb datatype without hitting the actual DB.Instead using some embedded database or other approach ,but embedded databases like H2 doesn't support Postgres jsonb specific operators like <code>-&gt;&gt;</code>, <code>#&gt;&gt;</code>  etc.</p>

<p>Is there a way that I can to this? Please also suggest any other approach for the same.</p>

<p>Query Example:</p>

<pre><code>@Query(value = ""SELECT * FROM table WHERE column -&gt;&gt; 'Id'=?1"", nativeQuery = true)
public Entity fertchById(String id);
</code></pre>
",https://stackoverflow.com/questions/59926910/is-there-a-way-where-we-can-test-postgres-jsonb-queries-using-embedded-database,"['java', 'postgresql', 'spring-boot', 'jsonb', 'embedded-database']",2246,True,4,1
"vue-composition-api unit testing with typescript, how to get internal setup function and data inside wrapper?","<p>Currently, I try to get the attributes inside my vue component while using vue-test-utils
I have included the <code>VueCompositionAPI</code></p>

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

<p><strong>test.vue</strong></p>

<pre><code>&lt;template&gt;
  &lt;div/&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import { defineComponent, reactive, onMounted, toRefs } from '@vue/composition-api'

export default defineComponent({
  props: {
    name: String
  },
  setup (props) {
    const state = reactive({
      testVar: 'test'
    })

    function inter () {
        console.log(""run"")
    }

    onMounted(() =&gt; {
      setInterval(() =&gt; { inter() }, 4000)
    })

    return { ...toRefs(state) }
  }
})
&lt;/script&gt;
</code></pre>

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

<pre><code>import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)

import { shallowMount } from '@vue/test-utils'
import Test from '@/components/Test.vue'

describe('has member', () =&gt; {
   const wrapper = shallowMount(VideoPlayer, {
      propsData
   })

   //i want to access value in using wrapper.vm.testVar but typescript return error

});
</code></pre>

<ol>
<li>I could set wrapper type as any to get wrapper.vm.testVar but I don't think it is a good idea</li>
<li>and as for the <code>function inter</code>, I don't know how to retrieve it. Would like to setup mock jest function to check the interval</li>
</ol>
",https://stackoverflow.com/questions/61812155/vue-composition-api-unit-testing-with-typescript-how-to-get-internal-setup-func,"['typescript', 'vuejs2', 'jestjs', 'vue-test-utils', 'vue-composition-api']",1182,False,3,0
How to wait for an async call to finish in component&#39;s mount callback before unit testing it?,"<p>I'm using Jest to unit test a component that makes an Axios call in it's <code>mounted()</code> method. I'm mocking the Axios call so it returns a promise so the API call is not actually made. But the problem seems to be that because Axios is asynchronous, how do I tell my test to wait for the Axios call (even the fake one) to complete before running my expectations?</p>
<p>This does not work:</p>
<pre><code>it('calls auth api', () =&gt; {
    spyOn(axios, 'get').and.callFake(() =&gt; Promise.resolve().then(() =&gt; authResponse));
    wrapper = shallowMount(App, {
        localVue,
    });
    expect(axios.get).toHaveBeenCalledWith('api/auth');
    // The &quot;status&quot; data is set in the axios callback. But this fails.
    expect(wrapper.vm.status).toBe('AUTHORIZED');
});
</code></pre>
<p>If I wrap it in a timeout, it does work. I think I've read this is because the timeouts are always called after promises are resolved or something?</p>
<pre><code>it('calls auth api', () =&gt; {
    spyOn(axios, 'get').and.callFake(() =&gt; Promise.resolve().then(() =&gt; authResponse));
    wrapper = shallowMount(App, {
        localVue,
    });
    expect(axios.get).toHaveBeenCalledWith('api/auth');
    setTimeout(() =&gt; {
        expect(wrapper.vm.status).toBe('AUTHORIZED');
    }, 0);
});
</code></pre>
<p>Is there a better way to do this?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/63994825/how-to-wait-for-an-async-call-to-finish-in-components-mount-callback-before-uni,"['javascript', 'vue.js', 'vuejs2', 'jestjs', 'axios']",1659,True,2,1
Blazor Server Page Unit Testing - How to mock secondary signalR client connection used in Blazor Server Page,"<p>I am a new user to bUnit and have managed to get some tests running for <code>NavMenu</code> to grasp the basic concepts.
However, a different Blazor page makes a request to a secondary signalR hub for communication of workflow state.</p>
<p>How to mock signalR connection?
<a href=""https://github.com/dotnet/aspnetcore/issues/14924"" rel=""nofollow noreferrer"">https://github.com/dotnet/aspnetcore/issues/14924</a></p>
<p><strong>Server Page that uses an additional signalR connection to communicate workflow state</strong></p>
<pre><code> protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                var hubUrl = NavigationManager.BaseUri.TrimEnd('/') + &quot;/motionhub&quot;;

                try
                {
                    Logger.LogInformation(&quot;Index.razor page is performing initial render, connecting to secondary signalR hub&quot;);

                    hubConnection = new HubConnectionBuilder()
                        .WithUrl(hubUrl)
                        .ConfigureLogging(logging =&gt;
                        {
                            logging.AddConsole();
                            logging.AddFilter(&quot;Microsoft.AspNetCore.SignalR&quot;, LogLevel.Information);
                        })
                        .AddJsonProtocol(options =&gt;
                        {
                            options.PayloadSerializerOptions = JsonConvertersFactory.CreateDefaultJsonConverters(LoggerMotionDetection, LoggerMotionInfo, LoggerJsonVisitor);
                        })
                        .Build();

                    hubConnection.On&lt;MotionDetection&gt;(&quot;ReceiveMotionDetection&quot;, ReceiveMessage);
                    hubConnection.Closed += CloseHandler;

                    Logger.LogInformation(&quot;Starting HubConnection&quot;);
                    await hubConnection.StartAsync();
                    Logger.LogInformation(&quot;Index Razor Page initialised, listening on signalR hub =&gt; &quot; + hubUrl.ToString());
                }
                catch (Exception e)
                {
                    Logger.LogError(e, &quot;Encountered exception =&gt; &quot; + e);
                }
            }
        }
</code></pre>
<p><strong>Stub Unit Test Class</strong></p>
<pre><code> public class IndexTest : TestContext, IDisposable
    {
        private MotionDetectionRepository repo;

        public IndexTest()
        {
            var mock = new Mock&lt;IMotionDetectionSerializer&lt;MotionDetection&gt;&gt;();
            repo = new MotionDetectionRepository(mock.Object, new NullLogger&lt;MotionDetectionRepository&gt;());

            Services.AddScoped&lt;ILogger&lt;MotionDetectionRepository&gt;, NullLogger&lt;MotionDetectionRepository&gt;&gt;();
            Services.AddScoped&lt;ILogger&lt;MotionInfoConverter&gt;, NullLogger&lt;MotionInfoConverter&gt;&gt;();
            Services.AddScoped&lt;ILogger&lt;MotionDetectionConverter&gt;, NullLogger&lt;MotionDetectionConverter&gt;&gt;();
            Services.AddScoped&lt;ILogger&lt;JsonVisitor&gt;, NullLogger&lt;JsonVisitor&gt;&gt;();
            Services.AddScoped&lt;ILogger&lt;WebApp.Pages.Index&gt;, NullLogger&lt;WebApp.Pages.Index&gt;&gt;();
            Services.AddScoped&lt;IMotionDetectionRepository&gt;(sp =&gt; repo);
            Services.AddScoped&lt;MockNavigationManager&gt;();
            Services.AddSignalR();
        }

        [Fact]
        public void Test()
        {
            var cut = RenderComponent&lt;WebApp.Pages.Index&gt;();

            Console.WriteLine($&quot;{cut.Markup}&quot;);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/64986959/blazor-server-page-unit-testing-how-to-mock-secondary-signalr-client-connectio,"['asp.net-core', 'blazor', 'blazor-server-side', 'asp.net-blazor', 'bunit']",786,True,2,1
Error trying to generate a random key pair when unit testing on a real device iOS Swift,"<p>When i try to run my unit test on a real device it fails.</p>
<p>The returned error is</p>
<blockquote>
<p>-25293 (&quot;The user name or passphrase you entered is not correct.&quot;).</p>
</blockquote>
<p>Here is my failing code:</p>
<pre><code>let accessControl = SecAccessControlCreateWithFlags(
  kCFAllocatorDefault,
  kSecAttrAccessibleAfterFirstUnlock,
  [.privateKeyUsage],
  nil)

let privateKeyAttrs = [
  kSecAttrIsPermanent as String    : true,
  kSecAttrApplicationTag as String : tag,
  kSecAttrAccessControl as String  : accessControl
  ] as [String : Any]

let generationQuery: [String: Any] = [
  kSecAttrKeyType as String       : kSecAttrKeyTypeRSA,
  kSecAttrKeySizeInBits as String : 2048,
  kSecPrivateKeyAttrs as String   : privateKeyAttrs]

var error: Unmanaged&lt;CFError&gt;?
    guard let privateKey = SecKeyCreateRandomKey(generationQuery as CFDictionary, &amp;error) else {
        throw &lt;MyError&gt;
    }
</code></pre>
<p>The SecKeyCreateRandomKey fails even if I change my Accessible protection to kSecAttrAccessibleAlways or kSecAttrAccessibleWhenUnlocked and my test pass if I just remove kSecAttrAccessControl from my privateKeyAttrs.</p>
<blockquote>
<p>More details: If I run my tests on a simulator it pass; I'm using
Xcode 11.6 and swift 5.</p>
</blockquote>
",https://stackoverflow.com/questions/63396595/error-trying-to-generate-a-random-key-pair-when-unit-testing-on-a-real-device-io,"['swift', 'xcode', 'unit-testing', 'keychain']",441,True,2,1
Python Unit Testing - &#39;gcsfs.utils.HttpError: Anonymous caller does not have storage.objects.list access to the Google Cloud Storage bucket.&#39;,"<p>I'm running a Python unit test on this script <code>api.py</code></p>
<pre><code>def download_models(gcs_model_path, local_path):
    filesystem = gcsfs.GCSFileSystem(project=PROJECT)  # , token='creds.json')
    # download models from gcs
    filesystem.get(gcs_model_path, local_path, recursive=True)
</code></pre>
<p>Here is the unit test script <code>embedding_api_test.py</code></p>
<pre><code>class EmbeddingAPITest(unittest.TestCase):

    @mock.patch('gcsfs.GCSFileSystem')
    def test_download_models(self, mock_filesystem):
        mock_filesystem.return_value.get.return_value = []
        download_models('gcs_model_path', 'local_path')
</code></pre>
<p>I'm getting this error on my terminal:</p>
<pre><code>_______________________ ERROR collecting qa_api/tests/qa_api_test.py ________________________
qa_api/tests/qa_api_test.py:3: in &lt;module&gt;
    from qa_api.api import app
qa_api/api.py:37: in &lt;module&gt;
    download_models(GCS_MODEL_PATH, LOCAL_MODEL_PATH)
qa_api/api.py:21: in download_models
    filesystem.get(gcs_model_path, local_path, recursive=True)
/opt/anaconda3/lib/python3.7/site-packages/fsspec/spec.py:556: in get
    rpaths = self.find(rpath)
/opt/anaconda3/lib/python3.7/site-packages/fsspec/spec.py:371: in find
    for path, dirs, files in self.walk(path, maxdepth, **kwargs):
/opt/anaconda3/lib/python3.7/site-packages/fsspec/spec.py:326: in walk
    listing = self.ls(path, detail=True, **kwargs)
/opt/anaconda3/lib/python3.7/site-packages/gcsfs/core.py:767: in ls
    out = self._list_objects(path)
/opt/anaconda3/lib/python3.7/site-packages/gcsfs/core.py:571: in _list_objects
    items, prefixes = self._do_list_objects(path)
/opt/anaconda3/lib/python3.7/site-packages/gcsfs/core.py:604: in _do_list_objects
    maxResults=max_results,
/opt/anaconda3/lib/python3.7/site-packages/gcsfs/core.py:504: in _call
    raise e
/opt/anaconda3/lib/python3.7/site-packages/gcsfs/core.py:487: in _call
    validate_response(r, path)
/opt/anaconda3/lib/python3.7/site-packages/gcsfs/core.py:130: in validate_response
    raise HttpError(error)
E   gcsfs.utils.HttpError: Anonymous caller does not have storage.objects.list access to the Google Cloud Storage bucket.
</code></pre>
<p>It seems I'm mocking it incorrectly but I don't understand why. Would really appreciate any help. Please let me know if more details are required. Thanks!</p>
",https://stackoverflow.com/questions/64673419/python-unit-testing-gcsfs-utils-httperror-anonymous-caller-does-not-have-sto,"['python', 'python-3.x', 'unit-testing', 'google-cloud-storage', 'python-unittest']",732,True,2,1
How do you know if loop or double loop is used in a function when unit testing?,"<p>I am new to unit testing, and would like to check if any line of code to contain double loop specifically.</p>
<p>I am currently studying at bootcamp and they somehow check if my solution contains specific loop (like while loop) or if I used nested loop as below.</p>
<pre><code>Test Code
function () {
    expect(DOUBLE_LOOP_EXP.test(funcBody)).to.be.equal(true);
  } 
</code></pre>
<p>To clarify, below is my function that's been tested through above criterion;</p>
<pre><code>function makePermutations(str) {
  let result = '';
  for (let i = 0; i &lt; str.length; i++) {
    for (let j = 0; j &lt; str.length; j++) {
      result += str[i] + str[j] + ',';
    }
  }
  return result.slice(0, result.length - 1);
}
module.exports = makePermutations;

</code></pre>
<p>Unfortunately, there's no way to know whats inside that DOUBLE_LOOP_EXP.test.
Please advise.</p>
",https://stackoverflow.com/questions/63866289/how-do-you-know-if-loop-or-double-loop-is-used-in-a-function-when-unit-testing,"['javascript', 'unit-testing', 'testing', 'jestjs']",108,True,1,1
"Unit testing: verifying a method was called, with an object created inside the tested method as parameter","<p><strong>Description of the problem</strong></p>
<p>A method to be tested creates objects of some type, let's call it <code>Item</code>. It initialises these objects' properties with data passed into it.</p>
<p>This method calls another method, which takes an <code>Item</code> as a parameter. How can it be made sure that this call is made correctly? That is, the following would need to be verified:</p>
<ol>
<li>The object being passed into the method is of the correct type.</li>
<li>The object being passed into the method has correct property values.</li>
<li>The other method is being called the correct number of times.</li>
</ol>
<p>Assume we are using NUnit and FakeItEasy.</p>
<p><strong>Code</strong></p>
<pre><code>public class Controller
{
    IService service {get; set;}

    // dependency injection, can use fakes
    public Controller(IService service) {
        this.service = service;
    }

    public void methodToTest(string itemName, string itemDescription, int quantity)
    {
        Item newItem = new Item
        {
            name = name,
            description = description
        }

        for (int i = 1; i &lt;= quantity; i++)
        {
            // need to verify that doSomething() is called with a parameter of type Item
            // and that it is called quantity times
            // and that newItem has correct parameters
            service.doSomething(newItem);
        }
    }
}

</code></pre>
",https://stackoverflow.com/questions/63087347/unit-testing-verifying-a-method-was-called-with-an-object-created-inside-the-t,"['c#', '.net', 'unit-testing', 'fakeiteasy']",1882,True,1,1
"In order to test a function with unit testing, does it need to have a return value?","<p>I am new to python and am trying to learn about unit testing. I am using pytest to run some unit tests on my code. Something very similar to this example:</p>

<pre><code>def test_calc_total():
    total = mathlib.calc_total(4,5)
    assert total == 9
</code></pre>

<p>I may be incorrect here, but I am learning that in order for your function be testable, it will have to return a value. Is this true for all unit tests?</p>

<p>I am finding that the majority of my functions are not able to be tested, since they don't have a return value. I am creating a ticket tracking system and storing the ticket information in a dataframe. Here is a portion of <em>TicketDF</em> class:</p>

<pre><code>class TicketDF():
    cwd = os.getcwd()
    df = pd.DataFrame()

    def __init__(self, configParser):
        self.populateFilePaths(configParser)
        self.populateAttributes(configParser)
        self.populateTable()

    def populateTable(self):
        if self.doesFileExistAndNotEmpty(self.ticketCSVFilePath):
            self.df = pd.read_csv(self.ticketCSVFilePath, converters={'Comments':literal_eval}) #, 'Attachments':literal_eval})
            self.df.set_index('Ticket ID', inplace=True)

    def populateAttributes(self, configParser):
        self.ticketAttributes =  configParser.getTicketAttributes()

    def populateFilePaths(self, configParser):
        self.ticketCSVFilePath = configParser.getTicketsCSVPath()

    def doesFileExistAndNotEmpty(self, filepath):
        if os.path.exists(filepath) and os.path.getsize(filepath) &gt; 0:
            return True
        else:
            return False

    def getTicketDF(self):
        return self.df

    def addTicketToDF(self, data):
        df = pd.DataFrame (data, columns = self.ticketAttributes)
        df.set_index('Ticket ID', inplace=True)
        self.df = self.df.append(df)
        self.saveDFToCSV()
</code></pre>

<p>As you can see, the majority of the functions, even the ones not shown, do not have return values. Is it best practice to write code so that all functions have a return value? Or is there another way to test functions without a return value?</p>
",https://stackoverflow.com/questions/62201897/in-order-to-test-a-function-with-unit-testing-does-it-need-to-have-a-return-val,"['python', 'unit-testing', 'pytest']",1094,True,1,2
How do you testrun your c++/Qt programs/projects with template classes? (Automated unit testing in 2020),"<p>I was confronted with a Think-Cell development position test in which a big part - if not the most important part - was testing the final version of the program one has written that contained a template class. So lots of testing is possible.</p>

<p>In my experience from open source projects the bare minimum is tested to make the program run&amp;done and solve bugs by ""creative users"" that do stuff programmers wouldn't ever come up with. </p>

<p>In the books I red and I learned from was just some minimal input IO handling for int/char/strings but nothing explicitly about testing the program with all/the most possible use cases.</p>

<p>But I really like the idea of writing a test program that covers all events/possible use cases especially a commercial use case and I can Imagine writing one general testing library that fires all kinds of data on the program that covers as much as possible would be handy wouldn't it?</p>

<p>And yes, I already googled and found some <a href=""https://stackoverflow.com/search?q=Unit%20testing%20c%2B%2B"">unit testing posts from '08 '10</a> also <a href=""https://stackoverflow.com/questions/1524390/what-unit-testing-framework-should-i-use-for-qt"">qt unit testing</a>
or <a href=""http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle"" rel=""nofollow noreferrer"">'04</a> and after that <a href=""https://www.youtube.com/watch?v=16FI1-d2P4E"" rel=""nofollow noreferrer"">google test</a> seem to dominate the market but even there one has to come up with all the different test cases that really takes time f.e in case of template classes.
Also the Qt toolkit already has a <a href=""https://doc.qt.io/qt-5/qttestlib-tutorial1-example.html"" rel=""nofollow noreferrer"">Qt unit testing library</a></p>

<p><strong><em>So my question is: How do you / What do you use or do to test your projects/programs in 2020? Do I have to write/come up with my own testing methods/classes redundant for every program/project every time new?
Isn't there already a way to automate the testing in a way errors/warnings are showing up f.e. in the qt creator during the programming process?</em></strong></p>
",https://stackoverflow.com/questions/62157664/how-do-you-testrun-your-c-qt-programs-projects-with-template-classes-automat,"['c++', 'qt', 'unit-testing']",56,False,0,0
Unit Testing custom eager validation on top of lazy validation from IOptions .NET Core 1.1 and up,"<p>This is not a question but a case study that was tried on by me where questions have not been asked. In case anyone else tries this kind of idiotic unit testing in the future, these are my findings:</p>

<p>While trying to implement eager validation, as it is not supported currently by .NET Core 3.1, but as the documentation states at the bottom of the section <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1#options-post-configuration"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1#options-post-configuration</a>:</p>

<blockquote>
  <p>Eager validation (fail fast at startup) is under consideration for a future release.</p>
</blockquote>

<p>You cannot test programmatically the lazy validation from accessing the option in question if you've implemented custom eager validation.</p>

<p>This is what I did:</p>

<p>Created config class</p>

<pre><code>public class TestOptions : IValidateObject // for eager validation config
{
    [Required]
    public string Prop { get; set; }

    public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrEmpty(this.Prop))
            yield return new ValidationResult($""{nameof(this.Prop)} is null or empty."");
    }
}
</code></pre>

<p>Added the configuration in my lib that I'm testing:</p>

<pre><code>public static void AddConfigWithValidation(this IServiceCollection services, Action&lt;TestOptions&gt; options)
{
    var opt = new TestOptions();
    options(opt);

    // eager validation
    var validationErrors = opt.Validate(new ValidationContext(opt)).ToList();

    if (validationErrors.Any())
        throw new ApplicationException($""Found {validationErrors.Count} configuration error(s): {string.Join(',', validationErrors)}"");

    // lazy validation with validate data annotations from IOptions
    services.AddOptions&lt;TestOptions&gt;()
        .Configure(o =&gt;
        {
            o.Prop = opt.Prop
        })
        .ValidateDataAnnotations();
}
</code></pre>

<p>And the test looks like this</p>

<pre><code>public class MethodTesting
{
    private readonly IServiceCollection _serviceCollection;

    public MethodTesting()
    {
        _serviceCollection = new ServiceCollection();
    }

    // this works as it should
    [Fact] 
    public void ServiceCollection_Eager_Validation()
    {
        var opt = new TestOptions { Prop = string.Empty };
        Assert.Throws&lt;ApplicationException&gt;(() =&gt; _serviceCollection.AddConfigWithValidation(o =&gt;
        {
            o.Prop = opt.Prop
        });
    }

    // this does not work
    [Fact]
    public void ServiceCollection_Lazy_Validation_Mock_Api_Start()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(""settings.json"", optional: false, reloadOnChange: true);

        _configuration = builder.Build();

        var opt = _configuration.GetSection(nameof(TestOptions)).Get&lt;TestOptions&gt;();

        _serviceCollection.AddConfigWithValidation(o =&gt;
        {
            o.Prop = opt.Prop
        });

        // try to mock a disposable object, sort of how the API works on subsequent calls
        using (var sb = _serviceCollection.BuildServiceProvider())
        {
            var firstValue = sb.GetRequiredService&lt;IOptionsSnapshot&lt;TestOptions&gt;&gt;().Value;
            firstValue.Should().BeEquivalentTo(opt);
        }

        // edit the json file programmatically, trying to trigger a new IOptionsSnapshot&lt;&gt;
        var path = $""{Directory.GetCurrentDirectory()}\\settings.json"";

        var jsonString = File.ReadAllText(path);

        var concreteObject = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;TestObject&gt;(jsonString);

        concreteObject.TestObject.Prop = string.Empty;

        File.WriteAllText(path, Newtonsoft.Json.JsonConvert.SerializeObject(concreteObject));

        using (var sb = _serviceCollection.BuildServiceProvider())
        {
            // this does not work, as the snapshot is still identical to the first time it is pulled
            Assert.Throws&lt;OptionsValidationException&gt;(() =&gt; _serviceCollection.BuildServiceProvider().GetRequiredService&lt;IOptionsSnapshot&lt;TestOptions&gt;&gt;().Value);
        }
    }

    // this does not work as well
    [Fact]
    public void ServiceCollection_Lazy_Validation_Mock_Api_Start_With_Direct_Prop_Assignation()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(""settings.json"", optional: false, reloadOnChange: true);

        _configuration = builder.Build();

        var opt = _configuration.GetSection(nameof(TestOptions)).Get&lt;TestOptions&gt;();

        _serviceCollection.AddConfigWithValidation(o =&gt;
        {
            o.Prop = opt.Prop
        });

        using (var sb = _serviceCollection.BuildServiceProvider())
        {
            var firstValue = sb.GetRequiredService&lt;IOptionsSnapshot&lt;TestOptions&gt;&gt;().Value;
            firstValue.Should().BeEquivalentTo(opt);
        }

        var prop = _configuration[""TestOptions:Prop""];

        _configuration[""TestOptions:Prop""] = string.Empty;

        // this returns a new value
        var otherProp = _configuration[""TestOptions:Prop""];

        using (var sb = _serviceCollection.BuildServiceProvider())
        {
            // this does not work, the snapshot is not yet modified, however, calling _configuration.GetSection(nameof(TestOptions)).Get&lt;TestOptions&gt;(); does return the new TestOptions.

            Assert.Throws&lt;OptionsValidationException&gt;(() =&gt; _serviceCollection.BuildServiceProvider().GetRequiredService&lt;IOptionsSnapshot&lt;TestOptions&gt;&gt;().Value);
        }

    }

    public class TestObject
    {
        public TestOptions TestOptions { get; set; }
    }
</code></pre>

<p>My settings.json looked like:</p>

<pre><code>{
    ""TestOptions"": {
        ""Prop"": ""something""
    }
}
</code></pre>

<p>A solution to get this up and running as a test, is to add an optional parameter or an overloaded method with an optional parameter that enforces or not eager validation and test that the lazy validation works properly when the eager is deactivated.</p>

<p>Please note that this is not perfect, but a method of test for people who want to test how the eager and lazy validation can be tested when the options provided are from a source that gets updated but the apps do not get restarted.</p>

<p>If you have suggestions, questions or want to discuss on the subject at hand, feel free to use the comment section</p>
",https://stackoverflow.com/questions/59861878/unit-testing-custom-eager-validation-on-top-of-lazy-validation-from-ioptions-ne,"['c#', '.net-core', 'xunit', 'asp.net-core-1.1', 'asp.net-core-3.1']",639,True,0,2
Fongo - Fake Mongo : Not able to load dataset from location for unit testing of mongrepository using fongo,"<p>I am using fongo as in memory database for testing my mongodbrepository.</p>
<p>I have taken reference from <a href=""http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html"" rel=""nofollow noreferrer"">http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html</a> for unit testing.</p>
<p>To populate sample data, I have added required json file under test/resources/json-data/user/user.json but it's not loaded into fongo.</p>
<pre><code>@Test
@UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT, locations = &quot;/json-data/user/user.json&quot;) // test/resources/..
    public void findUser_should_return_user() {
        User user = userRepository.findByXYZId(&quot;XX12345&quot;);
        assertNotNull(user);
    }
</code></pre>
<p>What's  missing ? What needs to change to load dataset from json to fongo(fake mongo)</p>
<p>[Edit-1] Need to try 2 things #1 Include missing rule &amp; #2 json format</p>
<p>looks like json format need to include collection name -
Reference-1 : <a href=""https://github.com/lordofthejars/nosql-unit#dataset-format"" rel=""nofollow noreferrer"">https://github.com/lordofthejars/nosql-unit#dataset-format</a></p>
<p>Reference 2 -https://github.com/lordofthejars/nosql-unit/tree/master/nosqlunit-demo/src/test/resources/com/lordofthejars/nosqlunit/demo/mongodb</p>
",https://stackoverflow.com/questions/63289949/fongo-fake-mongo-not-able-to-load-dataset-from-location-for-unit-testing-of,"['java', 'mongodb', 'junit', 'fongo']",250,True,0,2
AssertionError on comparing different types of an object when unit testing my list user by id service,"<p>I'm trying to test a service in my API that when given a certain id, it should return user that corresponds to that id. Pretty straightforward, but i'm getting the following error that should be simple to fix but have no idea how :</p>

<pre><code>java.lang.AssertionError: 
Expecting:
 &lt;User(id=89, name=null, email=null)&gt;
and actual:
 &lt;Optional[User(id=89, name=null, email=null)]&gt;
to refer to the same object
</code></pre>

<p>My test code is :</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ServiceDetailUserTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserDetailService userDetailService;

    @Test
    public void when_given_id_it_should_return_user() {
        User user = new User();
        user.setId(89L);

        when(userRepository.findById(user.getId())).thenReturn(Optional.of(user));

        Optional&lt;User&gt; expected = userDetailService.listUser(user.getId());

        assertThat(expected).isSameAs(user);
    }
}
</code></pre>

<p>And my service code (not even sure if needed) is :</p>

<pre><code>@Service
public class UserDetailService {

    @Autowired
    UserRepository repository;

    public Optional&lt;User&gt; listUser(Long id) {
        return repository.findById(id);
    }
}
</code></pre>

<p>So, to compare my <code>expected</code> with my <code>user</code>, i need them to be the exact same type...but how?
I've seen variations of this test, with one using the expression <code>assertThat(expected).isNotNull();</code> instead of <code>assertThat(expected).isSameAs(user);</code>, but i'm not sure if that's correct.</p>
",https://stackoverflow.com/questions/61963721/assertionerror-on-comparing-different-types-of-an-object-when-unit-testing-my-li,"['java', 'spring', 'api', 'unit-testing', 'repository']",515,True,0,2
Firebase - cloud firestore - unit testing fails with error - TypeError: The &quot;path&quot; argument must be of type string,"<p>Firebase - cloud firestore - unit testing fails with error 
- TypeError: The ""path"" argument must be of type string.</p>

<p>Otherwise, it works fine when run with NodeJS command 'node index.js'
I use service account and NodeJS</p>

<p><strong>myservice.js</strong></p>

<pre><code>
var admin = require(""firebase-admin"");

var serviceAccount = require(""./sakey.json"");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: ""https://myapp.firebaseio.com""
});

const db = admin.firestore();


const getData = async () =&gt; {
    const snapshot = await db.collection('users').get()
    return snapshot.docs.map(doc =&gt; doc.data())
}

module.exports = { getData }

</code></pre>

<p><strong>Test Case</strong></p>

<pre><code>const { getData } = require('./myservice')

describe('my test suite', () =&gt; {

    it('Retrieve data', async () =&gt; {
        let result = await getData();
        return result().then(data =&gt; expect(data).toBeDefined())
    }
}

</code></pre>

<p><strong>Error</strong></p>

<pre><code>TypeError: The ""path"" argument must be of type string. Received type objectTypeError [ERR_INVALID_ARG_TYPE]: The ""path"" argument must be of type string. Received type object

      at GrpcClient.loadProto (node_modules/google-gax/src/grpc.ts:166:23)
      at new FirestoreClient (node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js:113:38)
      at ClientPool.clientFactory (node_modules/@google-cloud/firestore/build/src/index.js:329:26)
      at ClientPool.acquire (node_modules/@google-cloud/firestore/build/src/pool.js:87:35)
      at ClientPool.run (node_modules/@google-cloud/firestore/build/src/pool.js:164:29)
      at node_modules/@google-cloud/firestore/build/src/index.js:957:30
      at Firestore._retry (node_modules/@google-cloud/firestore/build/src/index.js:822:38)
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>...
  ""dependencies"": {
    ""dotenv"": ""^8.2.0"",
    ""firebase-admin"": ""^8.10.0"",
    ""moment"": ""^2.24.0""
  },
  ""devDependencies"": {
    ""@types/jest"": ""^25.1.4"",
    ""jest"": ""^25.1.0""
  }
...
</code></pre>
",https://stackoverflow.com/questions/60802569/firebase-cloud-firestore-unit-testing-fails-with-error-typeerror-the-pat,"['node.js', 'firebase', 'google-cloud-firestore', 'jestjs']",319,True,0,1
"Performing non-mock, state-based unit testing of non-trivial functions and their dependencies that follow CQS","<p>I realize that this question may seem to be a duplicate of questions such as <a href=""https://stackoverflow.com/questions/37725504/how-to-unit-test-this-function-without-mock-asserts"">this</a>, <a href=""https://stackoverflow.com/questions/8666495/is-there-any-advantage-to-writing-both-classist-and-mockist-unit-tests-for-a-sin"">this</a>, <a href=""https://stackoverflow.com/questions/47749/are-mocks-better-than-stubs"">this</a>, <a href=""https://stackoverflow.com/questions/35133263/mockito-and-interface-event/35134356#35134356"">this</a>, and <a href=""https://softwareengineering.stackexchange.com/questions/382087/how-exactly-should-unit-tests-be-written-without-mocking-extensively"">this</a>. I'm specifically asking, however, how you would write unit tests using the Detroit style toward non-trivial code with multiple code paths. Other questions, articles, and explantations all discuss trivial examples such as a <code>Calculator</code> class. Further, I'm practicing CQS, or Command Query Separation, which alters the methods by which I write tests.</p>

<p>As per Martin Fowler's article ""<a href=""https://martinfowler.com/articles/mocksArentStubs.html"" rel=""nofollow noreferrer"">Mocks Aren't Stubs</a>"", I understand that there are two schools of thought toward TDD - Classical (Detroit) and Mockist (London). </p>

<p>When I first learned Unit Testing and TDD in general, I was taught the London style, utilizing Mocking Frameworks like Java's Mockito. I had no idea of the existence of Classical TDD.</p>

<p>The overutilization of Mocks in the London style concerns me in that tests are very much tied to implementation, making them brittle. Considering a lot of tests I've written have been behavioral in nature utilizing mocks, I'd like to learn and understand how you'd write tests using the Classical style.</p>

<p>To this effect, I have a few questions. For Classical testing,</p>

<ol>
<li>Should you use the real implementation of a given dependency or a fake class?</li>
<li>Do Detroit practitioners have a different definition of what a ""unit"" is than Mockists do?</li>
</ol>

<p>To further elaborate, here is a non-trivial real-world code example for signing up a user in a REST API.</p>

<pre><code>public async signUpUser(userDTO: CreateUserDTO): Promise&lt;void&gt; {
    const validationResult = this.dataValidator.validate(UserValidators.createUser, userDTO);

    if (validationResult.isLeft()) 
        return Promise.reject(CommonErrors.ValidationError.create('User', validationResult.value)); 

    const [usernameTaken, emailTaken] = await Promise.all([
        this.userRepository.existsByUsername(userDTO.username),
        this.userRepository.existsByEmail(userDTO.email)
    ]) as [boolean, boolean];

    if (usernameTaken)
        return Promise.reject(CreateUserErrors.UsernameTakenError.create());

    if (emailTaken)
        return Promise.reject(CreateUserErrors.EmailTakenError.create());

    const hash = await this.authService.hashPassword(userDTO.password);

    const user: User = { id: 'create-an-id', ...userDTO, password: hash };

    await this.userRepository.addUser(user);

    this.emitter.emit('user-signed-up', user);
}
</code></pre>

<p>With my knowledge of the mocking approach, I'd generally mock every single dependency here, have mocks respond with certain results for given arguments, and then assert that the repository <code>addUser</code> method was called with the correct user.</p>

<p>Using the Classical approach to testing, I'd have a <code>FakeUserRepository</code> that operates on an in-memory collection and make assertions about the state of the Repository. The problem is, I'm not sure how <code>dataValidator</code> and <code>authService</code> fits in. Should they be real implementations that actually validate data and actually hash passwords? Or, should they be fakes too that honor their respective interfaces and return pre-programmed responses to certain inputs?</p>

<p>In other Service methods, there is an exception handler that throws certain exceptions based on exceptions thrown from the <code>authService</code>. How do you do state-based testing in that case? Do you need to build a Fake that honors the interface and that throws exceptions based on certain inputs? If so, aren't we basically back to creating mocks now?</p>

<p>To give you another example of the kind of function I'd be unsure how to build a fake for, see this JWT Token decoding method which is a part of my <code>AuthenticationService</code>:</p>

<pre><code>public verifyAndDecodeAuthToken(
    candidateToken: string, 
    opts?: ITokenDecodingOptions
): Either&lt;AuthorizationErrors.AuthorizationError, ITokenPayload&gt; {
    try {
        return right(
            this.tokenHandler.verifyAndDecodeToken(candidateToken, 'my-secret', opts) as ITokenPayload
        );
    } catch (e) {
        switch (true) {
            case e instanceof TokenErrors.CouldNotDecodeTokenError:
                throw ApplicationErrors.UnexpectedError.create();
            case e instanceof TokenErrors.TokenExpiredError:
                return left(AuthorizationErrors.AuthorizationError.create());
            default:
                throw ApplicationErrors.UnexpectedError.create();
        }
    }
}
</code></pre>

<p>Here, you can see that the function can throw different errors which will have different meanings to the API caller. If I was building a fake here, the only thing I can think to do is have the fake respond with certain errors to hard-coded inputs, but again, this just feels like re-building the mocking framework now.</p>

<p>So, basically, at the end of the day, I'm unsure how you write unit tests without mocks using the Classical state-based assertion approach, and I'd appreciate any advice on how to do so for my code example above. Thanks.</p>
",https://stackoverflow.com/questions/60139201/performing-non-mock-state-based-unit-testing-of-non-trivial-functions-and-their,"['unit-testing', 'testing', 'mocking', 'tdd']",356,True,0,1
How to configure Kotlin Androidx dependencies for unit testing as well as succesfully writing the unit test,"<p>Up and running with android, and at the same time trying to understand what I am doing.</p>

<p>I have tried all sorts, read as much resources as I can related to unit testing android. One way or another I still come short and error after error when I run the unit tests. </p>

<p>Instrumented testing was straight forward and I actually managed to satisfactory getting it working.</p>

<p>Now onto unit test and I have gotten tired of changing one dependency to another because one is not compatible with the version of android. Finding these dependencies is a bit of sweat, I have relied more on this forum than the docs to figure out how to piece things together.</p>

<p>Here is my dependency configuration:
<a href=""https://i.stack.imgur.com/VgKBa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VgKBa.png"" alt=""enter image description here""></a></p>

<p>Here is my MainActivity class</p>

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

<p>And here is my test class set up against the activity. It is fairly simple for practical purposes:</p>

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

<p>I get this error now, after resolving a bunch of other errors:</p>

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

<p>I am basically spending an awful lot of time on configuration than doing what I need to do - write the unit test. </p>

<p>How can I go about successfully configuring the dependencies to enable me to write a successful unit test. If my tests are also wrong, how can I correctly change them?</p>
",https://stackoverflow.com/questions/61801671/how-to-configure-kotlin-androidx-dependencies-for-unit-testing-as-well-as-succes,"['android', 'kotlin', 'androidx', 'android-testing']",22,False,0,0
Koin Unit testing how to verify whether a class method was called when injected by &quot;by inject()&quot;,"<p>I have a class for which I have written unit tests. The class injects 2 other classes via the constructor. However due to cyclic dependency issues, I had to inject one of the other dependencies via by inject().</p>
<p>My class looks as the follows:</p>
<pre><code>class AuthUseCase(
    private val accessTokenUseCase: AccessTokenUseCase,
    private val refreshTokenRepo: RefreshTokenRepo
) : KoinComponent {

    val notificationService: NotificationService by inject()



    fun getSyncedAccessToken(loginResult: LoginResult): Token? {
        return when (loginResult) {
            is LoginResult.Success -&gt; {
                accessTokenUseCase.storeRefreshToken(loginResult.accessToken)
                notificationService.init()
                loginResult.accessToken.accessToken
            }
            is LoginResult.Failure -&gt; {
                null
            }
        }
    }
}
</code></pre>
<p>I want to test if notificationService.init was fired or not in my test.
Normally it would be as simple as</p>
<pre><code>verify(notificationService).init()
</code></pre>
<p>However I cannot understand how to mock this class. Any help would be highly appreciated.</p>
",https://stackoverflow.com/questions/63154656/koin-unit-testing-how-to-verify-whether-a-class-method-was-called-when-injected,"['android', 'unit-testing', 'koin']",344,False,0,1
Error in mocking for embedded unit testing &quot;Address of overloaded function does not match required type &#39;void()&#39;,"<p>I am working on an Embedded C project for which I am currently writing unit tests. I am using the fff mocking framework, which essentially creates fake function calls which should overload hardware specific calls.</p>
<p>When I create a 'fake function' I get an error stating that</p>
<blockquote>
<p>Address of overloaded function does not match required type 'void()'</p>
</blockquote>
<p>This is happening every time I attempt to create a Fake. I am primarily an embedded C programmer, and only using elements of C++ for the purposes of unit testing. I don't really understand what this message is telling me or why it is a problem. If anyone could offer any insight, I would be very grateful.</p>
<p>The code in question is shown below. The error is highlighted on the function names: xTaskCreate, HAL_TIM_Base_Init and HAL_TIM_ConfigClockSource.</p>
<pre><code>#include &lt;TinyEmbeddedTest.h&gt;
#include &lt;stdio.h&gt;
#include &quot;stm32f1xx_hal.h&quot;
#include &quot;FreeRTOS.h&quot;
#include &quot;task.h&quot;
#include &quot;fff.h&quot;

#include &quot;heater.c&quot;  //source file being tested

DEFINE_FFF_GLOBALS;

FAKE_VALUE_FUNC(BaseType_t, xTaskCreate, TaskFunction_t, char *, configSTACK_DEPTH_TYPE, void *, UBaseType_t, TaskHandle_t *);
FAKE_VALUE_FUNC(HAL_StatusTypeDef, HAL_TIM_Base_Init, TIM_HandleTypeDef);
FAKE_VALUE_FUNC(HAL_StatusTypeDef, HAL_TIM_ConfigClockSource, TIM_HandleTypeDef, TIM_ClockConfigTypeDef*);
</code></pre>
",https://stackoverflow.com/questions/64821121/error-in-mocking-for-embedded-unit-testing-address-of-overloaded-function-does,"['c++', 'c', 'unit-testing', 'mocking', 'fake-function-framework']",301,True,0,1
Unit testing Python Azure Function: How do I construct a mock test request message with a JSON payload?,"<p>I want to unit test my Python Azure function. I'm following the <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#unit-testing"" rel=""nofollow noreferrer"">Microsoft documentation</a>.</p>
<p>The documentation mocks the call to the function as follows</p>
<pre class=""lang-py prettyprint-override""><code>req = func.HttpRequest(
            method='GET',
            body=None,
            url='/api/HttpTrigger',
            params={'name': 'Test'})
</code></pre>
<p>I would like to do this but with the parameters passed as a JSON object so that I can follow the <code>req_body = req.get_json()</code> branch of the function code. I guessed I would be able to do this with a function call like</p>
<pre class=""lang-py prettyprint-override""><code>req = func.HttpRequest(
            method='GET',
            body=json.dumps({'name': 'Test'}),
            url='/api/HttpTrigger',
            params=None)
</code></pre>
<p>If I construct the call like this, <code>req.get_json()</code> fails with the error message <code>AttributeError: 'str' object has no attribute 'decode'</code>.</p>
<p>How do I construct the request with JSON input parameters? It should be trivial but I'm clearly missing something obvious.</p>
",https://stackoverflow.com/questions/63326322/unit-testing-python-azure-function-how-do-i-construct-a-mock-test-request-messa,"['python', 'azure', 'unit-testing']",2226,True,3,2
unit testing a FlatFileItemWriter outside of Spring - &quot;Writer must be open before it can be written to&quot; exception,"<p>I am writing a simple batch that writes a CSV file, and I wanted to use Spring Batch <code>FlatFileItemWriter</code> for that, using Spring Boot 2.3.1.RELEASE.</p>
<p>I want to unit test my writer so that I can confirm it's configured properly.</p>
<p>the code is very simple :</p>
<pre class=""lang-java prettyprint-override""><code>    public class CSVResultWriter implements ItemWriter&lt;Project&gt; {

    private final FlatFileItemWriter writer;

    public CSVResultWriter(String outputResource) {

      writer=new FlatFileItemWriterBuilder&lt;Project&gt;()
          .name(&quot;itemWriter&quot;)
          .resource(new FileSystemResource(outputResource))
          .lineAggregator(new PassThroughLineAggregator&lt;&gt;())
          .append(true)
          .build();

    }

   @Override
   public void write(List&lt;? extends Project&gt; items) throws Exception {
     writer.write(items);
   }
}

</code></pre>
<p>and I am writing a simple unit test without Spring, something like  :</p>
<pre class=""lang-java prettyprint-override""><code>    File generatedCsvFile = new File(workingDir.toString() + File.separator + &quot;outputData.csv&quot;);

    CSVResultWriter writer = new CSVResultWriter(generatedCsvFile.getAbsolutePath());

    Project sampleProject = Project.builder().name(&quot;sampleProject1&quot;).build();

    writer.write(List.of(sampleProject));

    assertThat(generatedCsvFile).exists();
</code></pre>
<p>But the test fails saying :</p>
<p><code>org.springframework.batch.item.WriterNotOpenException: Writer must be open before it can be written to</code></p>
<p>Looking at Spring source code, I don't understand how it's possible to make it work.. When trying to write items, the first thing that Spring does is checking that the writer is initialized :</p>
<p><a href=""https://github.com/spring-projects/spring-batch/blob/744d1834fe313204f06c0bcd0eedd472ab4af6be/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java#L237"" rel=""nofollow noreferrer"">https://github.com/spring-projects/spring-batch/blob/744d1834fe313204f06c0bcd0eedd472ab4af6be/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java#L237</a></p>
<pre class=""lang-java prettyprint-override""><code>    @Override
    public void write(List&lt;? extends T&gt; items) throws Exception {
        if (!getOutputState().isInitialized()) {
            throw new WriterNotOpenException(&quot;Writer must be open before it can be written to&quot;);
        }
...
</code></pre>
<p>but the way OutputState is built doesn't give a chance to say it has been initiated :</p>
<p><a href=""https://github.com/spring-projects/spring-batch/blob/744d1834fe313204f06c0bcd0eedd472ab4af6be/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java#L363"" rel=""nofollow noreferrer"">https://github.com/spring-projects/spring-batch/blob/744d1834fe313204f06c0bcd0eedd472ab4af6be/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java#L363</a></p>
<pre class=""lang-java prettyprint-override""><code>    // Returns object representing state.
    protected OutputState getOutputState() {
        if (state == null) {
            File file;
            try {
                file = resource.getFile();
            }
            catch (IOException e) {
                throw new ItemStreamException(&quot;Could not convert resource to file: [&quot; + resource + &quot;]&quot;, e);
            }
            Assert.state(!file.exists() || file.canWrite(), &quot;Resource is not writable: [&quot; + resource + &quot;]&quot;);
            state = new OutputState();
            state.setDeleteIfExists(shouldDeleteIfExists);
            state.setAppendAllowed(append);
            state.setEncoding(encoding);
        }
        return state;
    }
</code></pre>
<p>--&gt; the <code>initialized</code> flag in <code>OutputState</code> keeps its default value, which is false.</p>
<p>So I am a bit puzzled.. I guess when this is managed by Spring, some magic happens and it works.</p>
<p>Am I missing something obvious, or can't we really test this outside of Spring ?</p>
",https://stackoverflow.com/questions/63596068/unit-testing-a-flatfileitemwriter-outside-of-spring-writer-must-be-open-befor,"['java', 'spring-batch']",1659,True,1,1
"Transformed LiveData&#39;s value is always null in unit testing even when observed, but works fine in the UI","<p>I want to test a <code>LiveData</code>'s value. This <code>LiveData</code>'s value depends on another <code>LiveData</code> in the ViewModel. When I run the app, the UI is working as intended. However, when I create a unit test to test the dependent <code>LiveData</code>, the test always fails with an <code>AssertionError</code> saying that the value is always <code>null</code>.</p>
<p>I have the following <code>LiveData</code> in my ViewModel.</p>
<pre><code>class MovieViewModel @ViewModelInject constructor(
    private val movieRepository: MovieRepository
) : ViewModel() {
    private val state = movieRepository.getMoviesState()
    val errorLoading: LiveData&lt;Boolean&gt;
        get() = Transformations.map(state) { it == State.ERROR }
    val isLoading: LiveData&lt;Boolean&gt;
        get() = Transformations.map(state) { it == State.LOADING }
    ...
}
</code></pre>
<p>The <code>LiveData</code> I want to test are <code>errorLoading</code> and <code>isLoading</code>. To do that, I use Mockk to mock objects and have the following code to test them both.</p>
<pre><code>    @Test
    fun ensure_isLoading_is_true_when_state_is_loading() {
        ...
        every { movieRepository.getMoviesState() } returns MutableLiveData(State.LOADING)
        every { booleanObserver.onChanged(any()) } just runs
        viewmodel = MovieViewModel(movieRepository)
        verify { movieRepository.getMoviesState() }
        viewmodel.isLoading.observeForever(booleanObserver)
        verify { booleanObserver.onChanged(true) }
        assertEquals(true, viewmodel.isLoading.value)
        viewmodel.isLoading.removeObserver(booleanObserver)
    }
</code></pre>
<p>So far, the test can verify that <code>onChanged</code> on the mocked Observer is called and the value of the new change is also correct. However, when I want to access the value of the <code>LiveData</code> I want to test, it always returns null.</p>
<p>I am aware that the <code>LiveData</code> needs to be observed and I have made  a mock Observer to do that. However, the test still fails. Why does it always return null?</p>
",https://stackoverflow.com/questions/65262857/transformed-livedatas-value-is-always-null-in-unit-testing-even-when-observed,"['android', 'unit-testing', 'android-livedata', 'android-testing', 'mockk']",1025,False,1,2
Unit Testing Ag Grid&#39;s column header with Jest and Angular Cli. Unable to find all columns from columnDefs,"<p>I'm using Jest and Angular Cli testing to verify column headers.</p>

<p>Trying to mimic this: <a href=""https://www.ag-grid.com/javascript-grid-testing-angular/#testing-grid-contents"" rel=""nofollow noreferrer"">https://www.ag-grid.com/javascript-grid-testing-angular/#testing-grid-contents</a></p>

<p>The issue is, i'm able to only find 2/5 columns from querySelectorAll('className');</p>

<p>I tried various approaches like naming them all with different header class and selecting by them, but i always got just 2/5 column headers.</p>

<p>I imagine it is something to do with rendering, but i might be wrong.</p>

<p>Here is all of the relevant files.</p>

<p>Test.spec.ts</p>

<pre><code>
import { ComponentFixture, async, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { TestGridComponent } from './test-grid.component';


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

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                AgGridModule.withComponents([TestGridComponent])
            ],
            declarations: [TestGridComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();

        fixture = TestBed.createComponent(TestGridComponent);
        component = fixture.componentInstance;

        fixture.detectChanges();
    }));

    // Works
    it('grid API is not available until  `detectChanges`', () =&gt; {
        expect(component.gridOptions.api).not.toBeTruthy();
    });

    // Fails with expect(received).toBeTruthy()  Received: undefined
    it('grid API is available after `detectChanges`', () =&gt; {
        fixture.detectChanges();
        expect(component.gridOptions.api).toBeTruthy();
    });


    // Able to get 'ID 'and 'Quantity' but not the rest of the header fields. I see them on the grid but not in the received.
    //
      output: expect(received).toEqual(expected) // deep equality

   // - Expected
   // + Received

    /*  Array [
    -   ""ID"",
    -   ""Quantity"",
    -   ""someStuff1"",
    -   ""someStuff2"",
    -   ""someStuff3"",
    +   ""ID"",
    +   ""Quantity"",
      ]
    */

    it('should display grid headers as expected', () =&gt; {        
        const elm = fixture.nativeElement;
        fixture.detectChanges();

        const grid = elm.querySelector('ag-grid-angular');
        // have also tried other classes as defined in my config.ts
    headerClass: 'testColumn' and searched querySelectorAll with that - same result.
        const headerCells = grid.querySelectorAll('.ag-header-cell-text');

        const headerTitles = Array.from(headerCells).map((cell: any) =&gt;
            cell.textContent.trim()
        );        

        expect(headerTitles).toEqual(['ID', 'Quantity', 'someStuff1', 'someStuff2', 'someStuff3']);
    });   

});

</code></pre>

<p>test-grid.config.ts</p>

<pre><code>export const defaultColDef = {
  filter: true,
  sortable: true,
  resizable: true,
  headerClass: 'testColumn'
};

export const columnDefs = [  
  {
    headerName: 'ID',
    headerTooltip: 'ID',
    field: 'id',
    cellStyle: colorSide,
    headerClass: 'header1'
  },  
  {
    headerName: 'Quantity',
    headerTooltip: 'Quantity',
    field: 'quantity',
    cellStyle: {'text-align': 'right'},    
    headerClass: 'header2'
  },  
  {
    headerName: 'SomeField1',
    field: 'SomeField1',
    headerTooltip: 'somefield1',
    cellStyle: {'text-align': 'right'},
    headerClass: 'header3'
  },
  {
    headerName: 'SomeField2',
    headerTooltip: 'SomeField2',
    field: 'someField2',
    cellStyle: {'text-align': 'left'},
    headerClass: 'header4'
  },
  {
    headerName: 'SomeField3',
    headerTooltip: 'SomeField3',
    field: 'SomeField3',
    cellStyle: {'text-align': 'left'},
    headerClass: 'header5'
  }
];
</code></pre>

<p>TestComponent-grid.ts</p>

<pre><code>@Component({
  selector: 'web-client-app-common-grid',
  templateUrl: './test-grid.component.html'
})
export class TestGridComponent {
  // Data is coming from another container component, which was populated with the help of ngRx store.
  @Input() rowData;

  columnDefs: any;  
  defaultColDef: any;
  gridApi;
  gridColumnApi;
  gridOptions: GridOptions;  
  tooltipShowDelay;
  headerHeight: 48

  constructor() {
    this.columnDefs = columnDefs;
    this.defaultColDef = defaultColDef;
    this.tooltipShowDelay = 0;
  }

  onGridReady(gridOptions) {
    this.gridOptions= gridOptions;
    this.gridApi = gridOptions.api;
    this.gridColumnApi = gridOptions.columnApi;    
    this.gridOptions = &lt;GridOptions&gt;{
      headerHeight:75,   
    }  
  }
</code></pre>

<p>.html</p>

<pre><code>
&lt;h1&gt; Grid Works &lt;/h1&gt;

&lt;ag-grid-angular
  class=""ag-vertical-lines""
  [rowData]=""rowData""
  [columnDefs]=""columnDefs""
  [defaultColDef]=""defaultColDef""
  (gridReady)=""onGridReady($event)""
  (firstDataRendered)=""onFirstDataRendered()""
  [tooltipShowDelay]=""tooltipShowDelay""
  style="" height: 100%; width: 100%;""
&gt;&lt;/ag-grid-angular&gt;

</code></pre>

<p>jest.config.ts</p>

<pre><code>module.exports = {
  name: 'test-web-client',
  preset: '../../jest.config.js',
  coverageDirectory: '../../target/coverage',
  reporters: [
    'default',
    ['jest-junit', { outputDirectory: './target/coverage' }]
  ],
  snapshotSerializers: [
    'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
    'jest-preset-angular/build/AngularSnapshotSerializer.js',
    'jest-preset-angular/build/HTMLCommentSerializer.js'
  ],
  testEnvironment: 'jest-environment-jsdom-fourteen'
};
module.exports.globals = {
  'ts-jest': {
    tsConfig: 'tsconfig.spec.json',
    stringifyContentPathRegex: '\\.html$',
    astTransformers: [require.resolve('jest-preset-angular/build/StripStylesTransformer')]
  }
};
module.exports.setupFilesAfterEnv = ['&lt;rootDir&gt;/src/test-setup.ts'];
</code></pre>

<p>I'm not sure where i'm going wrong, upon inspecting i see the selectors classes.</p>

<p>let me know if you need anymore info.</p>

<p>Please and Thanks. </p>
",https://stackoverflow.com/questions/61556017/unit-testing-ag-grids-column-header-with-jest-and-angular-cli-unable-to-find-a,"['angular', 'typescript', 'jestjs', 'ag-grid-angular', 'angular-observable']",3304,True,1,2
Netty unit testing: How to test invocations on the Channel object that is part of the passed ChannelHandlerContext?,"<p>Part of the behavior of a <code>ChannelHandler</code> implementation is that it should send a response after receiving a message. However, the passed <code>ChannelHandlerContext</code> does seem to create an internal <code>Channel</code> instance that is not equal to the <code>EmbeddedChannel</code> instance used in the unit test. So, it is not possible to test from outside that a response has actually been written to the channel.</p>

<p>Here is some code to clarify the problem:</p>

<pre><code>public class EchoHandler extends SimpleChannelInboundHandler&lt;Object&gt;
{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        ctx.channel().writeAndFlush(msg);
    }
}

@Test
public void aTest() throws Exception
{
    EchoHandler handler = new EchoHandler();
    EmbeddedChannel channel = spy(new EmbeddedChannel(handler));
    Object anObject = new Object();
    channel.writeInbound(anObject);
    verify(channel, times(1)).writeAndFlush(eq(anObject)); // will fail
}
</code></pre>
",https://stackoverflow.com/questions/60259809/netty-unit-testing-how-to-test-invocations-on-the-channel-object-that-is-part-o,"['java', 'unit-testing', 'netty']",692,True,1,1
Unit testing a class with EF Core and in memory Sqliteprovider - stack overflow error in a test runner,"<p>I'd like to write a unit test for my service and I use in memory Sqlite database provider for this purpose, however, I am getting stack overflow error in a test runner while trying to add some entities to a DbContext.
The issue does not occur while reading from the DbContext.</p>
<p>The test code:</p>
<pre class=""lang-cs prettyprint-override""><code>public class DbBoardGameServiceTest : IDisposable
    {
        private readonly TestDbFactory _testDbFactory;
        private readonly BoardGamesDbContext _dbContext;
        private readonly Mock&lt;IMapper&gt; _mapperMock = new Mock&lt;IMapper&gt;();
        private readonly DbBoardGameService _sut;

        public DbBoardGameServiceTest()
        {
            _testDbFactory = new TestDbFactory();
            _dbContext = _testDbFactory.CreateDbContext();

            _sut = new DbBoardGameService(_dbContext, _mapperMock.Object);
        }

        [Fact(DisplayName = &quot;All BoardGames from a database are returned after being mapped when service gets all board games&quot;)]
        public void All_BoardGames_from_a_database_are_returned_when_after_being_mapped_service_gets_all_board_games()
        {
            _mapperMock.Setup(mock =&gt; mock.Map&lt;BoardGameDto&gt;(It.IsAny&lt;Models.BoardGame&gt;()))
                       .Returns&lt;Models.BoardGame&gt;(boardGame =&gt; DtoWithName(boardGame.Name));

            _dbContext.BoardGames.AddRange(TestBoardGames); //this line causes stackoverflow
            var games = _dbContext.BoardGames.ToArray(); // this line does not cause any errors

            var actualBoardGames = _sut.GetAllBoardGames().ToArrayAsync().Result;

            var expectedBoardGames = new[]
            {
                DtoWithName(&quot;Name1&quot;),
                DtoWithName(&quot;Name2&quot;),
                DtoWithName(&quot;Name3&quot;),
                DtoWithName(&quot;Name4&quot;),
            };

            actualBoardGames.Should().BeEquivalentTo(expectedBoardGames);
        }

        private static Models.BoardGame[] TestBoardGames =&gt; new[]
        {
            new BoardGameBuilder().WithName(&quot;Name1&quot;).WithId(1).Build(),
            new BoardGameBuilder().WithName(&quot;Name2&quot;).WithId(2).Build(),
            new BoardGameBuilder().WithName(&quot;Name3&quot;).WithId(3).Build(),
            new BoardGameBuilder().WithName(&quot;Name4&quot;).WithId(4).Build()
        };

        private static BoardGameDto DtoWithName(string name) =&gt; new BoardGameDto(0, name, 0, 0, 0);

        public void Dispose() =&gt; _testDbFactory.Dispose();
    }


</code></pre>
<p>I'm completely lost, I've come across the information that stack overflow during tests might be caused by circular dependencies, but I doubt this is the case.
Any hints would be much appreciated.</p>
<p>EDIT:
It fails on Ubuntu 20.04, but on macOS it works fine.</p>
",https://stackoverflow.com/questions/62811351/unit-testing-a-class-with-ef-core-and-in-memory-sqliteprovider-stack-overflow,"['c#', '.net-core', 'xunit', 'ef-core-3.1']",68,False,0,0
Unit Testing a custom TagHelper where HTML conditionally rendered based on the presence of a ValidationAttribute on the model Property,"<p>I have a custom TagHelper which extends the OOTB InputTagHelper. I am conditionally adding attributes to it based on the presence of a custom ValidationAttribute on the model property associated with it. The code for this in the TagHelper <code>.Process</code> method works fine:</p>
<pre><code>if (this.For.Metadata.ValidatorMetadata.OfType&lt;NumericValidationAttribute&gt;().Any())
{
   output?.Attributes.SetAttribute(new TagHelperAttribute(&quot;inputmode&quot;, &quot;numeric&quot;));
   output?.Attributes.SetAttribute(new TagHelperAttribute(&quot;pattern&quot;, &quot;[0-9]*&quot;));
}
</code></pre>
<p>My issue is in Unit Testing this. I have other Unit Tests written using the code available in the Net Core MVC Test repo: <a href=""https://github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/"" rel=""noreferrer"">https://github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/</a></p>
<p>... but there's no real steer on how to create the <code>For</code> i.e <code>ModelExpression</code> for the property I want to test which has this Validation attribute associated with it: e.g.</p>
<pre><code>    public class TestModel
    {
        [NumericValidation(ErrorMessage = &quot;Error message&quot;)]
        public string Field1 { get; set; }
    }
</code></pre>
<p>I want to be able to populate the <code>For.Metadata.ValidatorMetadata</code> list for this ModelExpression and I don't know how.</p>
<p>The full Unit Test which doesnt work is:</p>
<pre><code>[Fact]
        public void CustomInputTagHelperProcess_NumericValidationAttributeOnModelProperty_GeneratesCorrectHtml()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
            var model = new TestModel
            {
                Field1 = &quot;cc&quot;,
            };
            var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(TestModel), model);
            var modelExpression = new ModelExpression(name: &quot;Field1&quot;, modelExplorer: modelExplorer);
            var viewContext = TestableHtmlGenerator.GetViewContext(model, metadataProvider);

            var attributes = new TagHelperAttributeList
            {
                { &quot;name&quot;, PropertyName },
                { &quot;type&quot;, InputTypeName },
            };

            var tagHelperContext = new TagHelperContext(attributes, new Dictionary&lt;object, object&gt;(), nameof(CustomInputTagHelperTest));

            var output = new TagHelperOutput(
                Input,
                new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =&gt; Task.FromResult&lt;TagHelperContent&gt;(result: null))
            {
                TagMode = TagMode.SelfClosing,
            };

            var customInputTagHelper = new CustomInputTagHelper(this.htmlGenerator)
            {
                For = this.modelExpression,
                InputTypeName = InputTypeName,
                Name = PropertyName,
                ViewContext = this.viewContext,
            };

            // Act
            customInputTagHelper.Process(this.tagHelperContext, output);

            // Assert - ensure we have an inputmode attribute on the input.
            Assert.Contains(output.Attributes, x =&gt; x.Name == &quot;inputmode&quot; &amp;&amp; x.Value.ToString() == &quot;numeric&quot;);
        }
</code></pre>
<p>Any thoughts?</p>
",https://stackoverflow.com/questions/65239861/unit-testing-a-custom-taghelper-where-html-conditionally-rendered-based-on-the-p,"['unit-testing', 'asp.net-core-mvc', 'asp.net-core-tag-helpers', 'validationattribute']",342,False,8,0
how to make the sql database table reflect in the sqlite db when creating unit testing with Laravel 7?,"<p>I have a database with a few database tables in mysql of my laravel 7 application.
Now am trying to do unit testing , but the problem is, is there a way to make those database tables in mysql reflect in the sqlite db that I prefer to use in phpunit ? .how to do that? ..</p>
<p>in the root directory I created a file and named it .env.testing
then I modified its configuration into this</p>
<pre><code>DB_CONNECTION=sqlite
DB_DATABASE=&quot;C:/wamp64/www/myapplication/test.sqlite&quot;
</code></pre>
<p>when I ran the phpunit existing sample test file/suite in laravel 7,
nothing happened, the test.sqlite has no tables..what did I missed out ?</p>
",https://stackoverflow.com/questions/62947600/how-to-make-the-sql-database-table-reflect-in-the-sqlite-db-when-creating-unit-t,"['laravel', 'phpunit', 'laravel-7']",317,False,1,1
Getting issue as &quot;SyntaxError: Unexpected token { in JSON at position 40&quot; in while unit testing using mocha and chai,"<p>I am new to unit testing using Mocha and Chai. I am getting issue when I am testing my Rest API using  Mocha and Chai.</p>

<p>test.js </p>

<pre><code>let  chaiHttp = require('chai-http');
let chai = require('chai');
let should = chai.should ();
let expect = chai.expect;
let server = require('../app');
chai.use(chaiHttp)

describe(""Put /api/approvedUser/:id"",() =&gt; {
  it('it should Put the tasks ', (done) =&gt; {
                 const userid = 'farmer.Ak';
                  var userdata = {
                    ROLEID: 1,
                    approved: true 
                   }

                chai.request(server)
                    .put(""/approvedUser/"" + userid)
                    .send(userdata)
                    .end((err, res) =&gt; {
                        const body = res.body;
                        console.log(body);
                        res.should.have.httpstatus(200);                        
                        // res.body.should.be.a('object');
                         res.body.should.be.property('secret');
                        // res.body.should.be.property('ROLEID');
                        // res.body.should.be.property('approved');
                        // res.body.should.be.property('id').eq('dfarm1');
                         done();                  
                    })
                  .catch((err) =&gt; done(err));  
            });
        });     
</code></pre>

<p>API Response </p>

<pre><code> responseSuccessfully registered admin user pc and imported it into the wallet {""secret"":""KwCqRJIIwjKx"",""data"":{""type"":""X509"",""mspId"":""org1MSP"",""certificate"":""-----BEGIN CERTIFICATE-----\nMIICdDCCAhugAwIBAgIUPy8fI7Ul5x4tFKKZTRnthgAYnBgwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMjA2MTMzNTAwWhcNMjEwMjA1MTM0\nMDAwWjAeMQ8wDQYDVQQLEwZjbGllbnQxCzAJBgNVBAMTAnBjMFkwEwYHKoZIzj0C\nAQYIKoZIzj0DAQcDQgAEZi/vji38zbn8tvNVwWY+TaolA6oD5pG3braBh7TOhtVP\nLZsWlP07baSAa0aXnpyz0JDFYeggrY2xoTGg5jXKoaOB4TCB3jAOBgNVHQ8BAf8E\nBAMCB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUXcPkIg5WC2o0nI//LCNeeybk\n2fcwKwYDVR0jBCQwIoAgQNPu+NJFQ7FeXcKiC8WYjVl2gJGm6wZolSTDojNtmNIw\ncgYIKgMEBQYHCAEEZnsiYXR0cnMiOnsiYXBwcm9sZSI6InByb2Nlc3NpbmdDZW50\nZXIiLCJoZi5BZmZpbGlhdGlvbiI6IiIsImhmLkVucm9sbG1lbnRJRCI6InBjIiwi\naGYuVHlwZSI6ImNsaWVudCJ9fTAKBggqhkjOPQQDAgNHADBEAiAVUtW3FCy0rQUq\nbBCVEwMVkl7jw8KvSK1TDhDykRIj6wIgYrl8/s9+TtO9blZSCERMznC6fdQBmXC+\nLHEkr+tge6o=\n-----END CERTIFICATE-----\n"",""privateKey"":""-----BEGIN PRIVATE KEY-----\r\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgbuamIkkqqxjZtIey\r\nn35VYSc8RTaITfVBGY0AflPJp8ShRANCAARmL++OLfzNufy281XBZj5NqiUDqgPm\r\nkbdutoGHtM6G1U8tmxaU/TttpIBrRpeenLPQkMVh6CCtjbGhMaDmNcqh\r\n-----END PRIVATE KEY-----\r\n""},""httpstatus"":200}   
</code></pre>

<p>In above code I am trying to test the put method and sending some userdata which is in json, but I am getting error as "" </p>

<blockquote>
  <p>""SyntaxError: Unexpected token { in JSON at position 40"" 
  please suggest how can I fix this issue??</p>
</blockquote>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/60096553/getting-issue-as-syntaxerror-unexpected-token-in-json-at-position-40-in-whi,"['node.js', 'unit-testing', 'mocha.js', 'chai']",288,False,1,1
"Best practice for Unit Testing class which is mostly responsible to call methods of dependencies, but contains logic as well","<p>Let's assume I have <code>StartCommandHandler</code> which has responsibility to create some file with required files. But for doing this I have to give him a set of sub-responsibilities, like:</p>

<ul>
<li>Checks whether file exists in the FTP</li>
<li>If Not downloads files from multiple sources to the temp folder</li>
<li>Then executes some script in the folder</li>
<li>Then read generated file after script execution</li>
<li>Then create zip from that folder</li>
<li>Then remove that folder</li>
<li>Then updates database</li>
</ul>

<p>As a result of that Command Handler, we are creating folder with all required files. And now that folder is ready for another operations.</p>

<p>I have just read <code>""Art of the Unit testing""</code>. And started to add unit tests. I have followed <code>SOLID</code> principles as well. Especially, <code>SRP</code> and <code>DIP</code>, which are in my opinion prerequisites for Unit Testing.
So, most of that things which I stated above are done with specific interfaces. So, 90% job of that Command Handler is to call methods of dependencies. And 10% is the logic like this:</p>

<pre><code>if(!_dependency1.IsAnySomething())
{
     _dependency2.Download();

      var isScriptNeeded = _dependency2.IsScriptNeeded();

      if(isScriptNeeded)
      {
          var res = _dependency3.ExecuteScript();
         _dependency4.SetScriptResult(res.Info, res.Date, res.State);
      }

     _dependency3.Archive();

     _dependency5.DeleteTemp();
}
</code></pre>

<p>I already tested all dependencies of that command handler. But, hat command handler also includes some small logics like, is download file needed, or temp files are deleted or not and so on...</p>

<p><strong><em>I have so many question in my mind like:</em></strong></p>

<ol>
<li>May be Unit Testing doesn't make sense for such units? Integration Test to the rescue? Because, it seems wrong to test whether to check all calls, like whether <code>DeleteTemp</code> is called after download, or script is executed or not, or <strong><em>script result is passed in a right way</em></strong> to <code>SetScriptResult</code> method. Is it GOOD Unit Test?</li>
<li>Is there any way to refactor that class for making it testable?</li>
</ol>
",https://stackoverflow.com/questions/61848902/best-practice-for-unit-testing-class-which-is-mostly-responsible-to-call-methods,"['java', 'c#', 'unit-testing', 'testing', 'integration-testing']",1082,True,5,5
"If &#39;ongoingStatus&#39; is a directive input, make sure the directive is imported by the current module. Unit testing error","<p>I'm facing the issue something like this,
 If 'ongoingStatus' is a directive input, make sure the directive is imported by the current module. (""contact"" role=""tabpanel"" aria-labelledby=""pills-contact-tab"">
                        ][ongoingStatus]=""projects "">
     
        Binding to event property 'ongoingStatus' is disallowed for security reasons, please use (goingStatus)=...
        If 'ongoingStatus' is a directive input, make sure the directive is imported by the current module. (""contact"" role=""tabpanel"" aria-labelledby=""pills-contact-tab""></p>

<p>Failed: Template parse errors:
Binding to event property 'ongoingStatus' is disallowed for security reasons, please use (goingStatus)=...
If 'ongoingStatus' is a directive input, make sure the directive is imported by the current module. (""contact"" role=""tabpanel"" aria-labelledby=""pills-contact-tab"">
                ][ongoingStatus]=""projects "">
            
            

<p><strong>projects.spec.ts</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA ,CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';

import { AllProjectsComponent } from './all-projects.component';
import { RouterTestingModule } from '@angular/router/testing';
import { ProjectsService } from './../../../../services/projects/projects.service';
import { GooglePlaceModule } from 'ngx-google-places-autocomplete';
import { ProjectObject } from './../../../../models/project.model';
import { MockProjectService } from './../../../../mock/mockProject.service';



describe('AllProjectsComponent', () =&gt; {
  let component: AllProjectsComponent;
  let fixture: ComponentFixture&lt;AllProjectsComponent&gt;;
  let service : ProjectsService;
  let response;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ AllProjectsComponent ],
      imports: [  RouterTestingModule, GooglePlaceModule ],
      providers: [
        {
          provide: ProjectsService,
          useClass: MockProjectService
        },],
      schemas: [ NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AllProjectsComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ProjectsService);
    response = {

      project: {
          projectType : ""public"",
          status : ""open"",
      }    

  } as ProjectObject

    fixture.detectChanges();
  });

  it('', () =&gt; {
    component.ngOnInit();
    expect(service.getAllprojects()).toBe(response);
  })


</code></pre>

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

<pre><code> &lt;div class=""tab-pane fade"" id=""pills-contact"" role=""tabpanel"" aria-labelledby=""pills-contact-tab""&gt;
    &lt;app-ongoing-projects [ongoingStatus]=""projects ""&gt;&lt;/app-ongoing-projects&gt;
 &lt;/div&gt;
</code></pre>

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

<pre><code>import { ProjectObject } from './../../../../models/project.model';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ProjectsService } from './../../../../services/projects/projects.service';
import { GooglePlaceDirective } from 'ngx-google-places-autocomplete';
import { Address } from 'ngx-google-places-autocomplete/objects/address';


@Component({
  selector: 'app-all-projects',
  templateUrl: './all-projects.component.html',
  styleUrls: ['./all-projects.component.scss']
})
export class AllProjectsComponent implements OnInit {


  // public projects;
  public projects: ProjectObject[];
  @ViewChild('placesRef', { static: false }) placesRef: GooglePlaceDirective;
  public option = {
    types: ['(cities)'],
    componentRestrictions: { country: 'IN' }
  };

  public location: string;
  public licenseType: string;

  public resetBtn = false;
  public loading = true;

  validdata: boolean;
  constructor( private projectsService: ProjectsService) { }

  ngOnInit(): void {
      this.projectsService.getAllprojects().subscribe((data) =&gt; {
      console.log(data);
      this.projects = data;
      this.loading = false;

      if (!this.projects['0']) {
       this.validdata = true;

      }
      });

  }

  public handleAddressChange(address: Address) {
    this.location = address.formatted_address;
    console.log(address)
  }


}
</code></pre>
",https://stackoverflow.com/questions/61411476/if-ongoingstatus-is-a-directive-input-make-sure-the-directive-is-imported-by,"['angular', 'typescript', 'unit-testing', 'ionic-framework', 'rxjs']",2169,True,1,1
Spring Unit Testing: Using @SpyBean to mock a void method: getting NullPointerException for that bean unless I use @Mock instead,"<p>i am trying to make @SpyBean or @MockBean work in this test as they are working in all my other tests. the only difference here is this test uses an active profile because it mocks some AWS libs </p>

<p>I shouldnt have to instantiate the class it if I am using SpyBean, i've seen countless examples similar to mine below that seem to work fine.</p>

<p>The unit I'm testing:</p>

<pre><code>@Component
public class SqsAdapter {

    @Autowired
    QueueMessagingTemplate queueMessagingTemplate;

    @Autowired
    MyProcessor processor;

    @SqsListener(""${queue.name}"")
    public void onEvent(String message) {
        if (!StringUtils.isEmpty(message)) {
            processor.process(message);
        } else { 
            log.error(""Empty or null message received from queue"");
        }
    }
}
</code></pre>

<p>and a simple unit test to expect process(...) to be called:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@ActiveProfiles(""local"")
public class SqsAdapterTest {

    @Autowired
    AmazonSQSAsync amazonSQS;

    @SpyBean
    MyProcessor processor;

    @InjectMocks
    SqsAdapter adapter;

    @Test
    public void testOnEvent() {
        doNothing().when(processor).process(any()); // &lt;---- process() is void
        String event = ""royale with cheese"";
        adapter.onEvent(event);
        verify(processor, times(1)).process(event);
    }
}
</code></pre>

<p>when i debug in the unit test, i get a <code>java.lang.NullPointerException
</code> on <code>processor</code> as if it never gets initialized:</p>

<p>ive also tried switching it to @MockBean with the same results</p>

<p>furthermore, i also tried stripping the testing of the @SpringBootTest and the @ActiveProfiles ... and removed the AmazonSQSAsync dependency since im not mocking the Listener itself, and it still throws the same NPE</p>

<p>what am i missing here?</p>
",https://stackoverflow.com/questions/59849202/spring-unit-testing-using-spybean-to-mock-a-void-method-getting-nullpointerex,"['java', 'spring', 'unit-testing', 'mockito', 'spring-bean']",13827,True,5,2
"In Java unit testing, how to verify a variable of type Function is called with certain arguments passed in?","<p>I have a variable of type <code>Function</code> like:</p>
<pre><code>Class SomeClass{ 
    static final Function&lt;Throwable, Optional&lt;String&gt;&gt; SOME_FUNCTION = throwable -&gt; Optional.empty();
}
</code></pre>
<p>I am wondering how to verify it was called for certain times and was passed in certain arguments?</p>
<p>What I need is the equivalent of the following code:</p>
<p><code>verify(SomeClass, times(2)).SOME_FUNCTION(any(Exception.class));</code></p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/64717863/in-java-unit-testing-how-to-verify-a-variable-of-type-function-is-called-with-c,"['java', 'unit-testing', 'mockito']",289,True,0,1
How do I mock externally injected libraries that use import (ES6 typescript) exported in a node module for unit testing,"<p>In my main app, I am bringing in the node package ""ibm_db"" using:
<code>import * as ibmdb from ""ibm_db"";</code></p>

<p>In my unit tests I want to be able to override this, then I:
<code>import * as ibmdb from ""ibm_db"";</code></p>

<p>in my unit test and then:</p>

<pre><code>beforeEach(() =&gt; {
   ibmdb.open = jasmine.createSpy(""open"");
});
</code></pre>

<p>I get error:</p>

<pre><code>Cannot assign to 'open' because it is a readOnly property.
</code></pre>

<p>I need to know with typescript (being compiled into js using tsc, then tested using jasmine command), the right way to mock these functions so I can tell if there being called, I don't want the calls to actually fire.</p>
",https://stackoverflow.com/questions/59709175/how-do-i-mock-externally-injected-libraries-that-use-import-es6-typescript-exp,"['javascript', 'node.js', 'typescript', 'unit-testing', 'jasmine']",182,True,1,1
"When unit testing a viewmodel with a repository that returns a flow, an error happen when converting it to a livedata","<p>I need some help about writing unit tests in android, related to the viewmodel, livedata and flow mechanics and dispatching.</p>
<p>First of all, im writing <strong>unit tests</strong>, and not instrumeted test.</p>
<p>Actually, im creating an Unit test for an android app, for testing a ViewModel that uses a repository for fetching some data from internet.</p>
<p>The code for the viewmodel im using is like this:</p>
<pre class=""lang-kotlin prettyprint-override""><code>class ViewModel(private var repository: Repository? = Repository()) :
  androidx.lifecycle.ViewModel() {

  val data: LiveData&lt;Result&lt;Item&gt;&gt; = repository!!.remoteData.asLiveData()
}
</code></pre>
<p>The unit test code is as follows:</p>
<pre class=""lang-kotlin prettyprint-override""><code>import junit.framework.TestCase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.junit.MockitoJUnitRunner

@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class ViewModelTest : TestCase() {
    private val testDispatcher = TestCoroutineDispatcher()
    private lateinit var repository: Repository
    private lateinit var viewModel: ViewModel

    @Before
    public override fun setUp() {
        Dispatchers.setMain(testDispatcher)
        repository = mock(Repository::class.java)
        viewModel = ViewModel(repository)
    }

    @After
    public override fun tearDown() {
        super.tearDown()
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }

    @Test
    fun `remote data is returned`() = runBlockingTest {
        try {
          `when`(repository.remoteData).thenReturn(
            flowOf(Result.success(Item(SampleData.remoteData.apiResult!!)))
          )
          viewModel.data.observeForever { result -&gt;
                assertTrue(result.isSuccess)
            }
        } catch (exception: Exception) {
            fail()
        }
    }

}
</code></pre>
<p><strong>When creating the unit test, and running it, the following error happen:</strong></p>
<pre><code>java.lang.IllegalArgumentException: Parameter specified as non-null is null: method androidx.lifecycle.FlowLiveDataConversions.asLiveData, parameter $this$asLiveData

</code></pre>
<p>As for the error, it seems that i need to pass a parameter to the <em>viewmodel.data</em> value, but, which one? as per the code, it not need parameters.</p>
<p>I like to know about mocking the methods that returns a flow object, as the <em>asLiveData()</em> function is the one that, when running the test, throws the exception above.</p>
<p>Also, i think i need to know about the <em>observeForever</em> function for executing and observing values from the livedata, after all, is then observing where i can assert the results of the unit test.</p>
<p>Any help would be great. :)</p>
<p>Im using the following libraries in the app build.gradle file:</p>
<pre><code>    testImplementation &quot;junit:junit:4.13&quot;
    testImplementation &quot;com.squareup.okhttp3:mockwebserver:4.7.2&quot;
    testImplementation &quot;org.mockito:mockito-core:3.3.3&quot;
    testImplementation &quot;androidx.arch.core:core-testing:2.1.0&quot;
    testImplementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.2&quot;
    androidTestImplementation &quot;androidx.test.ext:junit:1.1.2&quot;
    androidTestImplementation &quot;androidx.test.espresso:espresso-core:3.3.0&quot;
</code></pre>
",https://stackoverflow.com/questions/64093240/when-unit-testing-a-viewmodel-with-a-repository-that-returns-a-flow-an-error-ha,"['unit-testing', 'android-livedata', 'android-viewmodel', 'kotlin-flow', 'android-unit-testing']",3563,True,6,1
Unit testing; How to mock out a class object which is going to be passed to a function in Python?,"<p>I'm in the means of doing a Python embedded project where I'm using Python-OpenZwave to communicate with a sensor via a z-wave dongle. And I need to do some unit testing on functions I have implemented. I'm not that experienced in unit testing, and have run into a problem with dependencies that I need to get rid of during the unit testing, because some of these funtions I have implemented communicates with the sensor and therefore only work on my embedded platform.</p>
<p>One of the functions I need to test is shown below, it takes 2 arguments, first is the ID of the sensor, the second is a network class object from the OpenZWave libary. It first sets the ID of the sensor we are working with in the class through a function call, second gets all data from the sensor and saves it as a dict in the class object, whereafter I search through all the data for the temperature value and return it;</p>
<pre><code>def get_temperature(sensor_id, network_obj):
    multisensor = network_obj.nodes[sensor_id]
    multisensor.get_values()
    values = {}
    for value in multisensor.values:
        if multisensor.values[value].label == 'Temperature':
            values = {'Temperature': multisensor.values[value].data}
    return values
</code></pre>
<p>The thing I need help with, is how I can get rid of the dependency coming from the class object which is parsed to the function? I have tried methods I found online Patching, MonkeyPatching, Mock and MagicMock but haven't been able to make any of it work. So I would like some advice on how I can get rid of the dependencies and what libary / tool I should use in this case.</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/64753811/unit-testing-how-to-mock-out-a-class-object-which-is-going-to-be-passed-to-a-fu,"['python', 'unit-testing', 'mocking', 'monkeypatching', 'z-wave']",67,False,1,0
How do I fix an exception thrown during unit testing because SQLite doesn&#39;t have a certain function defined in HasDefaultValueSql?,"<p>I have the following configuration for a BaseEntity that every other entity derives from:</p>
<pre><code>    entityTypeBuilder.Property(e =&gt; e.CreatedDate)
        .HasColumnType(&quot;timestamp without time zone&quot;)
        .HasDefaultValueSql(&quot;NOW()&quot;)
        .IsRequired();
</code></pre>
<p>I am using SQLite in my Unit tests but since addition of this field, they have started to throw an exception about &quot;NOW()&quot;. How do I fix this?</p>
",https://stackoverflow.com/questions/62969333/how-do-i-fix-an-exception-thrown-during-unit-testing-because-sqlite-doesnt-have,"['sqlite', 'unit-testing', 'asp.net-core', 'entity-framework-core']",111,False,0,0
"When unit testing, is it good practice to mock the dependencies of the test object when you don&#39;t need to?","<p>As an example, let's look at 3 classes:</p>
<p>B</p>
<p>C</p>
<p>A(B,C)</p>
<p>So A has a dependency on B and C. If B and C have already been unit tested - when writing unit tests for A is it considered good practice to create the test object A with mocked objects of B and C if you don't need to?</p>
",https://stackoverflow.com/questions/62974552/when-unit-testing-is-it-good-practice-to-mock-the-dependencies-of-the-test-obje,"['java', 'unit-testing', 'dependency-injection', 'mockito', 'standards']",643,False,0,1
"React JS Jest Unit Testing SpyOn ComponentDidMount action call, Getting Cannot spy on .. property because it is not a function","<p>I am learning to jest test react js reflux action calls from the componentDidMount() method</p>

<p>the jsx imports the store call like so</p>

<pre><code>import MyStore from '~/stores/myStore'

componentDidMount() {
  MyStore.getData()
}
</code></pre>

<p>In my myStore.test.jsx code</p>

<pre><code>import React from 'react'
import renderer from 'react-test-renderer'

jest.dontMock('./myStore.jsx')

const MyStore = require('./myStore.jsx').default

describe('', () =&gt; {
   it(''), () =&gt; {
     const spy = jest.spyOn(MyStore.prototype, 'MyStore.getData')
     render.create(&lt;MyStore/&gt;).getInstance()
     expect(spy).toHaveBeenCalled()
   }
}
</code></pre>

<p>I was following another similar post </p>

<pre><code>https://stackoverflow.com/questions/43245040/using-jest-to-spy-on-method-call-in-componentdidmount
</code></pre>

<p>But I am getting the following jest test error</p>

<pre><code>Cannot spy the MyStore.getData() property because it is not a function
</code></pre>

<p>I have not been able to find a testing on reflux action which involves a call to the store.</p>

<p>Is there a fix? Is there a better way to test the calls in componentDidMount?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/62045603/react-js-jest-unit-testing-spyon-componentdidmount-action-call-getting-cannot-s,"['reactjs', 'jestjs']",305,True,0,1
How do I get hundred percent code coverage with my unit testing on this component and access the else part?,"<p>I have no idea how to access the remaining line of code. I simply need to get a full code coverage. Checking if the function has been called (toHaveBeenCalled() ) will also do.</p>
<p>Pasting in the TypeScript file and my Spec file. My current code-coverage is as follows</p>
<p>TOTAL: 7 SUCCESS</p>
<p>==================== Coverage summary ========================</p>
<p>Statements   : 87.5% ( 35/40 )</p>
<p>Branches     : 100% ( 10/10 )</p>
<p>Functions    : 75% ( 6/8 )</p>
<p>Lines        : 86.11% ( 31/36 )</p>
<p>================================================================================</p>
<p><a href=""https://i.stack.imgur.com/NsVXY.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/NsVXY.jpg"" alt=""enter image description here"" /></a></p>
<p><strong>auth-guard.service.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>import { AuthKeywords } from './../_models/common.model';
import { environment } from 'src/environments/environment';
import { AppService } from './../app.service';
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { ConfirmationService } from 'primeng/api';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  isLoggedIn: boolean = false;
  constructor(public router: Router, public appService: AppService,
    public cookieService: CookieService, public confirmationService: ConfirmationService) { }

  canActivate(): Observable&lt;boolean&gt; {
    const token = this.cookieService.get(AuthKeywords.TOKEN);
    if (token &amp;&amp; !this.tokenExpired(token)) {
      this.isLoggedIn = true;
      return of(this.isLoggedIn);  
    } else {
      this.appService.confirmButtonLabel = 'Login';
      this.confirmationService.confirm({
        message: 'You are not logged in, Please login to Traders Desktop',
        accept: () =&gt; {
          this.isLoggedIn = false;
          window.location.replace(environment.traders_desktop);
          return of(this.isLoggedIn);
        }
      });
    }
  }

  public tokenExpired(token: string) {
    const expiry = (JSON.parse(atob(token.split('.')[1]))).exp;
    return (Math.floor((new Date).getTime() / 1000)) &gt;= expiry;
  }
}
</code></pre>
<p><strong>auth-guard.service.gen.spec.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>import { TestBed } from '@angular/core/testing';
import { AppService } from './../app.service';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { Confirmation, ConfirmationService } from 'primeng/api';
import { AuthGuardService } from './auth-guard.service';
import {} from 'jasmine';


describe('AuthGuardService', () =&gt; {
  let service: AuthGuardService;

  beforeEach(() =&gt; {
    const appServiceStub = () =&gt; ({ confirmButtonLabel: {} });
    const routerStub = () =&gt; ({});
    const cookieServiceStub = () =&gt; ({ get: token =&gt; ({}) });
    const confirmationServiceStub = () =&gt; ({ confirm: object =&gt; ({}) });


    TestBed.configureTestingModule({
      providers: [
        AuthGuardService,
        { provide: AppService, useFactory: appServiceStub },
        { provide: Router, useFactory: routerStub },
        { provide: CookieService, useFactory: cookieServiceStub },
        { provide: ConfirmationService, useFactory: confirmationServiceStub }
      ]
    });
    service = TestBed.get(AuthGuardService);
    const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dnZWRpbiI6dHJ1ZSwidXNlcm5hbWUiOiJ5YXNoLW1pc2hyYSIsImxvZ2luX3RpbWUiOjE2MDE0NTMxNDAsIkxBU1RfQUNUSVZJVFkiOjE2MDE0NTMxNDAsInN1cGVyX3VzZXIiOnRydWUsImlzcyI6IlRyYWRlVmlzaW9uMjAyMC5jb20iLCJzdWIiOiJDaGFydElRVmVyaWZpY2F0aW9uIiwiYXVkIjoieWFzaC1taXNocmEiLCJleHAiOjE2MDE1Mzk1NDB9.6S2cIrflTPRdTjXIaYaFcb2J5LrTa9-yqzfVVuNC85M';
    service.tokenExpired(token)
  });

  it('can load instance', () =&gt; {
    expect(service).toBeTruthy();
  });

  it(`isLoggedIn has default value`, () =&gt; {
    expect(service.isLoggedIn).toEqual(false);
  });

  it('checks button label value', () =&gt; {
    const appServiceStub: AppService = TestBed.get(AppService)
    expect(appServiceStub.confirmButtonLabel).toBeTruthy();
    expect(appServiceStub.confirmButtonLabel).toBeDefined()
  })

  describe('token expiration', () =&gt; {
    it('checks token expiration', () =&gt; {
      const cookieServiceStub: CookieService = TestBed.get(CookieService);
      const confirmationServiceStub: ConfirmationService = TestBed.get(ConfirmationService);
      const component: AuthGuardService = TestBed.get(AuthGuardService);
      
      spyOn(component, 'tokenExpired').and.callThrough();
      const token:string = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dnZWRpbiI6dHJ1ZSwidXNlcm5hbWUiOiJ5YXNoLW1pc2hyYSIsImxvZ2luX3RpbWUiOjE2MDE0NTMxNDAsIkxBU1RfQUNUSVZJVFkiOjE2MDE0NTMxNDAsInN1cGVyX3VzZXIiOnRydWUsImlzcyI6IlRyYWRlVmlzaW9uMjAyMC5jb20iLCJzdWIiOiJDaGFydElRVmVyaWZpY2F0aW9uIiwiYXVkIjoieWFzaC1taXNocmEiLCJleHAiOjE2MDE1Mzk1NDB9.6S2cIrflTPRdTjXIaYaFcb2J5LrTa9-yqzfVVuNC85M'
      component.tokenExpired(token)

      expect(component.tokenExpired).toHaveBeenCalled();
      
    })
  })

  describe('checks canActivate Observable', () =&gt; {
    it('checks inside if condition', () =&gt; {
      const component: AuthGuardService = TestBed.get(AuthGuardService);
      spyOn(component, 'tokenExpired')
      let tempToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dnZWRpbiI6dHJ1ZSwidXNlcm5hbWUiOiJ5YXNoLW1pc2hyYSIsImxvZ2luX3RpbWUiOjE2MDE0NTMxNDAsIkxBU1RfQUNUSVZJVFkiOjE2MDE0NTMxNDAsInN1cGVyX3VzZXIiOnRydWUsImlzcyI6IlRyYWRlVmlzaW9uMjAyMC5jb20iLCJzdWIiOiJDaGFydElRVmVyaWZpY2F0aW9uIiwiYXVkIjoieWFzaC1taXNocmEiLCJleHAiOjE2MDE1Mzk1NDB9.6S2cIrflTPRdTjXIaYaFcb2J5LrTa9-yqzfVVuNC85M'
      component.tokenExpired(tempToken);
      component.canActivate().subscribe(token =&gt; {
        expect(token).toBe(true);
      });  
    })

    it('checks inside else condition', () =&gt; {

      const component: AuthGuardService = TestBed.get(AuthGuardService);
      const appServiceStub: AppService = TestBed.get(AppService);
      
      spyOn(component, 'tokenExpired').and.returnValue(true)
      service.canActivate()
      expect(appServiceStub.confirmButtonLabel).toBe('Login')
    })

    it('checks accept inside else condition', () =&gt; {
      const component: AuthGuardService = TestBed.get(AuthGuardService);
      const appServiceStub: AppService = TestBed.get(AppService);
      const confirmationServiceStub: ConfirmationService = TestBed.get(ConfirmationService)
      let param: Confirmation = {message: 'Test Message', accept: () =&gt; {return false}}


      spyOn(component, 'tokenExpired').and.returnValue(true)

      spyOn(confirmationServiceStub, 'confirm')
      
      })
    })

});
</code></pre>
",https://stackoverflow.com/questions/64147421/how-do-i-get-hundred-percent-code-coverage-with-my-unit-testing-on-this-componen,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1019,False,0,1
While doing Unit testing with Jasmine should I mock or spy or stub my service which is injected in my component?,"<p>In my component.ts the service has been injected in the constructor of the component which subscribe to a function in the service and receives information. How can I test my component in that case?</p>

<p>In the component.ts I have the following code :-</p>

<p>How can I proceed in that case? </p>
",https://stackoverflow.com/questions/60506316/while-doing-unit-testing-with-jasmine-should-i-mock-or-spy-or-stub-my-service-wh,"['angular', 'unit-testing', 'karma-jasmine']",1074,True,0,1
Why am I expecting a status code of 200 but got a status code of 404 while unit testing in python?,"<p>I am writing a unit test case in python using unittest and pytest for a file. Out of the many functions I am unable to understand why doesn't it execute as a successfully passed test case.
Here is function which displays a settings page,and upon a successfull call it displays an html page.</p>
<pre><code>@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    global application_inst
    if request.method == 'POST':
        print(&quot;Setting changed&quot;)

    return render_template('settings.html', user=session['user'], application=application_inst)

</code></pre>
<p>and the unit testcase for the function is written below as:</p>
<pre><code>class MyApp(unittest.TestCase):
    def setUp(self):
        self.app = create_app(db)
        self.client = self.app.test_client(self)

        with self.app.app_context():
            # create all tables
            db.create_all()

    def tearDown(self):
        pass

    def test_settings_passed(self):
        response = self.client.get('/settings', follow_redirects=True)
        self.assertEqual(response.status_code, 200)
</code></pre>
<p>The error that I get in the stacktrace is:</p>
<pre><code>test_app.py::MyApp::test_settings_passed FAILED                          [100%]ENV :default
############ INIT ############
############ INIT ############
############ INIT ############

 
200 != 404

Expected :404
Actual   :200
&lt;Click to see difference&gt;
</code></pre>
<p>Please help me on this.</p>
",https://stackoverflow.com/questions/64256256/why-am-i-expecting-a-status-code-of-200-but-got-a-status-code-of-404-while-unit,"['python', 'unit-testing', 'flask', 'python-unittest']",1046,True,-2,1
As i am trying to perform unit testing on angular application..but i am getting below error while running the test,"<p>1 spec, 1 failure
Spec List | Failures
OverviewComponent should create
Failed: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?).
Error: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?).
at syntaxError (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:215:1)
at CompileMetadataResolver._getDependenciesMetadata (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:10807:1)
at CompileMetadataResolver._getTypeMetadata (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:10700:1)
at CompileMetadataResolver._getInjectableTypeMetadata (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:10922:1)
at CompileMetadataResolver.getProviderMetadata (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:10931:1)
at http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:10869:1
at Array.forEach ()
at CompileMetadataResolver._getProvidersMetadata (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:10829:1)
at CompileMetadataResolver.getNgModuleMetadata (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:10548:1)
at JitCompiler._loadModules (http://localhost:9876/<em>karma_webpack</em>/webpack:/node_modules/@angular/compiler/fesm5/compiler.js:22567:1)</p>
<p>============================================</p>
<pre><code>
describe('OverviewComponent', () =&gt; {
  let component: OverviewComponent;
  let fixture: ComponentFixture&lt;OverviewComponent&gt;;
  let router : Router

 
  const fakeActivatedRoute = {
    snapshot: { data: {  } }
  } as ActivatedRoute;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports:[
        SharedModule,
        FlexLayoutModule,
       
       // RouterModule.forRoot(routes),
        RouterTestingModule
      ],
       
      declarations: [ OverviewComponent,
      FooterComponent,
      LoginComponent,
      ChangePasswordComponent,
      ForgotPasswordComponent,
      AppComponent],

      providers:[
      HttpClient,
      HttpHandler,
      DataService,
      NgxSpinnerService,
      Router,
      RouterModule,
      EmitterService,
      {provide: ActivatedRoute, 
        useValue: fakeActivatedRoute}
      ]
    })
    .compileComponents();
    

  }));

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


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

 
});
</code></pre>
",https://stackoverflow.com/questions/62771018/as-i-am-trying-to-perform-unit-testing-on-angular-application-but-i-am-getting,"['angular6', 'karma-jasmine']",82,True,0,1
"Cordova build fails if I set &#39;type: modules&#39; in package.json. How do I resolve this, yet still carry out unit testing?","<p>I've built a simple app for Android, using the <a href=""https://cordova.apache.org/"" rel=""nofollow noreferrer"">Cordova framework</a>.  I have now now implemented a simple unit test (using <a href=""https://github.com/substack/tape"" rel=""nofollow noreferrer"">Tape</a>), which runs in Node.  Since the files I'm testing use ES6 modules, in order to run the tests in Node, I had to add <code>&quot;type&quot;: &quot;module&quot;,</code> to my <code>package.json</code> file.  But when I did that, my app would no longer build--the Cordova build command fails with the output below.  What is the proper way to resolve this issue?</p>
<ul>
<li>Is it possible to programmatically set <code>&quot;type&quot;: &quot;module&quot;,</code>?  If so, I can perhaps set it only when unit tests are running.</li>
<li>Or is some part of my method flawed in this case? That is certainly a possibility.  Maybe if I test in the browser (rather than in Node), this issue will be avoided?</li>
</ul>
<p>Thanks.</p>
<hr />
<p><strong>Build Output</strong></p>
<pre><code>$ cordova build android
Unable to load PlatformApi from platform. Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\snarl\my-project\platforms\android\cordova\Api.js
require() of ES modules is not supported.
require() of C:\Users\snarl\my-project\platforms\android\cordova\Api.js from C:\Users\snarl\AppData\Roaming\npm\node_modules\cordova\node_modules\cordova-lib\src\cordova\util.js is an ES module file as it is a .js file whose nearest parent package.json contains &quot;type&quot;: &quot;module&quot; which defines all .js files in that package scope as ES modules.
Instead rename Api.js to end in .cjs, change the requiring code to use import(), or remove &quot;type&quot;: &quot;module&quot; from C:\Users\snarl\my-project\package.json.

Unhandled error. ('The platform &quot;android&quot; does not appear to be a valid cordova platform. It is missing API.js. android not supported.')
</code></pre>
",https://stackoverflow.com/questions/62656119/cordova-build-fails-if-i-set-type-modules-in-package-json-how-do-i-resolve-t,"['javascript', 'node.js', 'unit-testing', 'cordova', 'es6-modules']",325,True,0,1
Unit Testing Components utilizing &quot;ChartJS&quot; with Jest and Enyzme in TypeScript for React Error: TypeError: Cannot read property &#39;getContext&#39; of null,"<p>I'm trying to unit test (<code>RiskChartComponent.spec.ts</code>) a React component in my application named <code>RiskChartComponent.tsx</code>:</p>
<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import RiskChartComponent from '../RiskChartComponent/RiskChartComponent'

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

    it('should render successfully', () =&gt; {
        const props = { xAxisArray: [4, 3, 2, 1, 0, -1, -2, -3, -4], yAxisArray: [-491.11, -392.11, -305.38, -140.15, -6.74, 6.18, 44.77, -12.04, -190.24], label: 'Delta', context: '2d'};

        const wrapped = shallow(&lt;RiskChartComponent{...props} /&gt;, { lifecycleExperimental: true });

        expect(wrapped).toBeTruthy();
    });
});
</code></pre>
<p>But when I run <code>npm test --watch</code> this unit test always fails with the following error:
<a href=""https://i.stack.imgur.com/WjdKo.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WjdKo.png"" alt=""enter image description here"" /></a></p>
<p>My component I'm trying to unit test is as follows:</p>
<pre><code>import React from 'react'
import Chart from &quot;chart.js&quot;;

interface RiskChartViewModel {
    xAxisArray: any[];
    yAxisArray: any[];
    label:string;
}

export default class RiskChartComponent extends React.Component&lt;RiskChartViewModel, {}&gt; {    
    chartRef:any = React.createRef();
    datacollection: any;

    fillData() {
        this.datacollection = {
            labels: this.props.xAxisArray,
            datasets: [{
                label: this.props.label,
                data: this.props.yAxisArray,
                backgroundColor: ['rgba(0, 35, 93, 0.2)'],
                borderColor: ['rgba(0, 35, 93, 1)']
            }]
        };
    }
    
    componentDidUpdate() {
        this.buildGraph();
    }

    componentDidMount() {
        this.buildGraph();
    }

    buildGraph()
    {
        const myChartRef = this.chartRef.current.getContext(&quot;2d&quot;);
        this.fillData();

        new Chart(myChartRef, {
            type: &quot;line&quot;,
            data: this.datacollection,
            options: {
                legend: {
                    display:false
                },
                scales: {
                    yAxes: {
                        display:true,
                        labelString: 'Delta'
                    },
                    xAxes: [{
                        display:true,
                        labelString:'Price',
                        ticks: {
                            callback: function(value, index, values) {
                                return '$' + value;
                            }
                        }
                    }]
                }
            }
        });
    }

    render() {
        return (
            &lt;div className=&quot;row&quot; &gt;
                &lt;div className=&quot;col-sm-8&quot;&gt;
                    &lt;div className=&quot;card&quot;&gt;
                        &lt;canvas id=&quot;myChart&quot; ref={this.chartRef} /&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        )
    }
}
</code></pre>
<p>In my initial research it seems that Jest uses <code>jsdom</code> for mocking the necessary parts of the DOM to be able to run the tests in Node, thus avoiding style calculation and rendering that a browser would normally do. Do I then need to mock <code>Chart.js</code> in this unit test to get it to work? How would I go about doing that in this instance?</p>
",https://stackoverflow.com/questions/64178570/unit-testing-components-utilizing-chartjs-with-jest-and-enyzme-in-typescript-f,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'enzyme']",5354,True,0,1
"In Java unit testing, how to mock the variables that are not injected but created inside the to-be-tested class?","<p>For example, the class to be tested is</p>
<pre><code>public class toBeTested {
    private Object variable;

    public toBeTested(){
        variable = someFactory();         // What if this someFactory() sends internet request? 
                                          // Can I mock &quot;variable&quot; without calling 
                                          // someFactory() in testing?
    }

    public void doSomething(){
        ...
        Object returnedValue = variable.someMethod();  // In testing, can I mock the behavior of 
                                                       // this someMethod() method when 
                                                       // &quot;variable&quot; is a private instance 
                                                       // variable that is not injected? 
        
        Object localVariable = new SomeClass();        // Can I mock this &quot;localVariable&quot; in 
                                                       // testing?
        ...
    }
}
</code></pre>
<p>My questions are as stated in the comments above.</p>
<p>In short, how to mock the variables that are not injected but created inside the to-be-tested class?</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/64404657/in-java-unit-testing-how-to-mock-the-variables-that-are-not-injected-but-create,"['java', 'unit-testing', 'junit', 'mockito']",1034,True,0,2
how to post and put request in unit testing with front-end angular and back-end node using jasmine and karma?,"<p>I have created one angular project and one node project for add data in SQL workbench.</p>
<p>I can add data in SQL workbench while I am running ng serve from angular project.</p>
<p>while the time of unit testing using jasmine &amp; karma and we run ng test command &amp; its run your test case and we got data in console log but we didn't get data in SQL database.</p>
<p><a href=""https://i.stack.imgur.com/q4svS.png"" rel=""nofollow noreferrer"">api.services.spec.ts</a></p>
<p><a href=""https://i.stack.imgur.com/owXNk.png"" rel=""nofollow noreferrer"">Form.component.ts</a></p>
<p>Can anyone help me for the same?</p>
<p>Thanks in Advance</p>
",https://stackoverflow.com/questions/64658067/how-to-post-and-put-request-in-unit-testing-with-front-end-angular-and-back-end,"['angular', 'unit-testing', 'karma-jasmine', 'angular-unit-test']",124,False,0,1
Is Angular unit-testing with 100% coverage still worth the effort when we test all our different use cases with Protractor anyway?,"<p>We have a <strong>microservice Architecture</strong>, multiple UIs, multiple Spring Boot Backends etc. And as a result our <strong>UI Projects are very sleek</strong>, contains just the frontend logic and consist of maximum 2-3 functional html pages.</p>

<p>Still, we have 100% Code coverage in unittest, and also we test every functional scenario also with Protractor, which are the most important tests for us, since they test the whole flow, and test if the whole application really works. So mostly for a regular UI with 2 pages, we have sth like 40-50 different protractor tests, for different use cases regardigng validations, success/error cases, display options etc.</p>

<p>So we have this debate again and again in team. Is unittesting Angular really worth for us?</p>

<p>My thought: When i compare my UI Code with my Backend code, <strong>Angular code is mostly more complex in terms of data flow than a backend</strong>. So in backend mostly the methods have input and output parameter, and you can really isolate them while testing. You must of course mock some service calls, but mostly the main task of a method is really imaginable and makes mostly sense also on its own.</p>

<p>In Angular world (or in Javasscript world actually) it seems a bit different. Mostly we have subscriptions, and events and some input and outputs from components and hostlisteners etc. So A main task of a function makes mostly no sense on its own. Mostly you need to check multiple components/services/DOM to see what the code really does at the end. </p>

<p>But other than that, <strong>Angular unittesting is for most of us really pain mostly</strong> (although we have 3-4 years of experience). Image you have a @ViewChild in some component, and you have to test the function which uses it. You need <strong>to simulate the whole DOM</strong> in order you have a HTMLElement at the end which you can test. Other than that you have mostly some <strong>timing sensitivity, in come cases you must wait for the next angular lifecycle in your tests etc</strong>. At the end the unitttest which you write <strong>is very technical in comparison to backend tests</strong>, and you write your tests mostly against your assumptions/mocks. And you cover with some unittest of a function mostly just a tiny part of your flow.</p>

<p><strong>But most importantly, the whole this code runs in Protractor Tests anyhow. For example, we have a service call, and have 2 functional branches there, success and error case. We test both these cases with our protractor tests from an whole other level. For this simple functional use case you only need 2 protractor tests. But when you want to unittest this exact flow/case, you need mostly tests in X separate places in order to cover the whole flow, and at the end this is still not guaranteed that your code will really work on a browser since you cannot really test the interactions between those multiple modules/components which run together. It is how it sounds: ""unittest"".</strong></p>

<p>We also cannot use this old argument for unittest like ""it is the first tests in your test hierarchy, so until you see your error in a system tests"" etc. We have a CI/CD Pipeline which let the both tests run always with every commit.</p>

<p><strong>I want to emphasize that the discussion is not about whether we should write unittest with 0% or 100% coverage. I believe, we should write unittest when we need.</strong> For example we have a function which use some regex. There you have really many many cases, which you may not want to cover all seperate with 50 protractor tests (time consuming). But you can really test this with your 50+ unittests, faster, cleaner. and also you can develop ""test-driven"". So can beautifully write your unittests first, and then your regex.</p>

<p>Also when you have some complex if/else logic; from a user view, regarding UI when there is not any change between some cases which you can distinguish with your protractor, you also have to write unittest.</p>

<p>But all in all, what we currently do, trying to have 100% Angular code coverage is, i believe really an overengineering. At the end our main aim is to guarantee that the code works. If our protractor tests the 90% of the whole application anyway, it sould be sufficient when we just unittest the rest and the logical places selectively.</p>

<p>What do you think?</p>
",https://stackoverflow.com/questions/61950950/is-angular-unit-testing-with-100-coverage-still-worth-the-effort-when-we-test-a,"['angular', 'unit-testing', 'protractor', 'code-coverage']",308,False,2,0
"Unit testing randomly stops working in Visual Studio . Has anyone else had this problem, and if so how do I fix it?","<p>My unit tests in Visual studio almost never run saying 'Test not run'. This happens regardless of the project. All day Yesterday they ran and passed with the only issue being a test in a test class I deleted still passed for some reason. I didn't do anything different yesterday, I just open Visual Studio as normal. I closed my laptop lid last night and attempted to run them again this morning and now they will not run again. Has anyone had this issue before? I have Visual Studio 2019. </p>
",https://stackoverflow.com/questions/60919566/unit-testing-randomly-stops-working-in-visual-studio-has-anyone-else-had-this,"['c#', 'visual-studio-2019']",236,True,1,3
Why do I get Method “props” is only meant to be run on a single node. 0 found instead in unit testing?,"<p>I was creating unit tests for my modal component but when I run the tests I get <code>Method “props” is onlymeant to be run on a single node. 0 found instead.</code> Here is my test file's excerpt: </p>

<pre><code>test('should contain input fields with appropriate labels', () =&gt; {
        expect(
            wrapper
                .find('Input')
                .at(0)
                .props().label
        ).toEqual('Current Password');
        expect(
            wrapper
                .find('Input')
                .at(1)
                .props().label
        ).toEqual('New Password');
        expect(
            wrapper
                .find('Input')
                .at(2)
                .props().label
        ).toEqual('Confirm New Password');
    });

    test('should contain input fields with appropriate placeholders', () =&gt; {
        expect(
            wrapper
                .find('Input')
                .at(0)
                .props().placeholder
        ).toEqual('Please enter your current password');
        expect(
            wrapper
                .find('Input')
                .at(1)
                .props().placeholder
        ).toEqual('Please enter your new password');
        expect(
            wrapper
                .find('Input')
                .at(2)
                .props().placeholder
        ).toEqual('Please confirm your new password');
    });

    test('should contain input fields with required props', () =&gt; {
        expect(
            wrapper
                .find('Input')
                .at(0)
                .props().required
        ).toEqual(true);
        expect(
            wrapper
                .find('Input')
                .at(1)
                .props().required
        ).toEqual(true);
        expect(
            wrapper
                .find('Input')
                .at(2)
                .props().required
        ).toEqual(true);
    });
});
</code></pre>

<p>And this is my component file that I want to test:</p>

<blockquote>
  <p>class ChangePasswordModalRoot extends PureComponent {
          form = FormBuilder.group(
              {
                  currentPassword: ['', [Validators.required]],
                  newPassword: ['', [Validators.required, Validators.pattern(RESET_PASSWORD_FORMAT)]],
                  confirmPassword: ['', [Validators.required]],
              },
              { validators: checkIfMatchingPasswords('newPassword', 'confirmPassword') as ValidatorFn }
          );</p>

<pre><code>    handleSave = () =&gt; {
        const { onSave } = this.props;
        const oldPassword = this.form.get('currentPassword').value;
        const newPasswordLeft = this.form.get('newPassword').value;
        const newPasswordRight = this.form.get('confirmPassword').value;
        onSave(oldPassword, newPasswordLeft, newPasswordRight);
    };

    render() {
        const { isShow, classes, onClose } = this.props;

        return (
            &lt;div className={classes.container}&gt;
                &lt;FieldGroup
                    control={this.form}
                    strict={false}
                    render={({ invalid }) =&gt; (
                        &lt;ModalDialog
                            maxWidth=""sm""
                            isShow={isShow}
                            disableSave={invalid}
                            config={{
                                title: `New password`,
                                handleConfirm: this.handleSave,
                                handleCancel: onClose,
                            }}
                        &gt;
                            &lt;div className={classes.defautlWrapper}&gt;
                                &lt;div className={classes.defautlWrapper}&gt;
                                    &lt;FieldControl
                                        name=""currentPassword""
                                        render={({ handler, errors, touched }) =&gt; (
                                            &lt;Input
                                                {...handler()}
                                                required
                                                touched={touched}
                                                label=""Current Password""
                                                type=""password""
                                                errors={errors}
                                                placeholder=""Please enter your current password""
                                                maxLength={200}
                                            /&gt;
                                        )}
                                    /&gt;
                                &lt;/div&gt;
                                &lt;div className={classes.newPasswordWrapper}&gt;
                                    &lt;FieldControl
                                        name=""newPassword""
                                        render={({ handler, errors, touched }) =&gt; (
                                            &lt;Input
                                                {...handler()}
                                                required
                                                touched={touched}
                                                errors={errors}
                                                type=""password""
                                                label=""New Password""
                                                errorMessages={DEFAULT_VALIDATION_ERRORS}
                                                placeholder=""Please enter your new password""
                                                maxLength={200}
                                            /&gt;
                                        )}
                                    /&gt;
                                &lt;/div&gt;
                                &lt;div className={classes.newPasswordWrapper}&gt;
                                    &lt;FieldControl
                                        name=""confirmPassword""
                                        render={({ handler, errors, touched }) =&gt; (
                                            &lt;div&gt;
                                                &lt;Input
                                                    {...handler()}
                                                    required
                                                    touched={touched}
                                                    errors={errors}
                                                    type=""password""
                                                    errorMessages={ERROR_MESSAGE_NO_MATCH}
                                                    label=""Confirm New Password""
                                                    placeholder=""Please confirm your password""
                                                    maxLength={200}
                                                /&gt;
                                            &lt;/div&gt;
                                        )}
                                    /&gt;
                                &lt;/div&gt;
                            &lt;/div&gt;
                        &lt;/ModalDialog&gt;
                    )}
                /&gt;
            &lt;/div&gt;
        );
    }
}
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/61058715/why-do-i-get-method-props-is-only-meant-to-be-run-on-a-single-node-0-found-in,"['reactjs', 'jestjs', 'enzyme']",97,False,0,1
Unit testing without testthat,"<p>There is one things which is wondering me. I've read something about unit testing and all I read was significantly connected with testthat (package created for unit testing). But for sure there are other approaches in R to do unit testing without using testthat package. So why they are unpopular in such level that it's even hard o find article about it ? what are the main advantages of testthat package which overwhelms unit testing market ?</p>
",https://stackoverflow.com/questions/63827740/unit-testing-without-testthat,"['r', 'unit-testing']",411,True,6,1
Is unit testing just testing methods?,"<p>I'm a new software developer and the devs are going over the importance of Java Unit Testing. Is Unit Testing just testing the individual java methods? And what is integration testing in relation to unit testing in Java?</p>
",https://stackoverflow.com/questions/63362515/is-unit-testing-just-testing-methods,"['java', 'unit-testing', 'testing']",47,True,-1,1
Why I couldn&#39;t use Microsoft.AspNetCore.Mvc; in my unit testing project?,"<p>I created an asp.net core mvc project and also created a unit testing project
below is the code for the unit testing project:</p>

<pre><code>using System;
using Microsoft.AspNetCore.Mvc;  // error, type or namespace is missing
using Xunit;

namespace Project.Tests
{
    public class UnitTest1
    { 

        [Fact]
        public void Test1()
        {
          ...
        }
    }
}
</code></pre>

<p>I don't quite understand, I used to create unit testing projects without any problem, why I cannot access <code>Microsoft.AspNetCore.Mvc</code> this time?</p>
",https://stackoverflow.com/questions/59726695/why-i-couldnt-use-microsoft-aspnetcore-mvc-in-my-unit-testing-project,"['c#', '.net', 'xunit.net']",2055,True,0,2
"Unit Testing with Mockk, java.lang.ClassCastException: PhoneValidationKt$isPhoneValid$1 cannot be cast to kotlin.jvm.functions.Function1","<p>Need some help in Unit testing my Kotlin funtion as follows, as i am new to unit testing, i had tried but failed,</p>

<p>My Kotlin top level function as follows,</p>

<pre><code>package com.reprator.phone
//PhoneValidation.kt
const val PHONE_LENGTH = 10

fun isPhoneValid(
phoneNumber: String, successBlock: (() -&gt; Unit) = {},
failBlock: (Int?.() -&gt; Unit) = {}
) =
when {
    phoneNumber.isEmpty() -&gt;
        failBlock(R.string.phone_validation_mobile_empty)
    phoneNumber.length &lt; PHONE_LENGTH -&gt;
        failBlock(R.string.phone_validation_mobile)
    else -&gt; successBlock.invoke()
}
</code></pre>

<p>My Unit test code for the above method is as follows,</p>

<pre><code>@Test
fun `Invalid Phone Number`() {
    mockkStatic(""com.reprator.phone.PhoneValidationKt"")

    val fn: (Int?) -&gt; Unit = mockk(relaxed = true)

    val result = R.string.phone_validation_mobile
    every {
        isPhoneValid(""904186605"", failBlock = captureLambda())
    } answers {
        secondArg&lt;(Int?) -&gt; Unit&gt;()(result)
    }

    isPhoneValid(""904186605"")

    verify { fn.invoke(result) }
}
</code></pre>

<p>The following is the error, i get while unit testing the code, as follows,</p>

<pre><code>java.lang.ClassCastException: com.reprator.phone.PhoneValidationKt$isPhoneValid$1 cannot be cast to kotlin.jvm.functions.Function1

at com.reprator.phone.PhoneValidationKtTest$Invalid Phone Number$2.invoke(PhoneValidationKtTest.kt:31)
at com.reprator.phone.PhoneValidationKtTest$Invalid Phone Number$2.invoke(PhoneValidationKtTest.kt:11)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2149)
at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2126)
at io.mockk.FunctionAnswer.answer(Answers.kt:19)
at io.mockk.impl.stub.AnswerAnsweringOpportunity.answer(AnswerAnsweringOpportunity.kt:13)
at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:54)
at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:263)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:25)
at io.mockk.proxy.jvm.advice.Interceptor.call(Interceptor.kt:20)
at com.reprator.phone.PhoneValidationKt.isPhoneValid(PhoneValidation.kt:15)
at com.reprator.phone.PhoneValidationKt.isPhoneValid$default(PhoneValidation.kt:7)
at com.reprator.phone.PhoneValidationKtTest.Invalid Phone Number(PhoneValidationKtTest.kt:26)
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.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>

<p>The following are the links, that i referred to try those unit testing as follows,</p>

<p><a href=""https://stackoverflow.com/questions/53808565/cast-exception-when-mocking-kotlin-lambda-callbacks-in-mockk?rq=1"">Link 1</a>
<a href=""https://stackoverflow.com/questions/53671695/how-to-mock-and-verify-lambda-expression-in-kotlin"">Link 2</a>
<a href=""https://stackoverflow.com/questions/53911556/mockk-verify-lambda-argument"">Link 3</a>
<a href=""https://stackoverflow.com/questions/53673292/how-to-call-a-lambda-callback-with-mockk"">Link 4</a></p>
",https://stackoverflow.com/questions/60928461/unit-testing-with-mockk-java-lang-classcastexception-phonevalidationktisphone,"['unit-testing', 'lambda', 'mocking', 'mockk', 'kotlintest']",3522,True,1,1
How do I do unit testing for oracle stored procedure call in spring boot JUnit 5,"<p>I am using spring-boot-starter-data-jpa and have Oracle stored procedure calls. How do I do unit testing and code coverage for this scenario.  Below is sample code</p>
<pre><code>StoredProcedureQuery userProcedure = entityManager.createStoredProcedureQuery(&quot;STOREDPROCNAME&quot;);
String param1 = &quot;p_search_string&quot;;
String param2 = &quot;p_start_position&quot;;
String param3 = &quot;P_worday_users&quot;;


userProcedure.registerStoredProcedureParameter(param1, String.class, ParameterMode.IN);
userProcedure.registerStoredProcedureParameter(param2, String.class, ParameterMode.IN);
userProcedure.registerStoredProcedureParameter(param3, void.class, ParameterMode.REF_CURSOR);
userProcedure.setParameter(param1, searchText);

List&lt;Object[]&gt; results = userProcedure.getResultList();
</code></pre>
<ol>
<li><p>Can I use in memory db instead oracle for unit testing?</p>
</li>
<li><p>How to do  unit testing for native query?</p>
<p>@Query(value = &quot;SELECT SCHEMA.ID_SEQ.nextval FROM dual&quot;, nativeQuery = true)
public int getPkgIdSeq();</p>
</li>
</ol>
",https://stackoverflow.com/questions/64150924/how-do-i-do-unit-testing-for-oracle-stored-procedure-call-in-spring-boot-junit-5,"['java', 'spring', 'spring-boot', 'unit-testing', 'spring-data-jpa']",555,False,4,0
Having a weird issue with Spring-boot + Rest Controller + Post Request + Kotlin + Unit testing,"<h2>The build file</h2>
<pre><code>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id(&quot;org.springframework.boot&quot;) version &quot;2.3.3.RELEASE&quot;
    id(&quot;io.spring.dependency-management&quot;) version &quot;1.0.9.RELEASE&quot;
    id(&quot;com.google.cloud.tools.jib&quot;) version &quot;2.5.0&quot;
    kotlin(&quot;jvm&quot;) version &quot;1.4.0&quot;
    kotlin(&quot;plugin.spring&quot;) version &quot;1.4.0&quot;
    kotlin(&quot;plugin.jpa&quot;) version &quot;1.4.0&quot;
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(&quot;org.springframework.boot:spring-boot-starter-data-jpa&quot;)
    implementation(&quot;org.springframework.boot:spring-boot-starter-data-rest&quot;)
    implementation(&quot;org.springframework.boot:spring-boot-starter-web&quot;)
    implementation(&quot;org.springframework.boot:spring-boot-starter-activemq&quot;)
    implementation(&quot;com.fasterxml.jackson.module:jackson-module-kotlin&quot;)
    implementation(&quot;org.flywaydb:flyway-core&quot;)
    implementation(&quot;org.jetbrains.kotlin:kotlin-reflect&quot;)
    implementation(&quot;org.jetbrains.kotlin:kotlin-stdlib-jdk8&quot;)
    developmentOnly(&quot;org.springframework.boot:spring-boot-devtools&quot;)
    runtimeOnly(&quot;org.postgresql:postgresql&quot;)
    testImplementation(&quot;org.springframework.boot:spring-boot-starter-test&quot;) {
        exclude(group = &quot;org.junit.vintage&quot;, module = &quot;junit-vintage-engine&quot;)
    }
    testImplementation(&quot;com.h2database:h2:1.4.200&quot;)
}

tasks.withType&lt;Test&gt; {
    useJUnitPlatform()
}

tasks.withType&lt;KotlinCompile&gt; {
    kotlinOptions {
        freeCompilerArgs = listOf(&quot;-Xjsr305=strict&quot;)
        jvmTarget = &quot;14&quot;
    }
}
</code></pre>
<h2>The controller</h2>
<pre><code>@RestController
@RequestMapping(&quot;/notification&quot;)
class NotificationResource(
    private val jobService: JobService
) {
    @PostMapping(&quot;/enqueue-mobile&quot;, produces = [APPLICATION_JSON_VALUE], consumes = [APPLICATION_JSON_VALUE])
    @ResponseStatus(ACCEPTED)
    fun enqueueMobile(@Valid @RequestBody mobile: Mobile): List&lt;Job&gt; = jobService.create(mobile)

    @GetMapping(&quot;/job-status/{id}&quot;, produces = [APPLICATION_JSON_VALUE])
    @ResponseStatus(OK)
    fun jobStatus(@Valid @PathVariable id: UUID): Job = jobService.fetch(id).get()
}

data class Mobile(
    val ids: List&lt;Long&gt;,
    val message: String
)
</code></pre>
<h2>Unit testing file</h2>
<pre><code>@SpringBootTest
@ActiveProfiles(&quot;test&quot;)
@AutoConfigureMockMvc
class NotificationResourceMobileTests {
    @Autowired
    lateinit var mockMvc: MockMvc

    @Test
    fun `with correct payload having one mobile id in a list and message - request returns http ok and response`() {
        val mobile = Mobile(ids = listOf&lt;Long&gt;(100, 101, 102), message = &quot;test&quot;)
        mockMvc.perform(post(urlPath).contentType(APPLICATION_JSON_VALUE).content(mobile.asJsonString()))
            .andDo(print())
            .andExpect(status().isAccepted)
    }

    companion object {
        const val urlPath = &quot;/notification/enqueue-mobile&quot;
    }
}
</code></pre>
<h2>The Request</h2>
<pre><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /notification/enqueue-mobile
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Content-Length:&quot;38&quot;]
             Body = {&quot;ids&quot;:[100,101,102],&quot;message&quot;:&quot;test&quot;}
    Session Attrs = {}

Handler:
             Type = com.notification.resource.NotificationResource
           Method = com.notification.resource.NotificationResource#enqueueMobile(Mobile)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.util.NestedServletException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Content-Type:&quot;application/json&quot;]
     Content type = application/json
             Body = {&quot;timestamp&quot;:&quot;2020-09-04T23:51:49.609645&quot;,&quot;status&quot;:400,&quot;error&quot;:&quot;Bad Request&quot;,&quot;message&quot;:&quot;'java.util.List com.notification.resource.Mobile.getIds()'&quot;,&quot;trace&quot;:&quot;java.lang.NoSuchMethodError: 'java.util.List com.notification.resource.Mobile.getIds()'\n\tat com.notification.service.JobService$create$1.invoke(JobService.kt:29)\n\tat com.notification.service.JobService$create$1.invoke(JobService.kt:19)\n\tat com.notification.resource.NotificationResource.enqueueMobile(NotificationResource.kt:25)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:652)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\n\tat org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:733)\n\tat org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\n\tat org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)\n\tat org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:183)\n\tat com.notification.resource.NotificationResourceMobileTests.with correct payload having one mobile id in a list and message - request returns http ok and response(NotificationResourceMobileTests.kt:134)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)\n\tat org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)\n\tat org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)\n\tat org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)\n\tat org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)\n\tat org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1510)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\n\tat java.base/java.util.ArrayList.forEach(ArrayList.java:1510)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)\n\tat org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)\n\tat org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)\n\tat org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)\n\tat org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\n\tat org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)\n\tat org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)\n\tat org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)\n\tat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)\n\tat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)\n\tat org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)\n\tat org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\n\tat org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)\n\tat org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)\n\tat com.sun.proxy.$Proxy2.stop(Unknown Source)\n\tat org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:564)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\n\tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)\n\tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)\n\tat org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)\n\tat org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)\n\tat org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)\n\tat org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)\n\tat java.base/java.lang.Thread.run(Thread.java:832)\n&quot;,&quot;path&quot;:&quot;uri=/notification/enqueue-mobile&quot;}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /notification/enqueue-mobile
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Content-Length:&quot;38&quot;]
             Body = {&quot;ids&quot;:[100,101,102],&quot;message&quot;:&quot;test&quot;}
    Session Attrs = {}

Handler:
             Type = com.notification.resource.NotificationResource
           Method = com.notification.resource.NotificationResource#enqueueMobile(Mobile)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.util.NestedServletException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Content-Type:&quot;application/json&quot;]
     Content type = application/json
             Body = {&quot;timestamp&quot;:&quot;2020-09-04T23:51:49.609645&quot;,&quot;status&quot;:400,&quot;error&quot;:&quot;Bad Request&quot;,&quot;message&quot;:&quot;'java.util.List com.notification.resource.Mobile.getIds()'&quot;,&quot;path&quot;:&quot;uri=/notification/enqueue-mobile&quot;}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Status expected:&lt;202&gt; but was:&lt;400&gt;
Expected :202
Actual   :400
</code></pre>
<blockquote>
<p>Why do I get NoSuchMethodError - when I have the field in the <code>data class</code>. Note: I can test the feature after running the app and using Postman. The same fails in unit-testing.
The unit-testing with <code>mockmvc</code> is not working as expected. The same works fine for <code>get</code> methods. Any input?</p>
</blockquote>
<pre><code>java.lang.NoSuchMethodError: 'java.util.List com.notification.resource.Mobile.getIds()'
    at com.notification.service.JobService$create$1.invoke(JobService.kt:29)
    at com.notification.service.JobService$create$1.invoke(JobService.kt:19)
    at com.notification.resource.NotificationResource.enqueueMobile(NotificationResource.kt:25)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code></pre>
",https://stackoverflow.com/questions/63749303/having-a-weird-issue-with-spring-boot-rest-controller-post-request-kotlin,"['spring-boot', 'kotlin', 'spring-boot-test', 'mockmvc']",470,False,0,0
Unit Test function in ReactJS,"<p>I have this code in my component. But I'm not sure if I'm unit testing it correctly</p>
<pre><code>const UnderConstruction = () =&gt; (
  &lt;div className=&quot;under-construction&quot;
    style={{ display: 'flex', justifyContent: 'center' }}
  &gt;
    &lt;p&gt;Under construction&lt;/p&gt;
  &lt;/div&gt;
);
</code></pre>
<p>Here's my unit testing code. But doesn't seem to work</p>
<pre><code>it('Renders with a className equal to the variant', () =&gt; {
  const {
    container: { firstChild },
  } = render(
    &lt;div
      className=&quot;under-construction&quot;
      style={{ display: 'flex', justifyContent: 'center' }}
    &gt;
      &lt;p&gt;Under construction&lt;/p&gt;
    &lt;/div&gt;,
  );
  expect(firstChild).toMatchSnapshot();
});
</code></pre>
<p><a href=""https://i.stack.imgur.com/lkt9h.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/lkt9h.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63626312/unit-test-function-in-reactjs,"['reactjs', 'jestjs']",33,False,0,1
Unit testing coroutines runBlockingTest: This job has not completed yet,"<p>Please find below a function using a coroutine to replace callback : </p>

<pre><code>override suspend fun signUp(authentication: Authentication): AuthenticationError {
    return suspendCancellableCoroutine {
        auth.createUserWithEmailAndPassword(authentication.email, authentication.password)
            .addOnCompleteListener(activityLifeCycleService.getActivity()) { task -&gt;
                if (task.isSuccessful) {
                    it.resume(AuthenticationError.SignUpSuccess)
                } else {
                    Log.w(this.javaClass.name, ""createUserWithEmail:failure"", task.exception)
                    it.resume(AuthenticationError.SignUpFail)
                }
            }
    }
}
</code></pre>

<p>Now I would like to unit testing this function. I am using Mockk : </p>

<pre><code>  @Test
  fun `signup() must be delegated to createUserWithEmailAndPassword()`() = runBlockingTest {

      val listener = slot&lt;OnCompleteListener&lt;AuthResult&gt;&gt;()
      val authentication = mockk&lt;Authentication&gt; {
        every { email } returns ""email""
        every { password } returns ""pswd""
      }
      val task = mockk&lt;Task&lt;AuthResult&gt;&gt; {
        every { isSuccessful } returns true
      }

      every { auth.createUserWithEmailAndPassword(""email"", ""pswd"") } returns
          mockk {
            every { addOnCompleteListener(activity, capture(listener)) } returns mockk()
          }

    service.signUp(authentication)

      listener.captured.onComplete(task)
    }
</code></pre>

<p>Unfortunately this test failed due to the following exception : <code>java.lang.IllegalStateException: This job has not completed yet</code> </p>

<p>I tried to replace <code>runBlockingTest</code> with <code>runBlocking</code> but the test seems to wait in an infinite loop.</p>

<p>Can someone help me with this UT please?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/61224047/unit-testing-coroutines-runblockingtest-this-job-has-not-completed-yet,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines', 'mockk']",33143,True,65,10
Using InstantTaskExecutorRule causes java.lang.RuntimeException in junit test,"<p>I am unit-testing a library that uses a <code>RoomDatabase</code>. Unit-testing the <code>RoomDatabase</code> itself was done using <code>InstantTaskExecutorRule</code> so that <code>LiveData</code> updates can occur instantaneously:</p>

<pre><code>@Rule public TestRule rule = new InstantTaskExecutorRule();
</code></pre>

<p>And that works fine. However, when unit-testing the library which calls the database, using the same rule causes the test to throw the exception:</p>

<pre><code>java.lang.RuntimeException: Exception while computing database live data.
...
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
</code></pre>

<p>Is there any reason why <code>InstantTaskExecutorRule</code> works on the underlying database DAOs but not a library calling them?</p>
",https://stackoverflow.com/questions/61784450/using-instanttaskexecutorrule-causes-java-lang-runtimeexception-in-junit-test,"['android', 'android-room', 'android-testing', 'android-livedata']",942,False,0,2
docker build with nvidia runtime,"<p>I have a GPU application that does unit-testing during the image building stage.
With Docker 19.03, one can specify nvidia runtime with <code>docker run --gpus all</code> but I also need access to the gpus for <code>docker build</code> because I do unit-testing. How can I achieve this goal?</p>

<p>For older version of docker that use nvidia-docker2 it was not possible to specifiy runtime during build stage, BUT you can set the default runtime to be nvidia, and docker build works fine that way. Can I do that in Docker 19.03 that doesn't need nvidia-docker anymore? If so, how?</p>
",https://stackoverflow.com/questions/59691207/docker-build-with-nvidia-runtime,"['docker', 'nvidia-docker']",23570,True,31,3
How to make interceptor Unit tesing,"<p>I am trying make interceptor unit testing using below code but i am getting exception please help me some one my code there in stackbliz</p>

<p><a href=""https://stackblitz.com/edit/angular-unit-testing-example-xnm226"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/angular-unit-testing-example-xnm226</a></p>

<h2>interceptor</h2>

<pre><code>import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

  constructor() { }

  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    return next.handle(request).pipe(catchError(err =&gt; {
      if (err.status === 401) {
      }
      const error = err.error.message || err.statusText;
      return throwError(error);
    }))
  }
}
</code></pre>

<h2>test</h2>

<pre><code>import { TestBed, inject, async } from ""@angular/core/testing"";
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HTTP_INTERCEPTORS, HttpClient, HttpHeaders, HttpRequest, HttpResponse, HttpClientModule, HttpErrorResponse, HttpHandler } from '@angular/common/http';
import { AutherizationInterceptor, InterceptorSkipHeader } from './authInterceptors';
import { ErrorInterceptor } from './errorInterceptors';
import { environment } from 'src/environments/environment';

describe('ErrorInterceptor', () =&gt; {
    let http: HttpTestingController;
    let httpClient: HttpClient;
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpClientModule, HttpClientTestingModule],
            providers: [{
                provide: HTTP_INTERCEPTORS,
                useClass: ErrorInterceptor,
                multi: true
            }]
        })
        http = TestBed.get(HttpTestingController);
        httpClient = TestBed.get(HttpClient);
    });

    it('Error interceptor test', () =&gt; {
        httpClient.get(environment.baseUrl + 'api/user/login').subscribe(
            response =&gt; {
                expect(response).toBeTruthy();
            }
        );
        http.expectOne(environment.baseUrl + 'api/user/login').error(new ErrorEvent('Unauthorized error'), {
            status: 401
        });
        http.verify();
    });
});
</code></pre>
",https://stackoverflow.com/questions/60089804/how-to-make-interceptor-unit-tesing,"['angular', 'karma-jasmine']",36,False,1,0
"Can not find module import { async, TestBed } from &#39;@angular/core/testing&#39;; import { IonicModule } from &#39;ionic-angular&#39;;","<p>Can not find module:</p>

<p><code>import { async, TestBed } from '@angular/core/testing';</code></p>

<p><code>import { IonicModule } from 'ionic-angular';</code></p>

<p>I am using ionic 3, wanted to do Unit testing on my application but facing problem in <code>spec.ts</code> file, which is unable to find modules.</p>

<p>I am using <strong>Karma</strong> and <strong>jasmine</strong> for unit testing</p>
",https://stackoverflow.com/questions/60149336/can-not-find-module-import-async-testbed-from-angular-core-testing-impo,"['angular', 'ionic3', 'karma-jasmine']",1118,True,1,1
Getting &quot;TypeError: cis.createLoader is not a function&quot; unit testing BsDatepickerDirective,"<p>The following is a piece of code of my unit testing.</p>
<pre><code>let BsDatepickerConfigStub = {};

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        ...
        providers: [
            { provide: BsDatepickerConfig, useValue: BsDatepickerConfigStub }
        ]
    }).compileComponents();
    fixture = TestBed.createComponent(GoalDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});
</code></pre>
<p>Whenever I run the test</p>
<pre><code>it('should create', () =&gt; {
    expect(component).toBeTruthy();
});
</code></pre>
<p>I get this error:</p>
<p>TypeError: cis.createLoader is not a function at new BsDatepickerDirective</p>
<p>What is right way to mock all Bootstrap items in unit testing?</p>
",https://stackoverflow.com/questions/62653137/getting-typeerror-cis-createloader-is-not-a-function-unit-testing-bsdatepicke,"['angular', 'typescript', 'unit-testing', 'angular-bootstrap']",76,False,1,0
How to Unit test Service &amp; controller (kotlin) in a Cordapp?,"<p>I have gone through many documentations for getting a sample of unit testing service and controller in a Cordapp, not the flows (that is already done using in corda docs). Can anyone please help me to get an example cordapp which implemented service unit testing?</p>
",https://stackoverflow.com/questions/63296264/how-to-unit-test-service-controller-kotlin-in-a-cordapp,"['spring-boot', 'unit-testing', 'kotlin', 'controller', 'corda']",296,True,1,2
how can i do unit testing for APIs?,"<p>i`am new to unit testing and i have this task to write unit testing for Post API i have only the end point and api body i read a lot in google but i could not figure out how to start , any help ?</p>
",https://stackoverflow.com/questions/60041169/how-can-i-do-unit-testing-for-apis,"['java', 'spring-boot', 'api', 'unit-testing', 'junit']",232,True,0,2
How to do the unit testing on stm32 programming,"<p>I have STM 32 nucleo board .I have done a program for an embedded functionality. Currently I want to do the unit testing for the functionalities including the peripherals like ADC,SPI,UART..Can anyone suggest the Unit testing framework to test the functionality for the same.</p>
",https://stackoverflow.com/questions/61136966/how-to-do-the-unit-testing-on-stm32-programming,['stm32'],6715,True,1,2
unit testing Embedded Source Code using GTEST / GMOCK,"<p>I am newbie to unit testing , I have basic doubt regarding unit testing , I have <strong>middle ware code</strong> which needs to be <strong>unit tested</strong> using <strong>gtest/gmock</strong> , My Middle ware Code talks with Stack code which come as library  .so and my stack library talks with Embedded Hardware ,  So below are few questions I have</p>
<p>(1) Does Unit Testing means , It should  done without Hardware ?, I mean writing stub code for stack since stack talks with H/w and test middle ware functionality on PC  , In that case developers has to know what events stack sends, when some operation is performed and mimic it in stub code</p>
<p><strong>or</strong></p>
<p>(2) Unit Testing means testing by writing test cases from middle ware code which will talk with stack and then to H/w and catch events from from H/W , then to stack and then to Application and , Assert on Events ,  to test whether test case is  case Pass/Fail</p>
<p>Below is diagram , I intend to unit testing to middle ware code using gtest , My Middle ware is application and stack is .so</p>
<p><a href=""https://i.stack.imgur.com/n1jqj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/n1jqj.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63371203/unit-testing-embedded-source-code-using-gtest-gmock,"['unit-testing', 'embedded', 'googletest']",649,True,0,2
how to generate a jwt token for rest controller unit testing?,"<p>I am working on the unit testing for securied restful endpoints. To test it, I need to add the 'Authorization' token in the header. </p>

<p>How can I generate a token for each mockMvc http call? An easier way I can come up with is to call ""api/authentication"" everytime before each test functions. Then the unit testing will depend on ""api/authentication"".</p>

<p>Currently, I am using <code>@WebMvcTest(restController.class)</code>. Then it only loads the restController, and ""api/authentication"" won't be available. </p>

<p>How should I handle unit testing for JWT securied rest APIs? </p>
",https://stackoverflow.com/questions/60085101/how-to-generate-a-jwt-token-for-rest-controller-unit-testing,"['rest', 'spring-boot', 'unit-testing', 'mockito', 'jwt']",2541,True,0,2
Test with component has been rendered,"<p>I am using Jest with Enzyme for unit testing. I have a component that renders components based on the media type. Under unit testing, I am checking if the appropriate component has been rendered.  </p>

<p>My 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>const getComponent = {
 'image': ImageComp,
 'video': VideoComp,
 'other': DocumentComp
}

const MediaDisplay =  (props) =&gt;  {
    let { assetInfo } = props;
    let source = assetInfo.assetUrl;
    const PreviewComponent = getComponent[assetInfo.type];
    return ( &lt;div&gt;
        {source &amp;&amp; &lt;PreviewComponent assetInfo={assetInfo} /&gt;}
        &lt;/div&gt;
    );
}</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>  </code></pre>
</div>
</div>
</p>

<p>In unit testing,</p>

<pre><code>import React from 'react';
import MediaDisplay from './../MediaDisplay';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });

describe('&lt;MediaDisplay/&gt;', () =&gt; {
  it('should render Image component when asset type is image', () =&gt; {
    const mockAssetInfo = {
        assetUrl:'https://example.com/image001.jpg',
        type:'image'

    };
    const component = mount(&lt;MediaDisplay assetInfo={mockAssetInfo} /&gt;);
    expect(component).toMatchSnapshot();
  });
});
</code></pre>

<p>I don't think I am writing the test case correctly. Can someone help me write this test case? </p>

<p>P.S - I have a separate test case inside the image component to check if image is rendered, where I am checking if the  tag has length.</p>

<p>Thanks a ton in advance.</p>
",https://stackoverflow.com/questions/61068693/test-with-component-has-been-rendered,"['reactjs', 'jestjs', 'enzyme']",191,False,0,1
"AssertionError: expected { Object (driver, name, ...) } to have property &#39;_id&#39;","<p>I am new to unit testing using Mocha and Chai. I am trying to implement the unit testing on a REST-API which is written using Node.js and MongoDB. I have tried one tutorial but I'm getting <code>AssertionError: expected { Object (driver, name, ...) } to have property '_id'</code> when I run <code>npm test</code>. Mainly it should enter the data into MongoDB. </p>

<p>app.js</p>

<pre><code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const Note = require('./db/models/note.js').Note;

app.use(bodyParser.json());

app.get('/notes', (req, res) =&gt; {
  Note.find()
    .then((notes) =&gt; res.status(200).send(notes))
    .catch((err) =&gt; res.status(400).send(err));
});

app.post('/notes', (req, res) =&gt; {
  const body = req.body;
  const note = new Note({
    name: body.name,
    text: body.text
  });
  note.save(note)
    .then((note) =&gt; res.status(201).send(note))
    .catch((err) =&gt; res.status(400).send(err));
});

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

<p>test.js</p>

<pre><code>process.env.NODE_ENV = 'test';

const expect = require('chai').expect;
const request = require('supertest');

const app = require('../../../app.js');
const conn = require('../../../db/index.js');

describe('POST /notes', () =&gt; {
  before((done) =&gt; {
    conn.connect()
      .then(() =&gt; done())
      .catch((err) =&gt; done(err));
  })

  after((done) =&gt; {
    conn.close()
      .then(() =&gt; done())
      .catch((err) =&gt; done(err));
  })

  it('OK, creating a new note works', (done) =&gt; {
    request(app).post('/notes')
      .send({ name: 'NOTE Name', text: ""AAA"" })
      .then((res) =&gt; {
        const body = res.body;
        expect(body).to.contain.property('_id');
        expect(body).to.contain.property('name');
        expect(body).to.contain.property('text');
        done();
      })
      .catch((err) =&gt; done(err));
  })

  it('Fail, note requires text', (done) =&gt; {
    request(app).post('/notes')
      .send({ name: 'NOTE' })
      .then((res) =&gt; {
        const body = res.body;
        expect(body.errors.text.name)
          .to.equal('ValidatorError')
        done();
      })
      .catch((err) =&gt; done(err));
  });
})
</code></pre>
",https://stackoverflow.com/questions/59992761/assertionerror-expected-object-driver-name-to-have-property-id,"['javascript', 'node.js', 'mocha.js', 'chai']",5754,True,2,1
Crash while performing fetch request -[NSTemporaryObjectID_default compare:]: unrecognized selector sent to instance,"<p>I am facing a strange issue. While unit testing Core data code, it crashes at (try fetchController.performFetch()). Unit test passes when run individually, but it fails when run in batches. I am using inMemory store type for unit testing. Any help please?</p>

<pre><code>   let fetchRequest = T.fetchRequest()
   fetchRequest.sortDescriptors = [NSSortDescriptor(key: ""objectID"", ascending: false)]
   let fetchController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                    managedObjectContext: self,
                                                    sectionNameKeyPath: nil,
                                                    cacheName: nil)

    self.performAndWait {
        do {
            try fetchController.performFetch()
        } catch (let exception) {
            error = exception
        }
    }
</code></pre>

<p>The error message is:</p>

<pre><code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSTemporaryObjectID_default compare:]: unrecognized selector sent to instance 0x7b0800086e40'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000011632a29b __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x000000011531d735 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000116348fa4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x000000011632efb6 ___forwarding___ + 1446
    4   CoreFoundation                      0x0000000116330e88 _CF_forwarding_prep_0 + 120
    5   Foundation                          0x0000000114da9bd0 _NSCompareObject + 46
    6   CoreFoundation                      0x000000011629b39b __CFSimpleMergeSort + 75
    7   CoreFoundation                      0x000000011629adf8 CFSortIndexes + 808
    8   CoreFoundation                      0x000000011629be0e CFMergeSortArray + 334
    9   Foundation                          0x0000000114daa2dd _sortedObjectsUsingDescriptors + 615
    10  Foundation                          0x0000000114daa5b7 -[NSArray(NSKeyValueSorting) sortedArrayUsingDescriptors:] + 531
    11  CoreData                            0x0000000115c71baa -[NSManagedObjectContext executeFetchRequest:error:] + 4746
    12  CoreData                            0x0000000115e27372 __43-[NSFetchedResultsController performFetch:]_block_invoke + 450
    13  CoreData                            0x0000000115d913f9 gutsOfBlockToNSPersistentStoreCoordinatorPerform + 201
    14  libclang_rt.tsan_iossim_dynamic.dylib 0x00000001115855f2 _ZN6__tsanL22dispatch_callback_wrapEPv + 306
    15  libdispatch.dylib                   0x0000000118d2e587 _dispatch_client_callout + 8
    16  libdispatch.dylib                   0x0000000118d3af87 _dispatch_lane_barrier_sync_invoke_and_complete + 94
    17  libclang_rt.tsan_iossim_dynamic.dylib 0x0000000111585980 wrap_dispatch_sync_f + 208
    18  CoreData                            0x0000000115d7b8f6 -[NSPersistentStoreCoordinator performBlockAndWait:] + 198
    19  CoreData                            0x0000000115cb42d1 developerSubmittedBlockToNSManagedObjectContextPerform + 161
    20  CoreData                            0x0000000115cb41af -[NSManagedObjectContext performBlockAndWait:] + 239
    21  CoreData                            0x0000000115e27751 -[NSFetchedResultsController _recursivePerformBlockAndWait:withContext:] + 145
    22  CoreData                            0x0000000115cb42d1 developerSubmittedBlockToNSManagedObjectContextPerform + 161
    23  CoreData                            0x0000000115cb41af -[NSManagedObjectContext performBlockAndWait:] + 239
    24  CoreData                            0x0000000115e27751 -[NSFetchedResultsController _recursivePerformBlockAndWait:withContext:] + 145
    25  CoreData                            0x0000000115e270db -[NSFetchedResultsController performFetch:] + 299
    26  C4M                                 0x000000010f6c5482 $sSo22NSManagedObjectContextC10RxCoreDataE16performSyncFetchySo26NSFetchedResultsControllerCySo20NSFetchRequestResult_pG_s5Error_pSgtxmSo0aB0CRbzlFyyXEfU_ + 194
    27  C4M                                 0x000000010f6c59cc $sSo22NSManagedObjectContextC10RxCoreDataE16performSyncFetchySo26NSFetchedResultsControllerCySo20NSFetchRequestResult_pG_s5Error_pSgtxmSo0aB0CRbzlFyyXEfU_TA + 44
    28  C4M                                 0x000000010f6c5ae8 $sIg_Ieg_TR + 40
    29  C4M                                 0x000000010f6c5b7c $sIg_Ieg_TRTA + 44
    30  C4M                                 0x000000010f6c5c00 $sIeg_IyB_TR + 80
    31  CoreData                            0x0000000115cb42d1 developerSubmittedBlockToNSManagedObjectContextPerform + 161
    32  libclang_rt.tsan_iossim_dynamic.dylib 0x00000001115855f2 _ZN6__tsanL22dispatch_callback_wrapEPv + 306
    33  libdispatch.dylib                   0x0000000118d2e587 _dispatch_client_callout + 8
    34  libdispatch.dylib                   0x0000000118d3af87 _dispatch_lane_barrier_sync_invoke_and_complete + 94
    35  libclang_rt.tsan_iossim_dynamic.dylib 0x0000000111585980 wrap_dispatch_sync_f + 208
    36  CoreData                            0x0000000115cb41de -[NSManagedObjectContext performBlockAndWait:] + 286
    37  C4M                                 0x000000010f6c5079 $sSo22NSManagedObjectContextC10RxCoreDataE16performSyncFetchySo26NSFetchedResultsControllerCySo20NSFetchRequestResult_pG_s5Error_pSgtxmSo0aB0CRbzlF + 1193
    38  C4M                                 0x000000010f6c48af $sSo22NSManagedObjectContextC10RxCoreData0d7ManagedbC0A2cDP16performSyncFetchySo26NSFetchedResultsControllerCySo20NSFetchRequestResult_pG_s5Error_pSgtqd__mSo0aB0CRbd__lFTW + 63
    39  C4M                                 0x000000010f6b7f4c $s10RxCoreData0C5StackC7objectsyAA07ResultsC0CyxGxmKSo15NSManagedObjectCRbzlF + 348
    40  C4M                                 0x000000010f6b7d3a $s10RxCoreData0C5StackCAA0cD8ProtocolA2aDP7objectsyAA07ResultsC0Cyqd__Gqd__mKSo15NSManagedObjectCRbd__lFTW + 74
    41  C4M                                 0x000000010ed8b4a0 $s3C4M10NetworkDAOC16fetchAllNetworks9projectId10onCompleteySS_ySayAA0B0CG_s5Error_pSgtctFy10RxCoreData0N13StackProtocol_pSgcfU_ + 1088
    42  C4M                                 0x000000010ed8baf9 $s3C4M10NetworkDAOC16fetchAllNetworks9projectId10onCompleteySS_ySayAA0B0CG_s5Error_pSgtctFy10RxCoreData0N13StackProtocol_pSgcfU_TA + 57
    43  C4MTests                            0x0000000131672acc $s8C4MTests14MockNetworkDAOC13loadDataStack9modelName9storeType6bundle6onLoadySS_06RxCoreG005StoreL0OSo8NSBundleCyAI0gH8Protocol_pSgctFyAO_s5Error_pSgtcfU_ + 204
    44  C4MTests                            0x0000000131672b89 $s8C4MTests14MockNetworkDAOC13loadDataStack9modelName9storeType6bundle6onLoadySS_06RxCoreG005StoreL0OSo8NSBundleCyAI0gH8Protocol_pSgctFyAO_s5Error_pSgtcfU_TA + 57
    45  C4M                                 0x000000010eff58b9 $s3C4M16DataStackManagerC9modelName4type6bundle10onCompleteACSS_06RxCoreB09StoreTypeOSo8NSBundleCyAH0bC8Protocol_pSg_s5Error_pSgtctcfc + 1753
    46  C4M                                 0x000000010eff51a5 $s3C4M16DataStackManagerC9modelName4type6bundle10onCompleteACSS_06RxCoreB09StoreTypeOSo8NSBundleCyAH0bC8Protocol_pSg_s5Error_pSgtctcfC + 117
    47  C4MTests                            0x00000001316727ac $s8C4MTests14MockNetworkDAOC13loadDataStack9modelName9storeType6bundle6onLoadySS_06RxCoreG005StoreL0OSo8NSBundleCyAI0gH8Protocol_pSgctF + 940
    48  C4M                                 0x000000010e9afe4a $s3C4M16DataAccessObjectCAA0bcD8ProtocolA2aDP04loadB5Stack9modelName9storeType6bundle6onLoadySS_06RxCoreB005StoreK0OSo8NSBundleCyAK0bgE0_pSgctFTW + 154
    49  C4M                                 0x000000010e9aef1f $s3C4M24DataAccessObjectProtocolPAAE04loadB5Stack9modelName9storeType6bundle6onLoadySS_06RxCoreB005StoreK0OSo8NSBundleCyAI0bgE0_pSgctF + 463
    50  C4M                                 0x000000010ed8affd $s3C4M10NetworkDAOC16fetchAllNetworks9projectId10onCompleteySS_ySayAA0B0CG_s5Error_pSgtctF + 605
    51  C4MTests                            0x00000001318d2eca $s8C4MTests14NetworkDOTestsC011testZCreateC8_SuccessyyFy0A1M0C0CSg_AE0C11AccessErrorOSgtcfU_ + 1098
    52  C4MTests                            0x00000001318d2fb9 $s8C4MTests14NetworkDOTestsC011testZCreateC8_SuccessyyFy0A1M0C0CSg_AE0C11AccessErrorOSgtcfU_TA + 57
    53  C4M                                 0x000000010ed89913 $s3C4M10NetworkDAOC6create4name9projectId10onCompleteySS_SSyAA0B0CSg_AA0B11AccessErrorOSgtctFy10RxCoreData0N13StackProtocol_pSgcfU_yyXEfU_ + 1075
    54  C4M                                 0x000000010ed899a6 $s3C4M10NetworkDAOC6create4name9projectId10onCompleteySS_SSyAA0B0CSg_AA0B11AccessErrorOSgtctFy10RxCoreData0N13StackProtocol_pSgcfU_yyXEfU_TA + 70
    55  C4M                                 0x000000010f6b762f $s10RxCoreData0C5StackC5write_13notifyOnWriteyyyXE_SbtKF + 271
    56  C4M                                 0x000000010f6b7492 $s10RxCoreData0C5StackCAA0cD8ProtocolA2aDP5write_13notifyOnWriteyyyXE_SbtKFTW + 82
    57  C4M                                 0x000000010f6b512b $s10RxCoreData0C13StackProtocolPAAE5write_13notifyOnWriteyyyXE_SbtKF + 283
    58  C4M                                 0x000000010ed89047 $s3C4M10NetworkDAOC6create4name9projectId10onCompleteySS_SSyAA0B0CSg_AA0B11AccessErrorOSgtctFy10RxCoreData0N13StackProtocol_pSgcfU_ + 1191
    59  C4M                                 0x000000010ed8937a $s3C4M10NetworkDAOC6create4name9projectId10onCompleteySS_SSyAA0B0CSg_AA0B11AccessErrorOSgtctFy10RxCoreData0N13StackProtocol_pSgcfU_TA + 74
    60  C4MTests                            0x0000000131672acc $s8C4MTests14MockNetworkDAOC13loadDataStack9modelName9storeType6bundle6onLoadySS_06RxCoreG005StoreL0OSo8NSBundleCyAI0gH8Protocol_pSgctFyAO_s5Error_pSgtcfU_ + 204
    61  C4MTests                            0x0000000131672b89 $s8C4MTests14MockNetworkDAOC13loadDataStack9modelName9storeType6bundle6onLoadySS_06RxCoreG005StoreL0OSo8NSBundleCyAI0gH8Protocol_pSgctFyAO_s5Error_pSgtcfU_TA + 57
    62  C4M                                 0x000000010eff58b9 $s3C4M16DataStackManagerC9modelName4type6bundle10onCompleteACSS_06RxCoreB09StoreTypeOSo8NSBundleCyAH0bC8Protocol_pSg_s5Error_pSgtctcfc + 1753
    63  C4M                                 0x000000010eff51a5 $s3C4M16DataStackManagerC9modelName4type6bundle10onCompleteACSS_06RxCoreB09StoreTypeOSo8NSBundleCyAH0bC8Protocol_pSg_s5Error_pSgtctcfC + 117
    64  C4MTests                            0x00000001316727ac $s8C4MTests14MockNetworkDAOC13loadDataStack9modelName9storeType6bundle6onLoadySS_06RxCoreG005StoreL0OSo8NSBundleCyAI0gH8Protocol_pSgctF + 940
    65  C4M                                 0x000000010e9afe4a $s3C4M16DataAccessObjectCAA0bcD8ProtocolA2aDP04loadB5Stack9modelName9storeType6bundle6onLoadySS_06RxCoreB005StoreK0OSo8NSBundleCyAK0bgE0_pSgctFTW + 154
    66  C4M                                 0x000000010e9aef1f $s3C4M24DataAccessObjectProtocolPAAE04loadB5Stack9modelName9storeType6bundle6onLoadySS_06RxCoreB005StoreK0OSo8NSBundleCyAI0bgE0_pSgctF + 463
    67  C4M                                 0x000000010ed88b43 $s3C4M10NetworkDAOC6create4name9projectId10onCompleteySS_SSyAA0B0CSg_AA0B11AccessErrorOSgtctF + 755
    68  C4MTests                            0x00000001318d28de $s8C4MTests14NetworkDOTestsC011testZCreateC8_SuccessyyF + 830
    69  C4MTests                            0x00000001318d3e95 $s8C4MTests14NetworkDOTestsC011testZCreateC8_SuccessyyFTo + 85
    70  CoreFoundation                      0x000000011633111c __invoking___ + 140
    71  CoreFoundation                      0x000000011632e5b5 -[NSInvocation invoke] + 325
    72  XCTest                              0x000000012de4a821 __24-[XCTestCase invokeTest]_block_invoke.208 + 78
    73  XCTest                              0x000000012dea49b9 -[XCTestCase(Failures) performFailableBlock:testCaseRun:shouldInterruptTest:] + 57
    74  XCTest                              0x000000012dea48d7 -[XCTestCase(Failures) _performTurningExceptionsIntoFailuresInterruptAfterHandling:block:] + 96
    75  XCTest                              0x000000012de4a30a __24-[XCTestCase invokeTest]_block_invoke + 1153
    76  XCTest                              0x000000012de49de2 -[XCTestCase testContextPerformInScope:] + 211
    77  XCTest                              0x000000012de49e7c -[XCTestCase invokeTest] + 137
    78  XCTest                              0x000000012de4bbed __26-[XCTestCase performTest:]_block_invoke_2 + 43
    79  XCTest                              0x000000012dea49b9 -[XCTestCase(Failures) performFailableBlock:testCaseRun:shouldInterruptTest:] + 57
    80  XCTest                              0x000000012dea48d7 -[XCTestCase(Failures) _performTurningExceptionsIntoFailuresInterruptAfterHandling:block:] + 96
    81  XCTest                              0x000000012de4bb04 __26-[XCTestCase performTest:]_block_invoke.334 + 88
    82  XCTest                              0x000000012deb8302 +[XCTContext runInContextForTestCase:block:] + 219
    83  XCTest                              0x000000012de4b273 -[XCTestCase performTest:] + 668
    84  XCTest                              0x000000012de90807 -[XCTest runTest] + 57
    85  XCTest                              0x000000012de4584a __27-[XCTestSuite performTest:]_block_invoke + 365
    86  XCTest                              0x000000012de44f74 -[XCTestSuite _performProtectedSectionForTest:testSection:] + 54
    87  XCTest                              0x000000012de45271 -[XCTestSuite performTest:] + 355
    88  XCTest                              0x000000012de90807 -[XCTest runTest] + 57
    89  XCTest                              0x000000012de4584a __27-[XCTestSuite performTest:]_block_invoke + 365
    90  XCTest                              0x000000012de44f74 -[XCTestSuite _performProtectedSectionForTest:testSection:] + 54
    91  XCTest                              0x000000012de45271 -[XCTestSuite performTest:] + 355
    92  XCTest                              0x000000012de90807 -[XCTest runTest] + 57
    93  XCTest                              0x000000012de4584a __27-[XCTestSuite performTest:]_block_invoke + 365
    94  XCTest                              0x000000012de44f74 -[XCTestSuite _performProtectedSectionForTest:testSection:] + 54
    95  XCTest                              0x000000012de45271 -[XCTestSuite performTest:] + 355
    96  XCTest                              0x000000012de90807 -[XCTest runTest] + 57
    97  XCTest                              0x000000012dec728e __44-[XCTTestRunSession runTestsAndReturnError:]_block_invoke + 171
    98  XCTest                              0x000000012dec7391 __44-[XCTTestRunSession runTestsAndReturnError:]_block_invoke.84 + 118
    99  XCTest                              0x000000012de5f593 -[XCTestObservationCenter _observeTestExecutionForBlock:] + 588
    100 XCTest                              0x000000012dec704d -[XCTTestRunSession runTestsAndReturnError:] + 623
    101 XCTest                              0x000000012de28dd7 -[XCTestDriver runTestsAndReturnError:] + 456
    102 XCTest                              0x000000012deb4554 _XCTestMain + 2484
    103 libXCTestBundleInject.dylib         0x00000001123f3be7 __copy_helper_block_e8_32s + 0
    104 CoreFoundation                      0x000000011628da3c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    105 CoreFoundation                      0x000000011628d1f0 __CFRunLoopDoBlocks + 336
    106 CoreFoundation                      0x0000000116287a64 __CFRunLoopRun + 1284
    107 CoreFoundation                      0x0000000116287221 CFRunLoopRunSpecific + 625
    108 GraphicsServices                    0x000000011b8df1dd GSEventRunModal + 62
    109 UIKitCore                           0x000000011ec9e115 UIApplicationMain + 140
    110 C4M                                 0x000000010eddf473 main + 99
    111 libdyld.dylib                       0x0000000118d9e551 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code></pre>
",https://stackoverflow.com/questions/62197157/crash-while-performing-fetch-request-nstemporaryobjectid-default-compare-un,"['ios', 'swift', 'core-data']",90,False,0,0
routerLinkActive not working in unit testing,"<p>RouterLinkActive is not working during unit testing but It works when outside unit testing.</p>

<p>Here is HTML:</p>

<pre><code>&lt;header class=""site-tab""&gt;
  &lt;nav class=""c-tab l-wrap""&gt;
    &lt;div
      class=""c-tab__item""
      routerLink=""/companies""
      routerLinkActive=""c-tab__item--active""
    &gt;
      &lt;p class=""c-tab__text""&gt;Companies&lt;/p&gt;
    &lt;/div&gt;
    &lt;div
      class=""c-tab__item""
      routerLink=""/products""
      routerLinkActive=""c-tab__item--active""
    &gt;
      &lt;p class=""c-tab__text""&gt;Products&lt;/p&gt;
    &lt;/div&gt;
    &lt;div
      class=""c-tab__item""
      routerLink=""/invoices""
      routerLinkActive=""c-tab__item--active""
    &gt;
      &lt;p class=""c-tab__text""&gt;Invoices&lt;/p&gt;
    &lt;/div&gt;
  &lt;/nav&gt;
&lt;/header&gt;

</code></pre>

<p>and here is my spec file:</p>

<pre><code>import { ComponentFixture, TestBed, async } from '@angular/core/testing';

import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { TabsComponent } from './tabs.component';

describe('TabsComponent', () =&gt; {
  let component: TabsComponent;
  let fixture: ComponentFixture&lt;TabsComponent&gt;;
  let de: DebugElement;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [TabsComponent],
      imports: [RouterTestingModule]
    }).compileComponents();
  }));

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

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

  it('should set clicked tab to active', () =&gt; {
    de.queryAll(By.css('.c-tab__item'))[1].nativeElement.click();
    expect(
      de.query(By.css('.c-tab__item--active .c-tab__text')).nativeElement
        .innerHTML
    ).toContain('Product');
  });
</code></pre>

<p>I expect the tab to be active once I click on it but I am getting this error
<code>TypeError: de.query(...) is null in http://localhost:9876/_karma_webpack_/main.js (line 872)</code> which I believe means that no tab was set to active.</p>
",https://stackoverflow.com/questions/60953499/routerlinkactive-not-working-in-unit-testing,"['angular', 'jasmine', 'karma-jasmine']",821,True,0,2
Getting NullPointerException performing unit-testing with Mockito,"<p><br/>
Please don't mark it as duplicate, I am unable to fix this issue.
<br/><br/>
I am writing unit testing using <em>Mockito</em>. While executing the test case, I am getting <code>NullPointerException</code> on the <code>@Autowired bean</code> of <code>MainTemplate class</code>.</p>

<p>Code:</p>

<pre><code>public abstract class Template{

  abstract public boolean isEven(String input);

  private String getName(String initial){
    return ""INIT""+initial;
  }

  final public void run(String input){
   isEven(input);
   getName(input);

  }
}
</code></pre>

<p><br/>
Implementation of Template:
<br/></p>

<pre><code>public class MainTemplate extends Template{

 @Autowired
 private UserUtil userUtil;

    @Override
    public boolean isEven(String input){
      return userUtil.getResult(input);  //GETTING NullPointerException here..
    }
}
</code></pre>

<p><br/>
Bean configuration:</p>

<pre><code>@Configuration
public class BeanConfiguration{
  @Bean
  public Template getBean(){
     return new MainTemplate();
  }
}

@Service
public class Executor{
 @Autowired
 private BeanConfiguration beanConfig;

 public void execute(){
   beanConfig.getBean().run(""sample input"");
 }

}
</code></pre>

<p>Unit testing class:
<br/></p>

<pre><code>@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MainTemplateTest{

  @InjectMocks
  private MainTemplate mainTemplate;

  @Mock
  private UserUtil userUtil;

  @Test
  public void isEvenTest(){

    Mockito.when(userUtil.getResult(anyString())).thenReturn(true);

    mainTemplate.isEven(""input string"");
  }
}
</code></pre>

<p><br/>
I am getting NullPointerException while running the above test.<br/>
Getting NullPointerException on:
<br/></p>

<pre><code>    @Override
    public boolean isEven(String input){
      return userUtil.getResult(input);  //GETTING NullPointerException, while calling from mock method
    }
</code></pre>
",https://stackoverflow.com/questions/61323907/getting-nullpointerexception-performing-unit-testing-with-mockito,"['java', 'unit-testing', 'mockito']",330,True,0,1
Why my API mock patch is not working on Python?,"<p>I'm a newbie to unit testing and mock. I have one script <code>get_table.py</code> and a function in it</p>
<pre><code>def get_table_name(id):
    url = &quot;https://some_api&quot; + id
    table = requests.get(url)
    return table
 
</code></pre>
<p>then I created a unit testing script as follows:</p>
<pre><code>from get_table import get_table_name
from unittest.mock import patch 

class TestFetchTable(unittest.TestCase):
    @patch('get_table.get_table_name')
    def test_get_table_name(self,mock):
        mock.return_value = 'table_1'
        result = get_table_name('id1')
        self.assertEquals(result, 'table_1')

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

</code></pre>
<p>The unit test is passed here but the test still ran over the actual API not the mocked API. May I know that I did wrong here?</p>
",https://stackoverflow.com/questions/63306217/why-my-api-mock-patch-is-not-working-on-python,"['python', 'api', 'unit-testing', 'patch']",279,False,0,1
How to switch between different types of R in unit testing,"<p>I want to create unit testing for different versions of R e.g. 3.6.3, 4.0 etc. I know that I can install older versions of R and try unit testing for each of them, but is there any possibility how can I do it in easier way ? For example artificially provide other R versions and loop them ?</p>
",https://stackoverflow.com/questions/64928848/how-to-switch-between-different-types-of-r-in-unit-testing,"['r', 'unit-testing', 'version']",23,False,1,0
How to check multiply results in unit testing Swift?,"<p>I am doing unit testing for a program. I have a func:</p>

<pre><code> static func make(for lesson: TrainingProgram.Lesson,
                     in program: TrainingProgram,
                     results: [String: TrickResults]) -&gt; [TrickContent]
</code></pre>

<p>In unit testing I written this:</p>

<pre><code>let session = TrainingSessionFactory.make(for: lesson,
                                                  in: program,
                                                  results: [trainedTrickId: result])
</code></pre>

<p>And I want to test in results: <code>[trainedTrickId: result]</code> and like <code>[trainedTrickId: resultsTwo]</code>, <code>[trainedTrickId: resultsThree]</code></p>

<p>But want to shorten my test code so don't want to make another session for different results. How do I do that?</p>

<p>result, resultsTwo, resultsThree have different values:</p>

<pre><code>let result = TrickResults(id: trainedTrickId,
                                  knowledge: 4,
                                  points: 0,
                                  lastTrainedOn: 0,
                                  lastRatedOn: 0)
</code></pre>
",https://stackoverflow.com/questions/59863013/how-to-check-multiply-results-in-unit-testing-swift,"['swift', 'unit-testing']",73,True,0,1
Pytest in AWS lambda,"<p>Is there any way we can perform unit testing on functions in an AWS lambda function using pytest?</p>
<p>Suppose I have a lambda function like the following:</p>
<pre><code>def func1(x,y):
   return x+y

def func2(x,y):
   return x-y

def handler(event,context):
   x = event[&quot;x&quot;]
   y = event[&quot;y&quot;]
   
   def func3(x,y):
      return x*y

   print(func1(x,y))
   print(func2(x,y))
   print(func3(x,y))
</code></pre>
<p>Pardon extra simplicity of the functions. I would like to do unit testing using <strong>pytest</strong> on these functions <code>func1</code>, <code>func2</code> and <code>func3</code>.</p>
<p>Is there any way I can do it in AWS lambda?</p>
",https://stackoverflow.com/questions/63410795/pytest-in-aws-lambda,"['python', 'amazon-web-services', 'unit-testing', 'aws-lambda', 'pytest']",3868,True,1,1
Javascript unit testing in Jasmin framework,"<p>I am new in JavaScript and unit testing. I have the following binary search code and I wanted to see if I can create some simple unit test cases for it in the Jasmine unit testing framework. However, for some reason my unit test is not working. 
&lt;</p>

<pre><code>script&gt; 
let Searching = function (array, x, start, end) { 

    // Base Condition 
    if (start &gt; end) return false; 

    // Find the middle index 
    let mid=Math.floor((start + end)/2); 

    // Compare mid with given key x 
    if (array[mid]===x) return true; 

    // If element at mid is greater than x, 
    // search in the left half of mid 
    if(array[mid] &gt; x) 
        return Searching(array, x, start, mid-1); 
    else

        // If element at mid is smaller than x, 
        // search in the right half of mid 
        return Searching(array, x, mid+1, end); 
} 

// Driver code 
let array = [1, 3, 5, 7, 8, 9]; 
let x = 5; 

if (Searching(array, x, 0, array.length-1)) 
    document.write(""Element found!&lt;br&gt;""); 
else document.write(""Element not found!&lt;br&gt;""); 

x = 6; 

if (Searching(array, x, 0, array.length-1)) 
    document.write(""Element found!&lt;br&gt;""); 
else document.write(""Element not found!&lt;br&gt;""); 
&lt;/script&gt;                                    

//unit testing

Describe ('Search Binary Algorithm', function () {
    var search = new Searching();
  it('should search in binary', function(){
      console.log (search ());
       expect(search (x).toEqual(5));
   });

});
</code></pre>

<p>When I run this one syntax error unexpected identifier. </p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/62378682/javascript-unit-testing-in-jasmin-framework,"['javascript', 'unit-testing']",26,False,0,0
How to mock file open and write with multiple write operation python2,"<p>How do I mock and test this code by unit testing?</p>

<pre><code>with open(filename, a) as f:
   f.write('test')
   f.write('\n')
</code></pre>
",https://stackoverflow.com/questions/59907039/how-to-mock-file-open-and-write-with-multiple-write-operation-python2,"['python-2.7', 'python-3.7']",31,False,1,0
How to perform Unit testing on PySpark Structured Streaming?,"<p>I'm using PySpark Structured Streaming with Kafka as a reader stream. For the sake of unit testing, I would like to replace Kafka reader stream with a mock. How can I do this?</p>
<p>The following question is equivalent to mine but I use Python (PySpark) instead of Scala. And I couldn't find MemoryStream in PySpark.</p>
<p><a href=""https://stackoverflow.com/questions/56894068/how-to-perform-unit-testing-on-spark-structured-streaming"">How to perform Unit testing on Spark Structured Streaming?</a></p>
",https://stackoverflow.com/questions/62981805/how-to-perform-unit-testing-on-pyspark-structured-streaming,"['pyspark', 'spark-streaming']",1358,False,3,0
using koin-test and mocking object tools,"<p>I am new to unit testing in android. My project is with MVVM and I use Koin as dependency injection/service locater tool.
I started to use koin-test for unit testing, my question is do I still need to use mocking object tools like mockito, mockK..etc? As far as I understand it is no but I need confirmation.</p>
",https://stackoverflow.com/questions/61332719/using-koin-test-and-mocking-object-tools,"['android', 'unit-testing', 'mocking', 'koin']",287,False,1,0
How to test a function that calls an API using Jest?,"<p>I am new to Node.js unit testing with Jest and still learning. I was wondering what is the proper way of unit testing a function that calls an API? Currently I am using cross-fetch library for API calls. I would like to achieve the unit test for payload validation, 2xx and 5xx API response on API calls.</p>
<p>Here's my code:</p>
<pre><code>export const myFunction = (payload: any) =&gt; {
  if (_.isNull(payload) || _.isUndefined(payload)) {
    throw new Error('payload is required')
  }

  httpFetch('http://localhost/api/send', { method: 'POST' }, { 'content-type': 'application/json', Authorization: 'Bearer 12ABC'})
    .then((resp) =&gt; {
      // ...return 2xx
    })
    .catch((e) =&gt; {
       // ...return 5xx
    })
}
</code></pre>
",https://stackoverflow.com/questions/64736674/how-to-test-a-function-that-calls-an-api-using-jest,"['node.js', 'unit-testing', 'jestjs']",4289,True,0,2
How to Mock BlobContainerClient() of Azure.Storage.Blobs?,"<p>I need some example of creating Mock object for BlobContainerClient of Azure.Storage.Blobs for unit testing. How can I create Mock for following class?</p>
<pre><code> public sealed class BlobStorageProcessor
    {
        public BlobStorageProcessor(ILogger logger, BlobContainerClient containerClient)
        {
            this.logger = logger;
            this.containerClient = containerClient;
        }
    }
</code></pre>
",https://stackoverflow.com/questions/64385008/how-to-mock-blobcontainerclient-of-azure-storage-blobs,"['c#', 'azure', 'mocking', 'azure-blob-storage']",17586,True,12,1
"What Is A Unit Testing Framework, And How Can I Use It In Java","<p>I see a lot of new programmers, specifically in Java, who do there tests something like this:</p>

<pre><code>System.out.println(myMethod(someValue));
System.out.println(expectedValue == myMethod(someValue));
</code></pre>

<p>However, there is something called a Unit Testing Framework, that will help test your code. So, what is a unit testing framework, and why do I want to use it to help ease my testing? And how can I use it in Java?</p>
",https://stackoverflow.com/questions/61763864/what-is-a-unit-testing-framework-and-how-can-i-use-it-in-java,"['java', 'testing', 'junit']",42,True,-1,1
thenReturn a data class in using mockito with kotlin,"<p>I want to create a unit testing by using mockito in my viewmodel code but i dont know how to use mockito <code>thenReturn</code> for a single data class contained some information . can somebody help me, please.</p>

<p>here is my viewModel class code which I created :</p>

<pre><code>open class DetailViewModel : ViewModel() {

    var dataCollection:SendDetail  = SendDetail("""",0,"""","""","""","""")

    fun getData(data:SendDetail){
        dataCollection.title=data.title
        dataCollection.picture=data.picture
        dataCollection.category= ""Category : "" + data.category
        dataCollection.genre= ""Genre : \n"" + data.genre
        dataCollection.release= ""Release : \n"" + data.release
        dataCollection.description= ""Description : \n"" + data.description
    }
}
</code></pre>

<p>and here are my unit testing code for code above :</p>

<pre><code>class DetailViewModelTest {

    private lateinit var viewModel: DetailViewModel
    private var sendDetail= SendDetail("""",0,"""","""","""","""")
    private val sampleDetail:MovieData = MovieDataObject.listData[1]

    private var dummyDetail= SendDetail(""Doctor Who"",
        2131165337,
        ""Category : "" +""Tv Series"",
        ""Genre : \n"" +""Action, Adventure, Drama, Fantasy, Sci-fi"",
        ""Release : \n"" +""March 26, 2005"",
        ""Description : \n""+ ""The Doctor is a Time Lord: a 900 year old alien with 2 hearts, part of a gifted civilization who mastered time travel. The Doctor saves planets for a living – more of a hobby actually, and the Doctor's very, very good at it."")

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        viewModel = DetailViewModel()
        sendDetail.title=sampleDetail.title
        sendDetail.picture=sampleDetail.picture
        sendDetail.category=""Category : "" +sampleDetail.category
        sendDetail.genre=""Genre : \n"" +sampleDetail.genre
        sendDetail.release=""Release : \n"" +sampleDetail.release
        sendDetail.description=""Description : \n""+sampleDetail.description
    }

    @Test
    fun getData() {
        val movieEntities = viewModel.getData(sendDetail)
        assertNotNull(movieEntities)
        assertEquals(dummyDetail,sendDetail)
    }

    @Test
    fun testMockGetData() {
        Mockito.`when`(viewModel.getData(sendDetail)).thenReturn(dummyDetail)   // &lt;--- this dummyDetail is the problem
        val movieEntities = viewModel.getData(sendDetail)
        verify(viewModel).getData(sendDetail)
        assertEquals(dummyDetail, movieEntities)
    }

}
</code></pre>

<p>and this is the error message :</p>

<pre><code>Type mismatch: inferred type is SendDetail but Unit! was expected
</code></pre>
",https://stackoverflow.com/questions/61929936/thenreturn-a-data-class-in-using-mockito-with-kotlin,"['unit-testing', 'kotlin', 'mockito']",592,False,0,1
When to use act() in jest unit tests with react-dom,"<p>According to the react unit testing documentation:</p>

<blockquote>
  <p><strong>act()</strong></p>
  
  <p>To prepare a component for assertions, wrap the code rendering
  it and performing updates inside an act() call. This makes your test
  run closer to how React works in the browser.</p>
</blockquote>

<p>But the test runs perfectly fine in both cases:</p>

<h3>Without act()</h3>

<pre><code>it('Should return some text', () =&gt; {
  render(&lt;TestComponent /&gt;, container);
  expect(container.textContent).toBe('some text');
});
</code></pre>

<h3>With act()</h3>

<pre><code>it('Should return some text', () =&gt; {
  act(() =&gt; {
    render(&lt;TestComponent /&gt;, container);
  });

  expect(container.textContent).toBe('some text');
})
</code></pre>

<p>The questions is: <strong>What exactly act() does, and when should someone use it?</strong></p>
",https://stackoverflow.com/questions/60113292/when-to-use-act-in-jest-unit-tests-with-react-dom,"['reactjs', 'unit-testing', 'jestjs', 'react-dom']",68848,True,50,3
Unit testing the service itself in Angular with SnackBar call,"<p>I am relatively new to Angular Material unit testing and also to Service unit testing.
I created a service for my application with which I can call a Material SnackBar open function and passing a message parameter through. It's working really fine in every component when it needed but the unit testing for it is something... terrible to me.</p>

<pre><code>import { Injectable } from '@angular/core';
import { MatSnackBar, MatSnackBarRef, MatSnackBarConfig } from '@angular/material/snack-bar';

@Injectable({
  providedIn: 'root',
})
export class NotificationService {
  private snackBarConfig: MatSnackBarConfig;
  private snackBarRef: MatSnackBarRef&lt;any&gt;;
  private snackBarAutoHide = '5000';

  constructor(private sb: MatSnackBar) {}

  openSnackBar(message) {
    this.snackBarConfig = new MatSnackBarConfig();
    this.snackBarConfig.duration = parseInt(this.snackBarAutoHide, 0);
    this.sb.open(message, 'Dismiss', this.snackBarConfig);
  }
}
</code></pre>

<p>And the so-called test specification file is this:</p>

<pre><code>import { Overlay } from '@angular/cdk/overlay';
import { TestBed } from '@angular/core/testing';
import { MatSnackBar } from '@angular/material/snack-bar';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator';
import { NotificationService } from './notification-service';

describe('NotificationService testing:', () =&gt; {
  let spectator: SpectatorService&lt;NotificationService&gt;;
  const createService = createServiceFactory({
    service: NotificationService,
    providers: [MatSnackBar, Overlay],
    entryComponents: [],
    mocks: [NotificationService],
  });

  beforeEach(() =&gt; (spectator = createService()));

  it('should openSnackBar() be known as function', () =&gt; {
    expect(typeof spectator.service.openSnackBar).toEqual('function');
  });

  it('should be created', () =&gt; {
    const dateService = spectator.inject(NotificationService);
    spyOn(spectator.service, 'openSnackBar');
    dateService.openSnackBar('Test');
    expect(spectator.service.openSnackBar).toHaveBeenCalledWith('Test');
  });
});
</code></pre>

<p>My question would be the followings:</p>

<ol>
<li>Why my karma coverage says the openSnackBar(message) method is not
tested? I mean at least I testing if it is a function or not.</li>
<li>How can I actually test a service like this on its own?</li>
</ol>

<p>Thank you in advance. </p>
",https://stackoverflow.com/questions/61681785/unit-testing-the-service-itself-in-angular-with-snackbar-call,"['angular', 'unit-testing', 'karma-jasmine', 'angular9', 'spectator']",1362,True,0,1
Unit Tesing directives in Angular without TestBed &amp; Component,"<p>I did write a Unit Testing for a directive and it works but I wanted to ask if I can test it without component and TestBed.
What can I here change or what can I improve?
What is the idea to create a TestComponent and the idea of TestBed</p>

<p>Here it is the code of the directive.</p>

<pre><code>@Directive({
  selector: '[ngModel][endOfSeasonValidation]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() =&gt; EndOfSeasonValidationDirective),
      multi: true,
    },
  ],
})
export class EndOfSeasonValidationDirective extends AbstractValidatorDirective {
  @Input('beginDate')
  public beginDate: Date | null;

  @Input('startOfSeason')
  public startOfSeason: number | null;

  public validate(control: AbstractControl): ValidationErrors | null {
    const endOfSeason = control.value;

    if (!endOfSeason || !this.startOfSeason || !this.beginDate) {
      return null;
    }

    if (
      endOfSeason === this.startOfSeason ||
      endOfSeason + (endOfSeason &lt; this.startOfSeason ? 12 : 0) - this.startOfSeason === 11
    ) {
      return { isInvalid: true };
    }

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

<p>And here it is the code of unit testing</p>

<pre><code>@Component({
  template: `
    &lt;form&gt;
      &lt;select
        endOfSeasonValidation
        [ngModel]=""endOfSeason""
        name=""endOfSeason""
        [beginDate]=""beginDate""
        [startOfSeason]=""startOfSeason""
      &gt;&lt;/select&gt;
    &lt;/form&gt;
  `,
})
class EndOfSeasonValidationTestComponent {
  public beginDate = new Date('2020-01-16');
  public startOfSeason: number | null;
  public endOfSeason: number | null;
  @ViewChild(NgForm, { static: true })
  public form: NgForm;
}
describe('EndOfSeasonValidationDirective', () =&gt; {
  let fixture: ComponentFixture&lt;EndOfSeasonValidationTestComponent&gt;;
  let form: NgForm;
  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [
        EndOfSeasonValidationTestComponent,
        EndOfSeasonValidationDirective,
        DateAccessorPluginDirective,
        SelectAccessorDirective,
      ],
      imports: [FormsModule],
    }).compileComponents();
    fixture = TestBed.createComponent(EndOfSeasonValidationTestComponent);
    fixture.detectChanges();
    await fixture.whenStable();
    form = fixture.componentInstance.form;
  });
  it('should not validate if beginDate or startOfSeason or endOfSeason are not given', async () =&gt; {
    fixture.componentInstance.beginDate = new Date('2020-01-01');
    fixture.detectChanges();
    await fixture.whenStable();
    expect(form.valid).toBeTruthy();
    expect(form.errors).toBeFalsy();
  });
  it('should validate if startOfSeason and endOfSeason are equal', async () =&gt; {
    fixture.componentInstance.beginDate = new Date('2020-12-02');
    fixture.componentInstance.startOfSeason = 2;
    fixture.componentInstance.endOfSeason = 2;
    fixture.detectChanges();
    await fixture.whenStable();
    expect(fixture.componentInstance.form.invalid).toBeTruthy();
  });
});
</code></pre>
",https://stackoverflow.com/questions/59874353/unit-tesing-directives-in-angular-without-testbed-component,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",1046,True,1,1
Mocking a method that returns a method call to another object,"<p>I'm currently unit testing my code and I have problem with creating a mock using Moq. I'm unit testing Foo, and I wish to mock User.GetSomething() to isolate the test. I have created a qick sample of the code that I wish to test:</p>
<pre><code>public class User(){
    public List&lt;int&gt; GetSomething(){
         return bar.CreateList();
     }
}


public class Foo(User user){
   public int SomeMethod() {
      var x = User.GetSomething()
      Do something with x
      ...
    }
}
</code></pre>
<p>I have tried creating a mock by doing the following. I have excluded the assert and unnecessary arrange for this question:</p>
<pre><code>var mock = new Mock&lt;User&gt;();
List&lt;int&gt; someList = new List&lt;int&gt;(){1, 2, 3};
mock.Setup(u =&gt; u.CreateList()).Returns(SomeList);

Foo(mock.object)
var res = Foo.SomeMethod();
etc.
</code></pre>
<p>But I get the exception: <code>System.NotSupportedException : Unsupported expression: u =&gt; u.CreateList()</code></p>
<p><code>Non-overridable members (here: User.CreateList) may not be used in setup / verification expressions.</code></p>
",https://stackoverflow.com/questions/64663759/mocking-a-method-that-returns-a-method-call-to-another-object,"['c#', 'unit-testing', 'mocking', 'moq']",459,True,2,2
Assert in python code &amp; unit testing that checks if there is assert statement?,"<p>I have a code with an <code>assert</code> statement in it. Also, I'm doing unit testing on that code and I want to give a condition and if there is an <code>assert</code> statement in the code the test will pass.</p>

<pre><code>def do_something(m, n):
   assert m !=0, ""m has to be greater then 1""
       .....
</code></pre>

<p>In unit testing, I want to:</p>

<pre><code>class Test_ (unittest.TestCase):
    def test_something(self):
        # if m=0
        self.assert?????(m=0, ??not sure??)
</code></pre>

<p>What to write in order to test if there is an <code>assert</code> statement to <code>m=0</code>?
I saw something about context manager? Is it related?</p>
",https://stackoverflow.com/questions/59968068/assert-in-python-code-unit-testing-that-checks-if-there-is-assert-statement,"['python', 'python-3.x', 'unit-testing']",369,False,0,2
UWP Unit Tests Don&#39;t Show Up in Rider,"<p>I have a solution with two unit testing projects. One is for .NET and the other is for UWP. The .NET Framework and .NET Core tests show up in Rider but the UWP tests don't show up. They show up in Visual Studio. You can see the project <a href=""https://github.com/MelbourneDeveloper/Device.Net/tree/develop/src/Usb.Net.UWP.Sample"" rel=""nofollow noreferrer"">here</a>. It appears that dotCover is supposed to <a href=""https://www.jetbrains.com/help/dotcover/Profiling_Guidelines__Windows_Store_Applications.html"" rel=""nofollow noreferrer"">support UWP</a>. I assume that Rider uses the same engine. Also, I opened dotCover and found my app unit testing app among the packages but it doesn't pick up any of the tests either. I'm using MS Test but can switch if need be.</p>
<p>This is what I see in dotCover:
<a href=""https://i.stack.imgur.com/81Lao.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/81Lao.png"" alt=""enter image description here"" /></a></p>
<p>Does Rider support UWP for unit testing? If not, can I do this with dotCover? What am I doing wrong?</p>
",https://stackoverflow.com/questions/65375065/uwp-unit-tests-dont-show-up-in-rider,"['unit-testing', 'uwp', 'mstest', 'rider', 'dotcover']",170,True,1,1
Mocking EF&#39;s ExecuteSqlCommand using NUnit,"<p>I'm using Entity framework core. I was referring to one of the code suggested here: <a href=""https://stackoverflow.com/a/41515103/9766215"">https://stackoverflow.com/a/41515103/9766215</a></p>

<pre><code>public void SaveOrUpdate(MyEntity entity)
{
    var sql =  @""MERGE INTO MyEntity
                USING 
                (
                   SELECT   @id as Id
                            @myField AS MyField
                ) AS entity
                ON  MyEntity.Id = entity.Id
                WHEN MATCHED THEN
                    UPDATE 
                    SET     Id = @id
                            MyField = @myField
                WHEN NOT MATCHED THEN
                    INSERT (Id, MyField)
                    VALUES (@Id, @myField);""

    object[] parameters = {
        new SqlParameter(""@id"", entity.Id),
        new SqlParameter(""@myField"", entity.myField)
    };
    context.Database.ExecuteSqlCommand(sql, parameters);
}
</code></pre>

<p>I need to mock ExecuteSqlCommand but this extension method is not allowed to be overridden by Moq setup. I don't want to mock the whole method <code>SaveOrUpdate</code>. 
Please suggest if there's any way to mock or setup it for unit testing using any Database context methods. I'm using <code>UseInMemoryDatabase</code> for unit testing database context.</p>
",https://stackoverflow.com/questions/60484172/mocking-efs-executesqlcommand-using-nunit,"['c#', 'unit-testing', 'asp.net-core', 'entity-framework-core', 'dbcontext']",881,True,3,2
Testing a ResizeObserver inside an Effect Fn,"<p>I'm struggling a bit with unit testing the following:</p>
<pre><code>    const { element, state } = props;
    const { theme } = state;
    const { computedHeight, computedWidth   } = theme;
    const elementToSize = document.querySelector(element);

    const observer = new ResizeObserver(element =&gt; {
        const { contentRect } = element[0];

        // set the viewport size in the state
        dispatch(setViewportSize(state, contentRect.width, contentRect.height));

        // perform the task function
        wrapper(600, computedWidth, computedHeight, contentRect.width, contentRect.height).
            then(() =&gt; {
                elementToSize.style.height = `${contentRect.height &lt;= computedHeight ? contentRect.height : computedHeight}px`;
                elementToSize.style.width = `${contentRect.width &lt;= computedWidth ? contentRect.width : computedWidth}px`;
            }).catch( e =&gt; new Error(e));
    });

    observer.observe(document.documentElement);

    const wrapper = async (ms, ...callbackArgs) =&gt; {
        try {
            await asyncInterval(checkSize, ms, ...callbackArgs);
        } catch {
            new Error('async Interval has failed...');
        }

        return await asyncInterval(checkSize, ms, ...callbackArgs);
    };
};

export const SizeableEffect = (element, state) =&gt; [effectFn, { element, state } ];
</code></pre>
<p>In the code above, I have difficulties with unit testing the code inside the ResizeObserver.
I have the following in my test.</p>
<pre><code>import ResizeObserver from 'resize-observer-polyfill';
import { SizeableEffect } from 'effects';
import { domMock } from '../mocks/dom';

jest.mock('resize-observer-polyfill');

describe('SizeableEffect', () =&gt; {
    let stateMock, dispatch, effect, effectFn;

    beforeEach(() =&gt; {
        stateMock = {
            viewportWidth: null,
            viewportHeight: null,
            theme: {
                chatFrameSize: {
                    width: 300,
                    height: 500
                }
            }
        };

        dispatch = jest.fn();
        effect = SizeableEffect('elementMock', stateMock);
        effectFn = effect[0];

        Object.defineProperties(window, {
            document: {
                value: domMock()
            }
        });
    });

    it('the effect should be called with the element', () =&gt; {
        expect(effect[1]).toEqual(
            expect.objectContaining({
                element: 'elementMock',
                state: stateMock
            })
        );
    });

    it('the effect function should perform the operations', () =&gt; {
        effectFn(dispatch, { element: 'some', state: stateMock });
        expect(document.querySelector).toHaveBeenCalledWith('some');
        expect(dispatch).not.toHaveBeenCalled();
        expect(ResizeObserver).toHaveBeenCalled();
    });
});
</code></pre>
<p>And as you can see from the screenshot, I have uncovered lines where the <code>ResizeObserver</code> is doing the login by measuring the width' and height's against the viewport. <a href=""https://i.stack.imgur.com/yj5B5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yj5B5.png"" alt=""Code uncovered by the unit tests"" /></a></p>
<p>How can I cover those lines in the best way?</p>
",https://stackoverflow.com/questions/65337151/testing-a-resizeobserver-inside-an-effect-fn,"['javascript', 'jestjs']",389,False,1,0
Unit test case for camunda related services,"<pre><code>public variableInstance getVariableInstance(String proccessInstanceId, ProcessEngine processEngine) {
  RuntimeService runtimeService
    = processEngine.getRuntimeService();
  return runtimeService.createVariableInstanceQuery().processInstanceIdIn(processInstanceId).variableName(BiConstant.ID).singleResult();
}
</code></pre>
<p>Need help to write unit test case of this piece of code.New to unit testing.</p>
",https://stackoverflow.com/questions/64424569/unit-test-case-for-camunda-related-services,"['java', 'unit-testing', 'camunda']",562,False,0,1
@quasar/extras/mdi-v4 jest unit testing failing on Unexpected token &#39;export&#39;,"<p>I am using the new SVG images. I have created a test for a header that contains a logo, name mdiMenu.</p>
<p>import { mdiMenu } from '@quasar/extras/mdi-v4'
But everything I am running the test: I always get this error:</p>
<pre><code>SyntaxError: Unexpected token 'export'

      29 | 
      30 | &lt;script&gt;
    &gt; 31 | import { mdiMenu } from '@quasar/extras/mdi-v4'
Do somebody else have encounter this problem and how can I solve this?

This is the rest of the error message:

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 &quot;node_modules&quot;.

    Here's what you can do:
     • To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
     • If you need a custom transformation specify a &quot;transform&quot; 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 &quot;moduleNameMapper&quot; config option.        

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    C:\Users\YohnCheung\work\bitBucket\central-station\node_modules\@quasar\extras\mdi-v4\index.js:3
    export const mdiAbTesting = 'M4 2A2 2 0 0 0 2 4V12H4V8H6V12H8V4A2 2 0 0 0 6 2H4M4 4H6V6H4M22 15.5V14A2 2 0 0 0 20 12H16V22H20A2 2 0 0 0 22 20V18.5A1.54 1.54 0 0 0 20.5 17A1.54 1.54 0 0 0 22 15.5M20 20H18V18H20V20M20 16H18V14H20M5.79 21.61L4.21 20.39L18.21 2.39L19.79 3.61Z'
    ^^^^^^
</code></pre>
<p>Question was taken from:</p>
<p><a href=""https://forum.quasar-framework.org/topic/5459/quasar-extras-mdi-v4-jest-unit-testing-failing"" rel=""nofollow noreferrer"">https://forum.quasar-framework.org/topic/5459/quasar-extras-mdi-v4-jest-unit-testing-failing</a>
<a href=""https://forum.vuejs.org/t/quasar-extras-mdi-v4-jest-unit-testing-failing/89973"" rel=""nofollow noreferrer"">https://forum.vuejs.org/t/quasar-extras-mdi-v4-jest-unit-testing-failing/89973</a></p>
",https://stackoverflow.com/questions/63481304/quasar-extras-mdi-v4-jest-unit-testing-failing-on-unexpected-token-export,"['jestjs', 'quasar']",178,False,0,1
Updating multiple attributes of a python object - unit testing,"<pre><code>import requests


class RadioInfo:
    def __init__(self, url, station_num=0):
        self.url = url
        self.station_num = station_num

    def update(self):
        radio_info = self.get_json()
        self.update_info(radio_info)

    def get_json(self):
        r = requests.get(self.url)
        return r.json()[self.station_num]

    def update_info(self, radio_info):
        self.radio_station_name = radio_info[&quot;station&quot;][&quot;name&quot;]
        self.radio_station_description = radio_info[&quot;station&quot;][&quot;description&quot;]
        self.current_listeners = radio_info[&quot;listeners&quot;][&quot;current&quot;]
        self.unique_listeners = radio_info[&quot;listeners&quot;][&quot;unique&quot;]
        self.total_listeners = radio_info[&quot;listeners&quot;][&quot;total&quot;]
        self.now_playing_playlist = radio_info[&quot;now_playing&quot;][&quot;playlist&quot;]
        self.now_playing_song_title = radio_info[&quot;now_playing&quot;][&quot;song&quot;][&quot;title&quot;]
        self.now_playing_song_artist = radio_info[&quot;now_playing&quot;][&quot;song&quot;][&quot;artist&quot;]
        self.now_playing_song_album = radio_info[&quot;now_playing&quot;][&quot;song&quot;][&quot;album&quot;]
        ###
        # What if radio[&quot;playing_next&quot;] is None ??
        ###
        self.next_playing_playlist = radio_info[&quot;playing_next&quot;][&quot;playlist&quot;]
        self.next_playing_song_title = radio_info[&quot;playing_next&quot;][&quot;song&quot;][&quot;title&quot;]
        self.next_playing_song_artist = radio_info[&quot;playing_next&quot;][&quot;song&quot;][&quot;artist&quot;]
        self.next_playing_song_album = radio_info[&quot;playing_next&quot;][&quot;song&quot;][&quot;album&quot;]
</code></pre>
<p>Having the above, trying to figure out how to refactor this, so that I can check if some of the nodes are <code>None</code> and handle this accordingly.
Additionally starting out with unit testing, and besides error handling was thinking about best practices of unit testing this object.
Should I create a method for each property and unit test with <code>pytest.mark.parametrize</code> for example, or is this considered redundant and not necessary ?</p>
",https://stackoverflow.com/questions/65455552/updating-multiple-attributes-of-a-python-object-unit-testing,"['python', 'unit-testing', 'pytest']",90,False,0,0
Is there an equivalent method to java&#39;s `getDeclaredMethod()` to test private methods of classes in Typescript?,"<p>I'm unit testing a <code>typescript</code> project using <code>mocha</code> and <code>sinon</code>, with several private methods and variables. I have reworked by tests so that they are not calling them directly. I was wondering though, in unit testing I've done in <code>java</code> I've been able to use reflection to access private variables and methods. Namely, I've been able to use <code>java</code>'s <code>getDeclaredMethod()</code>. Is there an equivalent method in <code>typescript</code>? to test private methods of classes in <code>typescript</code>?</p>
",https://stackoverflow.com/questions/63165325/is-there-an-equivalent-method-to-javas-getdeclaredmethod-to-test-private-me,"['java', 'typescript', 'mocha.js', 'sinon']",71,False,0,1
File is not `goimports`-ed with -local somePath,"<p>I made some changes in Golang project and later ran <code>make test</code> which takes care of linting, formatting and unit testing. But when it run linter.sh, it throws following error</p>

<pre><code>pkg/skaffold/kubernetes/wait.go:23: File is not `goimports`-ed with -local github.com/GoogleContainerTools/skaffold (goimports)
        ""github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl""
</code></pre>

<p>Here is the link to <a href=""https://github.com/GoogleContainerTools/skaffold/pull/3346/commits"" rel=""noreferrer"">Code</a>.</p>
",https://stackoverflow.com/questions/59960394/file-is-not-goimports-ed-with-local-somepath,['go'],34547,True,18,8
Fortran Unit Testing with Visual Studio,"<p><strong>Dear all</strong>,</p>

<p>I tried to find any existing documentation about Fortran and <strong>Unit testing</strong> in Visual Studio but couldn't find any.
Do you have experience with Unit Testing for Fortran, can you recommend some good tutorials or books for that topic? The tools need to integrate into the Visual Studio 19 environment and I would love to use the built in Test-Explorer. (I use the Intel Compiler, but that should not matter for testing, right?)</p>

<p>best regards,</p>
",https://stackoverflow.com/questions/60973769/fortran-unit-testing-with-visual-studio,"['visual-studio', 'unit-testing', 'fortran']",480,True,3,2
Unit test BizTalk 2020 artefacts using Visual Studio 2019 leads to Intellisense issue,"<p>I encounter an issue when trying to use unit testing for BizTalk 2020 artefacts in Visual Studio 2019.</p>
<p>Here are the steps I have followed :</p>
<ul>
<li>I create new empty BizTalk project &quot;Testing&quot; and configure it for unit testing in project properties.</li>
<li>I create a folder in the project named &quot;Pipelines&quot;</li>
<li>In this folder I create a receive pipeline &quot;ppr_Testing.btp&quot; with a single &quot;XML disassembler&quot; component.</li>
<li>I create new unit testing project &quot;_Test&quot;</li>
<li>In &quot;_Test&quot; project, I add a project reference to &quot;Testing&quot;</li>
<li>In the unit testing project, I create a unit test and try to write code to instanciate &quot;ppr_Testing&quot; pipeline</li>
</ul>
<pre class=""lang-cs prettyprint-override""><code>using Testing.Pipelines;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace _Test
{
    
    /// &lt;summary&gt;
    ///This is a test class for Test_ppr_Testing and is intended
    ///to contain all Test_ppr_Testing Unit Tests
    ///&lt;/summary&gt;
    [TestClass()]
    public class Test_ppr_Testing
    {

        private TestContext testContextInstance;

        /// &lt;summary&gt;
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///&lt;/summary&gt;
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        /// &lt;summary&gt;
        ///A test for ppr_Testing Constructor
        ///&lt;/summary&gt;
        [TestMethod()]
        public void Test_ppr_TestingConstructor()
        {
            ppr_Testing target = new ppr_Testing();

            var lDocuments = new System.Collections.Specialized.StringCollection();
            lDocuments.Add(@&quot;C:\MyTestDirectory\SomeFile.xml&quot;);

            var lParts = new System.Collections.Specialized.StringCollection();
            var lSchemas = new System.Collections.Generic.Dictionary&lt;string, string&gt;();

            try
            {
                target.TestPipeline(lDocuments, lParts, lSchemas);
                var lTmp = this.TestContext;
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.ToString());
            }
        }
    }
}
</code></pre>
<p>Result :</p>
<ul>
<li>The code is underlined in error because the object is not recognized by Intellisense</li>
<li>If I manage to write the testing code without Intellisense, it compiles and runs successfuly</li>
</ul>
<p><img src=""https://i.stack.imgur.com/LHluK.png"" alt=""Intellisense error 1"" /></p>
<p><img src=""https://i.stack.imgur.com/OAcXL.png"" alt=""Intellisense error 2"" /></p>
<p>Am I doing something wrong, or is my Visual Studio 2019 installation corrupted ?</p>
<p>I'm in the process of migrating from BizTalk 2010 to BizTalk 2020, and with BizTalk 2010 and Visual Studio 2010 things were easier :</p>
<ul>
<li>I just go to &quot;Test&quot; menu, &quot;New Test...&quot;, then &quot;Unit Test Wizard&quot;, and follow the wizard, and everything is OK.</li>
</ul>
<p>Thanks in advance for any help.</p>
",https://stackoverflow.com/questions/64260172/unit-test-biztalk-2020-artefacts-using-visual-studio-2019-leads-to-intellisense,"['c#', 'unit-testing', 'visual-studio-2019', 'biztalk', 'biztalk-2020']",196,True,1,1
Testing a function that returns an object with a function - JavaScript (Jest),"<p>I have a situation where I am facing an issue regarding unit testing of a function. There is a function <code>SOP3loginConfig</code> which returns an object, within that object we have a function <code>isSOP3</code> that returns a boolean, I want to test this function and cover the test part of it.</p>

<p><strong>The actual implementation of the function <code>sop3login.ts</code></strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export const SOP3loginConfig = (props: IVariables) =&gt; {
  const { i18n } = props;
  return {
    buttonLabel: props.user != null ? i18n('StartJourney') : i18n('logIn'),
    loginLink:""/login?redirectUrl=""+window.location.href,
    isSOP3: async() =&gt; {
      let userData = await ADCServices.getUserInfo();
      if (!userData.session.tammUserInfo || userData.session.tammUserInfo.Type!=""SOP3"") {
        props.SOP3toggleModal(props,true);
        setTimeout(()=&gt;props.SOP3toggleModal(props,false),5000)
        return false;
      } else {
        return true;
      }
    },
  };
};</code></pre>
</div>
</div>
</p>

<p><strong>My Integration <code>work.ts</code></strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { SOP3loginConfig } from 'client/.../sop3login';

const start = async (props: IVariables) =&gt; {
  if (props.user) {
    if (await SOP3loginConfig(props).isSOP3()) {
      props.history.push('/adc/card-renewal/customs');
    }
  } else {
    props.history.push(SOP3loginConfig(props).loginLink);
  }
};</code></pre>
</div>
</div>
</p>

<p><strong>Unit testing implmentation of mine <code>work.test.ts</code></strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>  describe('Start SOP3loginConfig should be called', () =&gt; {
    it('Should call the SOP3', async () =&gt; {
      props.user = true;
      // const isSOP3Mock = () =&gt; {
      //   return true;
      // };
      // let SOP3loginConfig = async (props: any) =&gt; {
      //   return true;
      //   // return {
      //   //   isSOP3: isSOP3Mock,
      //   // };
      // };
      let SOP3loginConfig = jest.fn(props =&gt; {
        return {
          isSOP3: jest.fn(() =&gt; {
            return true;
          }),
        };
      });
      functions.start(props);
      expect(await SOP3loginConfig(props).isSOP3).toHaveBeenCalled();
      expect(props.history.push).toHaveBeenCalled();
    });
  });</code></pre>
</div>
</div>
</p>

<p><strong>Error I am getting</strong></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: &gt;= 1
    Received number of calls:    0

       97 |       });
       98 |       functions.start(props);
    &gt;  99 |       expect(await SOP3loginConfig(props).isSOP3).toHaveBeenCalled();
          |                                                   ^
      100 |       expect(props.history.push).toHaveBeenCalled();
      101 |     });
      102 |   });</code></pre>
</div>
</div>
</p>

<blockquote>
  <p>All I want to is cover the <code>if (await SOP3loginConfig(props).isSOP3())</code> part in <code>work.ts</code>.</p>
</blockquote>
",https://stackoverflow.com/questions/59627009/testing-a-function-that-returns-an-object-with-a-function-javascript-jest,"['typescript', 'unit-testing', 'jestjs', 'react-testing-library', 'jest-fetch-mock']",6364,True,0,1
How to access real DataBase in unit testing?,"<p>I want to get data from my actual database in unit testing.
I have a table named person and I have data in that table. Now, I want to get data from that table in unit testing.
Below is the code which I am using to fetch data from the DB.</p>
<pre><code>public class PersonAppService_Tests: AppTestBase
{
private readonly IRepository&lt;Person&gt; _PersonRepositroy;
private readonly IUnitOfWorkManager _unitOfWorkManager;

public PersonAppService_Tests()
        {
            
            _PersonRepositroy = Resolve&lt;IRepository&lt;Person&gt;&gt;();
            _unitOfWorkManager = Resolve&lt;IUnitOfWorkManager&gt;();

        }
public async Task&lt;List&lt;PersonListDto&gt;&gt; GetAll()
        {
           List&lt;PersonListDto&gt; a = new List&lt;PersonListDto&gt;();
            using (var uow = _unitOfWorkManager.Begin())
            {
                var test = from Person in _PersonRepositroy.GetAll()
                           select new PersonListDto
                           {
                               Id = Person.Id,
                               Text = Person.Text,
                               Code = Person.Code,                               
                               TenantId = Person.TenantId
                           };
                a = test.ToList();//No Data is apppearing, event though database has the data
                await uow.CompleteAsync();
            }

            
        }

}
</code></pre>
<p>using this code I get null data as I have data in my DB.</p>
<p>I am using asp.net Core (3.0) +Entity Framework 5.0</p>
",https://stackoverflow.com/questions/63987043/how-to-access-real-database-in-unit-testing,"['database', 'entity-framework', 'unit-testing', 'asp.net-core', 'aspnetboilerplate']",448,True,0,1
NSubstitute.Exceptions.ReceivedCallsException: Expected to receive a call matching error while unit testing,"<p>I am getting a below error while unit testing the piece of code</p>

<blockquote>
  <p>NSubstitute.Exceptions.ReceivedCallsException: Expected to receive a call matching error while unit testing
  NSubstitute.Exceptions.ReceivedCallsException
    HResult=0x80131500
    Message=Expected to receive a call matching:
      enrollWithHelper("""", """")
  Actually received no matching calls.</p>
  
  <p>Source=NSubstitute
    StackTrace:
     at NSubstitute.Core.ReceivedCallsExceptionThrower.Throw(ICallSpecification callSpecification, IEnumerable<code>1 matchingCalls, IEnumerable</code>1 nonMatchingCalls, Quantity requiredQuantity)
     at NSubstitute.Routing.Handlers.CheckReceivedCallsHandler.Handle(ICall call)
     at NSubstitute.Routing.Route.Handle(ICall call)
     at NSubstitute.Proxies.CastleDynamicProxy.CastleForwardingInterceptor.Intercept(IInvocation invocation)
     at Castle.DynamicProxy.AbstractInvocation.Proceed()
     at Castle.DynamicProxy.AbstractInvocation.Proceed()
     at Castle.Proxies.ObjectProxy_1.enrollWithHelper(String name, String type)
     at MyProject.MyTest.processing_test_pass() in C:\MyProject\MyTest.cs:line 75</p>
</blockquote>

<p><strong>Framework</strong>: .NET Core</p>

<p><strong>Unit Testing</strong>: NSubstitute</p>

<p>Here is my class under test</p>

<pre><code> public class MyService: IMysService
 {
   private readonly IRepository _repository;
   Private readonly IIoTHelper _iotHelper;  
   Private readonly HttpClient _httpClient;
   private Configuration _configuration; 

   public MyService(IRepository repository, IIoTHelper iotHelper, HttpClient httpClient )
   {
        _repository = repository;
        _iotHelper =iotHelper;
        _httpClient = httpClient ;
   }

   public bool CallService(JObject reqObj, out Status status)
   {
        bool provisioningSuccess = false;
        return PreProcessing(reqObj,out Status status); //private method
   }
}
</code></pre>

<p>Here is my private method</p>

<pre><code>    private PreProcessing(JObject JosnObj, out Status status)
    {
        if (_configuration== null)
        {
            _configuration= _repository.GetConfigurations()                 
        }

       using (var client = this._httpClient)
       {
            var request = new {_configuration.Number,_configuration.Type};
            var response = client.PostAsJsonAsync(""api/preprocess"", request).Result;

            if (response.IsSuccessStatusCode)
            {
                  _iotHelper.enrollWithHelper(_configuration.Number,_configuration.Type);
            }
       }
    }
</code></pre>

<p>Here is my Configuration class</p>

<pre><code>   public class Configuration 
   {
     public Configuration (string number, string type)
     {
        Number= number;
        Type= type;
     }      
     public string Number { get;}

     public string Type { get; }

   }
</code></pre>

<p>Here is my unit test code, where I want to make sure it reaches the <code>private</code> method </p>

<pre><code>    protected override void InitializeTest()
    {
        this._repository = Substitute.For&lt;IRepository&gt;();
        this._iotHelper = Substitute.For&lt;IIotHelper&gt;();
    }

    [TestMethod]
    public void processing_test_pass()
    {
          //Arrange
        var messageHandler = new MockHttpMessageHandler(""TEST VALUE"", HttpStatusCode.OK);
        var httpClient = new HttpClient(messageHandler);


          JObject reqobj= new JObject(
          new JProperty(""user"", ""username""),
          new JProperty(""pass"", ""password""));

        Status status = new Status();

        //act
        var t = new MyService(this._repository,this._iotHelper, httpClient );
        bool success = t.CallService(reqobj, out status);
        //assert
        this._iotHelper.Received().enrollWithHelper("""","""");

    }
</code></pre>

<p>How would I test <code>enrollWithHelper</code> is called?</p>

<p>Also I am stuck due to error!</p>
",https://stackoverflow.com/questions/59773418/nsubstitute-exceptions-receivedcallsexception-expected-to-receive-a-call-matchi,"['c#', 'unit-testing', 'nsubstitute']",3204,False,0,0
how to compare File/Stream Equality in dart,"<p>How can I check Files/Stream equality in dart?</p>
<p>Like this:</p>
<pre><code>File file1;
File file2;
file1.equals(file2) // false Or true
</code></pre>
<p>Or in Streams Like this:</p>
<pre><code>
Stream&lt;Int8List&gt; stream1;
Stream&lt;Int8List&gt; stream2;

stream1.equals(Stream2) // false Or true
</code></pre>
<p>And also in unit testing?</p>
",https://stackoverflow.com/questions/63563038/how-to-compare-file-stream-equality-in-dart,"['flutter', 'dart', 'stream', 'equality', 'rxdart']",875,True,3,1
The purpose of self,"<p>I tried to test a file named <strong>calc.py</strong> using unit testing</p>
<pre><code>import unittest
import calc
class TestCalc(unittest.TestCase):
    
    def test_add(self):
        result = calc.add(10,5)
        self.assertEqual(result,15)
</code></pre>
<p>What does self refer to in this code?</p>
",https://stackoverflow.com/questions/62586642/the-purpose-of-self,"['python', 'python-unittest']",59,True,0,1
Do I need to continue build my model until controller and view or create another model to create associations to each?,"<p>In my rails app, I am done creating my first model and the unit testing. What to do next?</p>
",https://stackoverflow.com/questions/61626297/do-i-need-to-continue-build-my-model-until-controller-and-view-or-create-another,['ruby-on-rails-6'],17,False,0,1
Angular JS: Karma not installing in project folder. ERR! code EINTEGRITY,"<p>Im learning angular JS currently and im trying to learn unit testing. I was instructed to use karma and Jasmine for my unit testing and Im currently trying to set it up.after installing JS node and performing the global installation  i keep getting the error below thats putting up an EEINTEGRITY error code.Any ideas? Here is the error shown along with the full log of the run performed below.</p>

<pre><code>npm ERR! code EINTEGRITY
npm ERR! sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== integrity checksum failed when using sha512: wanted sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== but got sha512-ALpfN/W8faBisExChxWPuhT1Qnp0P2OVFYaRHMj/j5tZXE3/uxLDvf9BtIdbBuCqMp258SHJPz2JbxEX37EG/Q==. (2082 bytes)
</code></pre>

<p>Here is a complete log of the run shown above</p>

<pre><code>0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   'karma'
1 verbose cli ]
2 info using npm@6.13.4
3 info using node@v12.14.0
4 verbose config Skipping project config: C:\Users\HP/.npmrc. (matches userconfig)
5 verbose npm-session aa0738418c1931c7
6 silly install loadCurrentTree
7 silly install readLocalPackageData
8 http fetch GET 200 http://registry.npmjs.org/karma 1451ms
9 http fetch GET 200 http://registry.npmjs.org/karma/-/karma-5.0.9.tgz 2392ms
10 silly pacote tag manifest for karma@latest fetched in 3968ms
11 timing stage:loadCurrentTree Completed in 4234ms
12 silly install loadIdealTree
13 silly install cloneCurrentTreeToIdealTree
14 timing stage:loadIdealTree:cloneCurrentTree Completed in 0ms
15 silly install loadShrinkwrap
16 timing stage:loadIdealTree:loadShrinkwrap Completed in 10ms
17 silly install loadAllDepsIntoIdealTree
18 silly resolveWithNewModule karma@5.0.9 checking installable status
19 http fetch GET 200 http://registry.npmjs.org/body-parser 752ms
20 http fetch GET 200 http://registry.npmjs.org/dom-serialize 745ms
21 http fetch GET 200 http://registry.npmjs.org/di 806ms
22 http fetch GET 304 http://registry.npmjs.org/braces 884ms (from cache)
23 silly pacote range manifest for braces@^3.0.2 fetched in 902ms
24 silly resolveWithNewModule braces@3.0.2 checking installable status
25 http fetch GET 304 http://registry.npmjs.org/glob 914ms (from cache)
26 http fetch GET 304 http://registry.npmjs.org/colors 956ms (from cache)
27 silly pacote range manifest for glob@^7.1.6 fetched in 979ms
28 silly resolveWithNewModule glob@7.1.6 checking installable status
29 http fetch GET 304 http://registry.npmjs.org/graceful-fs 1053ms (from cache)
30 http fetch GET 200 http://registry.npmjs.org/flatted 1192ms
31 silly pacote range manifest for graceful-fs@^4.2.4 fetched in 1265ms
32 silly resolveWithNewModule graceful-fs@4.2.4 checking installable status
33 http fetch GET 200 http://registry.npmjs.org/di/-/di-0.0.1.tgz 545ms
34 http fetch GET 200 http://registry.npmjs.org/isbinaryfile 392ms
35 silly pacote range manifest for di@^0.0.1 fetched in 1392ms
36 silly resolveWithNewModule di@0.0.1 checking installable status
37 http fetch GET 200 http://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz 689ms
38 http fetch GET 200 http://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz 792ms
39 silly pacote range manifest for dom-serialize@^2.2.1 fetched in 1588ms
40 silly resolveWithNewModule dom-serialize@2.2.1 checking installable status
41 http fetch GET 200 http://registry.npmjs.org/http-proxy 685ms
42 http fetch GET 200 http://registry.npmjs.org/colors/-/colors-1.4.0.tgz 678ms
43 http fetch GET 200 http://registry.npmjs.org/flatted/-/flatted-2.0.2.tgz 447ms
44 http fetch GET 200 http://registry.npmjs.org/chokidar 1697ms
45 silly pacote range manifest for body-parser@^1.19.0 fetched in 1705ms
46 silly resolveWithNewModule body-parser@1.19.0 checking installable status
47 silly pacote range manifest for colors@^1.4.0 fetched in 1710ms
48 silly resolveWithNewModule colors@1.4.0 checking installable status
49 silly pacote range manifest for flatted@^2.0.2 fetched in 1709ms
50 silly resolveWithNewModule flatted@2.0.2 checking installable status
51 http fetch GET 200 http://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.6.tgz 337ms
52 silly pacote range manifest for isbinaryfile@^4.0.6 fetched in 900ms
53 silly resolveWithNewModule isbinaryfile@4.0.6 checking installable status
54 http fetch GET 304 http://registry.npmjs.org/lodash 668ms (from cache)
55 silly pacote range manifest for lodash@^4.17.15 fetched in 714ms
56 silly resolveWithNewModule lodash@4.17.15 checking installable status
57 http fetch GET 200 http://registry.npmjs.org/range-parser 664ms
58 http fetch GET 200 http://registry.npmjs.org/qjobs 673ms
59 http fetch GET 200 http://registry.npmjs.org/mime 841ms
60 http fetch GET 304 http://registry.npmjs.org/minimatch 741ms (from cache)
61 http fetch GET 200 http://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz 880ms
62 silly pacote range manifest for http-proxy@^1.18.1 fetched in 1647ms
63 silly resolveWithNewModule http-proxy@1.18.1 checking installable status
64 silly pacote range manifest for minimatch@^3.0.4 fetched in 883ms
65 silly resolveWithNewModule minimatch@3.0.4 checking installable status
66 http fetch GET 304 http://registry.npmjs.org/rimraf 740ms (from cache)
67 silly pacote range manifest for rimraf@^3.0.2 fetched in 802ms
68 silly resolveWithNewModule rimraf@3.0.2 checking installable status
69 http fetch GET 200 http://registry.npmjs.org/connect 2772ms
70 http fetch GET 200 http://registry.npmjs.org/chokidar/-/chokidar-3.4.0.tgz 1126ms
71 silly pacote range manifest for chokidar@^3.0.0 fetched in 2842ms
72 silly resolveWithNewModule chokidar@3.4.0 checking installable status
73 http fetch GET 200 http://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz 538ms
74 silly pacote range manifest for range-parser@^1.2.1 fetched in 1243ms
75 silly resolveWithNewModule range-parser@1.2.1 checking installable status
76 http fetch GET 304 http://registry.npmjs.org/source-map 456ms (from cache)
77 http fetch GET 200 http://registry.npmjs.org/qjobs/-/qjobs-1.2.0.tgz 611ms
78 silly pacote range manifest for qjobs@^1.2.0 fetched in 1405ms
79 silly resolveWithNewModule qjobs@1.2.0 checking installable status
80 http fetch GET 200 http://registry.npmjs.org/ua-parser-js 447ms
81 http fetch GET 200 http://registry.npmjs.org/socket.io 1210ms
82 http fetch GET 304 http://registry.npmjs.org/tmp 598ms (from cache)
83 http fetch GET 200 http://registry.npmjs.org/connect/-/connect-3.7.0.tgz 593ms
84 http fetch GET 304 http://registry.npmjs.org/yargs 542ms (from cache)
85 silly pacote range manifest for connect@^3.7.0 fetched in 3437ms
86 silly resolveWithNewModule connect@3.7.0 checking installable status
87 http fetch GET 200 http://registry.npmjs.org/mime/-/mime-2.4.5.tgz 966ms
88 silly pacote range manifest for mime@^2.4.5 fetched in 1854ms
89 silly resolveWithNewModule mime@2.4.5 checking installable status
90 silly fetchPackageMetaData error for source-map@^0.6.1 sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== integrity checksum failed when using sha512: wanted sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== but got sha512-ALpfN/W8faBisExChxWPuhT1Qnp0P2OVFYaRHMj/j5tZXE3/uxLDvf9BtIdbBuCqMp258SHJPz2JbxEX37EG/Q==. (2082 bytes)
91 http fetch GET 200 http://registry.npmjs.org/socket.io/-/socket.io-2.3.0.tgz 705ms
92 silly pacote range manifest for socket.io@^2.3.0 fetched in 1946ms
93 silly resolveWithNewModule socket.io@2.3.0 checking installable status
94 http fetch GET 200 http://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz 889ms
95 silly pacote version manifest for tmp@0.2.1 fetched in 1551ms
96 silly resolveWithNewModule tmp@0.2.1 checking installable status
97 http fetch GET 200 http://registry.npmjs.org/log4js 2868ms
98 http fetch GET 200 http://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.21.tgz 1168ms
99 silly pacote version manifest for ua-parser-js@0.7.21 fetched in 1652ms
100 silly resolveWithNewModule ua-parser-js@0.7.21 checking installable status
101 http fetch GET 200 http://registry.npmjs.org/log4js/-/log4js-6.2.1.tgz 509ms
102 silly pacote range manifest for log4js@^6.2.1 fetched in 3453ms
103 silly resolveWithNewModule log4js@6.2.1 checking installable status
104 http fetch GET 200 http://registry.npmjs.org/yargs/-/yargs-15.3.1.tgz 1443ms
105 silly pacote range manifest for yargs@^15.3.1 fetched in 2035ms
106 silly resolveWithNewModule yargs@15.3.1 checking installable status
107 timing stage:rollbackFailedOptional Completed in 0ms
108 timing stage:runTopLevelLifecycles Completed in 9154ms
109 silly saveTree HP
109 silly saveTree +-- karma@5.0.9
109 silly saveTree | +-- body-parser@1.19.0
109 silly saveTree | +-- braces@3.0.2
109 silly saveTree | +-- chokidar@3.4.0
109 silly saveTree | +-- colors@1.4.0
109 silly saveTree | +-- connect@3.7.0
109 silly saveTree | +-- di@0.0.1
109 silly saveTree | +-- dom-serialize@2.2.1
109 silly saveTree | +-- flatted@2.0.2
109 silly saveTree | +-- glob@7.1.6
109 silly saveTree | | `-- minimatch@3.0.4
109 silly saveTree | +-- graceful-fs@4.2.4
109 silly saveTree | +-- http-proxy@1.18.1
109 silly saveTree | +-- isbinaryfile@4.0.6
109 silly saveTree | +-- lodash@4.17.15
109 silly saveTree | +-- log4js@6.2.1
109 silly saveTree | +-- mime@2.4.5
109 silly saveTree | +-- minimatch@3.0.4
109 silly saveTree | +-- qjobs@1.2.0
109 silly saveTree | +-- range-parser@1.2.1
109 silly saveTree | +-- rimraf@3.0.2
109 silly saveTree | +-- socket.io@2.3.0
109 silly saveTree | +-- tmp@0.2.1
109 silly saveTree | +-- ua-parser-js@0.7.21
109 silly saveTree | `-- yargs@15.3.1
109 silly saveTree `-- popper.js@1.15.0
110 verbose stack Error: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== integrity checksum failed when using sha512: wanted sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== but got sha512-ALpfN/W8faBisExChxWPuhT1Qnp0P2OVFYaRHMj/j5tZXE3/uxLDvf9BtIdbBuCqMp258SHJPz2JbxEX37EG/Q==. (2082 bytes)
110 verbose stack     at Transform.&lt;anonymous&gt; (C:\Program Files\nodejs\node_modules\npm\node_modules\ssri\index.js:328:19)
110 verbose stack     at Transform.emit (events.js:215:7)
110 verbose stack     at endReadableNT (_stream_readable.js:1184:12)
110 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:80:21)
111 verbose cwd C:\Users\HP\Documents\web dev\Angular1
112 verbose Windows_NT 10.0.10240
113 verbose argv ""C:\\Program Files\\nodejs\\node.exe"" ""C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"" ""install"" ""karma""
114 verbose node v12.14.0
115 verbose npm  v6.13.4
116 error code EINTEGRITY
117 error sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== integrity checksum failed when using sha512: wanted sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== but got sha512-ALpfN/W8faBisExChxWPuhT1Qnp0P2OVFYaRHMj/j5tZXE3/uxLDvf9BtIdbBuCqMp258SHJPz2JbxEX37EG/Q==. (2082 bytes)
118 verbose exit [ 1, true ]
</code></pre>
",https://stackoverflow.com/questions/61925808/angular-js-karma-not-installing-in-project-folder-err-code-eintegrity,"['javascript', 'angularjs', 'npm', 'karma-jasmine']",158,False,0,0
Jest and Enzyme unit test: TypeError: Cannot read property &#39;push&#39; of undefined,"<p>I'm writing a unit test to simulate a click on a button. The button's onClick method has a reference to a method that loads another page using props.history.push('/). The simulation works but jest says it can't read the property push because history is undefined and that makes the test to fail.How can i add props.history while unit testing .What i'm i doing wrong.</p>

<p>This is the test file</p>

<pre><code> import React from 'react';
import Landing from '../Components/Landing/Landing';
import configureStore from 'redux-mock-store';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import {StyleRoot}from 'radium';
import { Provider } from 'react-redux';
import { createMemoryHistory } from 'history';


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

const mockStore = configureStore();

let wrapper;
let store;


const initialState = {
    auth:{
        isLoggedIn:false,
        role:''
    },

};

const history = createMemoryHistory().push('/');

beforeEach(()=&gt;{

    store = mockStore(initialState); 

    wrapper = mount( &lt;Provider store={store} &gt;
                        &lt;StyleRoot&gt; 
                          &lt;Landing history={history}/&gt; 
                        &lt;/StyleRoot&gt; 
                     &lt;/Provider&gt;
                    ); 

});

   describe('Landing.js',()=&gt;{

    it ('Simulate click', ()=&gt;{

        const signInBtn = wrapper.find('.Btn');

        signInBtn.simulate('click');

       });  

   });
</code></pre>

<p>This is the component</p>

<pre><code>const landing = props =&gt;{


const loadSignInPage = ()=&gt;{
    props.history.push('/signin');
};


 return(
     &lt;React.Fragment&gt;

        &lt;Button buttonClass=""SignIn"" className=""Btn"" click={loadSignInPage}&gt;SIGN IN&lt;/Button&gt;

     &lt;/React.Fragment&gt;
 );
};

const mapStateToProps = state =&gt;{
    return{
        isLoggedIn: state.auth.isLoggedIn,
        role: state.auth.role
    };
};

export default connect(mapStateToProps)(landing);
</code></pre>

<p>The error</p>

<pre><code>  TypeError: Cannot read property 'push' of undefined

   8 | 
   9 | const loadSignInPage = ()=&gt;{
&gt; 10 |     props.history.push('/signin');
     |                   ^
  11 | };
</code></pre>

<p>How can i add props.history while unit testing</p>
",https://stackoverflow.com/questions/61044700/jest-and-enzyme-unit-test-typeerror-cannot-read-property-push-of-undefined,"['reactjs', 'unit-testing', 'jestjs']",7288,True,2,3
Test suite failed to run Cannot find module &#39;@env&#39; from &#39;&#39;mylocalfile.js&quot;,"<p>I am using jest unit testing in my project. It was working fine for some time. I have integrated dotenv with my project recently. Now testing is failed for all files. Receiving following error when I do a run test.</p>
<p><a href=""https://i.stack.imgur.com/A9XW6.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/A9XW6.png"" alt=""enter image description here"" /></a></p>
<p>Project dotenv Structure</p>
<ol>
<li>.env in my root folder</li>
<li>env.d.ts in my root folder/src/typings</li>
</ol>
<p>My actual code</p>
<pre><code>import { Linking, AsyncStorage, Platform, Alert } from &quot;react-native&quot;;
import { Toast } from &quot;native-base&quot;;
import { ZOOM_APP_PLAYSTORE, ZOOM_APP_APPSTORE, ZOOM_URL } from &quot;@env&quot;;
import { General } from &quot;../Constants&quot;;
</code></pre>
<p>when I do run the app, it is working fine, and issues with only run a test.</p>
<p>Unit testing - jest</p>
<p>Test code</p>
<pre><code>describe(&quot;Testpage Component&quot;, () =&gt; {
    it('renders without crashing', () =&gt; {
        const rendered = renderer.create(&lt;Provider store={store}&gt;
            &lt;DrawerComponent /&gt;
        &lt;/Provider&gt;).toJSON();
        expect(rendered).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/64504627/test-suite-failed-to-run-cannot-find-module-env-from-mylocalfile-js,"['react-native', 'jestjs', 'environment-variables', 'dotenv']",436,False,2,0
"I am Get starting with unit testing with NUnit, (doesn&#39;t run the test) Why?","<p>i am starting using unit testing in visual Studio. I'm reading the Microsoft Documantation about it: <a href=""https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2019"" rel=""nofollow noreferrer"">Get started with unit testing</a>, but when i run, doesn't run the test, and show this: Program, is inaccessible due to its protection level. I dont know what i have to do now.
Can u help.</p>
<p>This is my Hello World Program</p>
<pre><code>using System;

namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine(&quot;Hello World!&quot;);
        }
    }
}

</code></pre>
<p>Unit test with NUnit</p>
<pre><code>using NUnit.Framework;
using System.IO;
using System;

namespace HelloWorldTests
{
    public class Tests
    {
        private const string Expected = &quot;Hello World!&quot;;

        [SetUp]
        public void Setup()
        {
        }
        [Test]
        public void TestMethod1()
        {
            using (var sw = new StringWriter())
            {
                Console.SetOut(sw);
                demo.Program.Main();

                var result = sw.ToString().Trim();
                Assert.AreEqual(Expected, result);
            }
        }
    }
}

</code></pre>
<p>ERROR SHOW: Error CS0122: 'Program' is inaccessible due to its protection level (CS0122) (HelloWorldTests)</p>
",https://stackoverflow.com/questions/62961673/i-am-get-starting-with-unit-testing-with-nunit-doesnt-run-the-test-why,"['c#', 'visual-studio', 'unit-testing', 'nunit']",364,True,0,3
Performing unit test for dynamo db functions,"<p>I am new to unit testing and wanted to perform some tests on the below listed functions. Thanks for the help.     </p>
",https://stackoverflow.com/questions/60436442/performing-unit-test-for-dynamo-db-functions,"['python', 'python-3.x', 'unit-testing', 'mocking', 'amazon-dynamodb']",1292,True,1,2
Insert data in h2 database through data.sql file before performing unit testing in spring boot,"<p>I want to perform unit testing in spring boot+ JPA. For that I created configuration file to create bean for dataSource, all hibernate properties, entityManagerFactory and transactionManager. Everything going perfect. Tables are getting created by model classes. but now I want to insert data in all tables of database for testing through data.sql file.
I kept data.sql file in src/main/resources but it not loading the file.
So how can I load data in h2 database before starting with unit testing. </p>

<p>This is my cofiguration file - </p>

<pre><code>
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.cfg.Environment;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@EnableJpaRepositories(basePackages = ""base_package_name"")
@EnableTransactionManagement
public class JPAConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(""org.h2.Driver"");
        dataSource.setUrl(""jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1"");
        /*dataSource.setDriverClassName(""org.hsqldb.jdbcDriver"");
        dataSource.setUrl(""jdbc:hsqldb:mem:testdb"");*/
        dataSource.setUsername(""sa"");
        dataSource.setPassword("""");

        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put(""hibernate.dialect"", ""org.hibernate.dialect.H2Dialect"");
        properties.put(""hibernate.hbm2ddl.auto"", ""create"");
        properties.put(""hibernate.show_sql"", ""true"");
        properties.put(""hibernate.format_sql"", ""false"");
        return properties;
    }

    @Bean(name=""entityManagerFactory"")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setDataSource(this.dataSource());
        lcemfb.setPackagesToScan(new String[] {""Package_to_scan""});

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        lcemfb.setJpaVendorAdapter(va);

        lcemfb.setJpaProperties(this.hibernateProperties());

        lcemfb.afterPropertiesSet();

        return lcemfb;

    }


    @Bean
    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();

        tm.setEntityManagerFactory(
            this.entityManagerFactoryBean().getObject() );

        return tm;

    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

</code></pre>
",https://stackoverflow.com/questions/60333899/insert-data-in-h2-database-through-data-sql-file-before-performing-unit-testing,"['java', 'spring-boot', 'h2', 'spring-boot-test', 'h2db']",12374,True,4,1
InvalidArgumentException: Action App\Http\Controllers\App\Http\Controllers\OrderController@store not defined,"<p>I'm new to unit Testing and I'm using Laravel 8 ,</p>
<p>I get always this error :</p>
<pre><code>InvalidArgumentException: Action App\Http\Controllers\App\Http\Controllers\OrderController@store not defined.
 
</code></pre>
<p>Thank you for any help!</p>
",https://stackoverflow.com/questions/64695993/invalidargumentexception-action-app-http-controllers-app-http-controllers-order,"['laravel', 'api', 'unit-testing', 'controller', 'laravel-8']",162,True,0,1
How to test UIFontMetrics UIFont.TextStyle in XCTest,"<p>How can I test the given <code>UIFont.TextStyle</code> for a <code>UIFont</code> with a dynamic font size via <code>UIFontMetrics</code> in <code>XCTest</code> unit testing?</p>
<pre class=""lang-swift prettyprint-override""><code>var myDynamicFont: UIFont {
    let font = UIFont(name: &quot;Font-Name&quot;, size: 42)
    return UIFontMetrics(forTextStyle: .largeTitle).scaledFont(for: font)
}
</code></pre>
<p><em>XCTest Unit Test:</em></p>
<pre class=""lang-swift prettyprint-override""><code>func testMyDynamicFont() {
    ...
    XCTAssertEqual(myDynamicFont.???, .largeTitle) // &lt;-- How to check the given TextStyle?
}
</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/65235232/how-to-test-uifontmetrics-uifont-textstyle-in-xctest,"['swift', 'unit-testing', 'xctest', 'uifont']",253,True,1,1
How to mock AWS Amplify in Jest?,"<p>I am creating an application with Vue and using Vue Test Utils and Jest as a unit testing framework. However, I encountered an issue in testing the scenario when it should show invalid credentials on failed login. I was wondering how to mock the Auth of AWS Amplify. I am not quite sure if I am doing the testing right because I am new to unit testing in frontend.</p>

<p>Login.vue:</p>

<pre><code>import { Auth } from 'aws-amplify'
import { required } from 'vuelidate/lib/validators'

export default {
  name: 'loginComponent',
  data() {
    return {
      form: {
        email: null,
        password: null,
      },
      authErrMsg: '',
      isShowAuthErr: false,
      isLoading: false,
    }
  },
  validations: {
    form: {
      email: { required },
      password: { required }
    }
  },
  methods: {
    validateState(name) {
      const { $dirty, $error } = this.$v.form[name];
      return $dirty ? !$error : null;
    },
    onSubmit() {
      this.$v.$touch();
      if (this.$v.$invalid) {
        return
      }

      this.isLoading = true
      this.isShowAuthErr = false
      const { email, password } = this.form
      Auth.signIn(email, password).then(() =&gt; {
          this.isLoading = false
          this.$store.dispatch('ACTION_SET_LOGGEDIN_STATUS', true)
          this.$router.push({ name: 'home' })
      }).catch(() =&gt; {
          this.isLoading = false
          this.authErrMsg = 'Invalid login credentials'
          this.$store.dispatch('ACTION_SET_LOGGEDIN_STATUS', false)
          this.isShowAuthErr = true
      })

    }
  }
}
</code></pre>

<p>Login.spec.js:</p>

<pre><code>import { mount, shallowMount, createLocalVue } from '@vue/test-utils'
import Login from '@/components/Login'
import BootstrapVue from 'bootstrap-vue'
import Vuelidate from 'vuelidate'
import Vuex from 'vuex'
import Auth from '@aws-amplify/auth'
import flushPromises from 'flush-promises'

const localVue = createLocalVue()
localVue.use(BootstrapVue)
localVue.use(Vuelidate)
localVue.use(Vuex)
localVue.use(Auth)

let wrapper
beforeEach(() =&gt; {
  wrapper = mount(Login, { localVue, 
    form: {
      email: null,
      password: null,
    }
  })
})

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

  it('should error message on failed login', async () =&gt; {
    wrapper.find('input[name=""email""]').setValue('email@gmail.com')
    wrapper.find('input[name=""password""]').setValue('123ABC')
    wrapper.find(""form"").trigger(""submit.prevent"")
    await flushPromises()
    Auth.signIn = jest.fn().mockImplementation(() =&gt; {
      throw new Error('Incorrect username or password.')
    });
    expect(Auth.signIn()).rejects.toThrow()
  })

})
</code></pre>

<p>Error I got:</p>

<blockquote>
  <p>TypeError: Cannot read property 'clientMetadata' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/62013004/how-to-mock-aws-amplify-in-jest,"['unit-testing', 'vue.js', 'jestjs', 'aws-amplify', 'vue-test-utils']",1958,False,1,0
Override class value,"<p>During unit testing, is it possible to change a class definition with a function?</p>
<p>The below code does not work.</p>
<pre><code>describe('Test Serializble',(){

    class Bar{}
    class Foo{}
    function setBarObjectProprietyOfFoo(){
        class Bar extends Serializable {
            id: string
        }

        class Foo extends Serializable {
            bar: Bar
        }
    }
    it('should not pass undefined',()=&gt;{
        setBarObjectProprietyOfFoo()
        const foo = Foo.fromJson(undefined)
        expect(foo).deep.equal(null)
    })
    it('should not pass null',()=&gt;{
        setBarObjectProprietyOfFoo()
        const foo = Foo.fromJson(null)
        expect(foo).deep.equal(null)
    })
})
</code></pre>
",https://stackoverflow.com/questions/63285949/override-class-value,"['javascript', 'node.js']",23,False,0,0
How to write mockito test for custom broadcast receiver,"<p>I have on custom broadcast receiver class which i'm using in multiple places in application, it is working fine. Now i want to write unit testing using mockito but i'm unable to achieve it. This custom broadcast is communicating with Bind Service. </p>

<p>I have followed some SO questions and google articles nothing help me out.</p>

<p>Following articles i have followed.</p>

<p><a href=""https://stackoverflow.com/questions/5769315/unit-testing-a-broadcast-receiver"">Unit testing broadcast receiver</a> </p>

<p><a href=""https://stackoverflow.com/questions/41172775/creating-intent-in-test-method-putextra-in-android-content-intent-not-mocked"">Unit testing for calling broadcast receiver</a></p>

<p>I have try booth but nothing worked.</p>

<p>Following code will tell how my custom broadcast receiver is.</p>

<pre><code>class CustomBroadcastReceiver(val onResultListener: OnResultListener) :
BroadcastReceiver() {

override fun onReceive(context: Context?, intent: Intent?) {
    when (intent!!.action) {
        Constants.STATUS_ONE -&gt; {
           onResultListener.connectionSuccess()
        }
        Constants.DATA_AVAILABLE -&gt; {                
            onResultListener.onDataAvailable(data)
        }
        Constants.GATT_READ -&gt; {
            onResultListener.onRead(readData)
        }}



interface OnResultListener {

    fun connectionSuccess()

    fun connectionFail(isFromConnection: Boolean, isFrom: String = Constants.DEFAULT)

    fun onDataAvailable(data: ArrayList&lt;Data&gt;)

    fun onCharacteristicRead(data:Data)}}
</code></pre>

<p>Above code is just sample i'm doing lot of work in this class, by implementing above interface in activities i'm getting data from receiver.</p>

<p>Everything is working fine but unable to write the mockito unit test, i'm new to mockito i know very little things about mockito,following are the mockito imports i'm using.</p>

<pre><code>testImplementation 'org.mockito:mockito-core:2.24.5'
androidTestImplementation 'org.mockito:mockito-core:2.24.5'
testImplementation ""com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0""
</code></pre>
",https://stackoverflow.com/questions/60775025/how-to-write-mockito-test-for-custom-broadcast-receiver,"['android', 'unit-testing', 'mockito', 'broadcastreceiver']",304,False,0,0
How to correctly unit test labels coming from transloco api in angular,"<p>I have been using Transloco API for a time but I have not been able to use it during unit testing.</p>

<p>I am following this blog from ngneat <a href=""https://netbasal.gitbook.io/transloco/general/unit-testing"" rel=""nofollow noreferrer"">Unit testing with transloco</a></p>

<p>But my simple test cases are also failing due to some reason with below error:</p>

<pre><code>Chrome 83.0.4103 (Windows 10.0.0) AppComponent should render title in a h1 tag FAILED
        Error: Expected ' page-heading! ' to contain 'Welcome to transloco-sample!'.
            at &lt;Jasmine&gt;
            at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/src/app/app.component.spec.ts:40:54)
            at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:308:1)
</code></pre>

<p>My config files and test suite are as follows :</p>

<blockquote>
  <p>transloco-root.module.ts</p>
</blockquote>

<pre><code>import { HttpClient } from '@angular/common/http';
import {
  TRANSLOCO_LOADER,
  Translation,
  TranslocoLoader,
  TRANSLOCO_CONFIG,
  translocoConfig,
  TranslocoModule
} from '@ngneat/transloco';
import { Injectable, NgModule } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
  constructor(private http: HttpClient) { }

  getTranslation(lang: string) {
    return this.http.get&lt;Translation&gt;(`/assets/i18n/${lang}.json`);
  }
}

@NgModule({
  exports: [TranslocoModule],
  providers: [
    {
      provide: TRANSLOCO_CONFIG,
      useValue: translocoConfig({
        availableLangs: ['fr', 'en'],
        defaultLang: 'en',
        // Remove this option if your application doesn't support changing language in runtime.
        reRenderOnLangChange: true,
        prodMode: environment.production,
      })
    },
    { provide: TRANSLOCO_LOADER, useClass: TranslocoHttpLoader }
  ]
})
export class TranslocoRootModule { }
</code></pre>

<blockquote>
  <p>app.component.html</p>
</blockquote>

<pre><code>&lt;div style=""text-align:center""&gt;
  &lt;h1&gt;
    {{ 'page-heading' | transloco }}!
  &lt;/h1&gt;
&lt;/div&gt;
</code></pre>

<blockquote>
  <p>transloco-testing.module.ts</p>
</blockquote>

<pre><code>import { TranslocoTestingModule, TranslocoConfig } from '@ngneat/transloco';
import * as en from '../assets/i18n/en.json';
import * as fr from '../assets/i18n/fr.json';

export function getTranslocoModule(config: Partial&lt;TranslocoConfig&gt; = {}) {
    return TranslocoTestingModule.withLangs(
        { en, fr },
        {
            availableLangs: ['en', 'fr'],
            defaultLang: 'en',
            ...config
        }
    );
}
</code></pre>

<p>and </p>

<p>test suite as</p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { getTranslocoModule } from './transloco-testing.module';
import { LangDropDownComponent } from './lang-drop-down/lang-drop-down.component';

fdescribe('AppComponent', () =&gt; {

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        getTranslocoModule()
      ],
      declarations: [
        AppComponent, LangDropDownComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

  it('should render title in a h1 tag', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    console.log(compiled.querySelector('h1').textContent);
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to transloco-sample!');
  });
});
</code></pre>

<blockquote>
  <p>Also, en.json</p>
</blockquote>

<pre><code>{
    ""application"": ""Transloco - Sample "",
    ""title"": ""Testing Transloco"",
    ""para-title"": ""Here are some links to help you start: "",
    ""page-heading"": ""Welcome to Transloco App"",
    ""client"": {
        ""name"": ""Name""
    }
}
</code></pre>

<p>I also have the following options in tsconfig.json:</p>

<p>""resolveJsonModule"": true,
""esModuleInterop"": true</p>

<p>Can anyone suggest something?</p>
",https://stackoverflow.com/questions/62322437/how-to-correctly-unit-test-labels-coming-from-transloco-api-in-angular,"['angular', 'unit-testing', 'transloco']",2566,True,1,1
How to unit test search functionality?,"<p>First off, i'm just new to unit testing or testing in general so i'm still wrapping my head around some concepts. Already got the basic of unit testing and I'm also currently learning about rxjs marble testing, so currently i'm stuck on how to test searching w/c functions the same way with the code in the documentation.</p>
<p>So Let's use the code from the tour of heroes in angular documentation</p>
<pre><code>this.heroes$ = this.searchTerms.pipe(
  // wait 300ms after each keystroke before considering the term
  debounceTime(300),

  // ignore new term if same as previous term
  distinctUntilChanged(),

  // switch to new search observable each time the term changes
  switchMap((term: string) =&gt; this.heroService.searchHeroes(term)),
);
</code></pre>
<p>Here's my current test looks like</p>
<pre><code>const searchResults$ = (inputs$: Observable&lt;string&gt;) =&gt;
  inputs$.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    switchMap((term: string) =&gt; fakeHeroService.searchHeroes(term))
  );

  it('should return the correct results', () =&gt; {
    scheduler.run(helpers =&gt; {
      const { cold, hot, expectObservable } = helpers;

      // these are the search terms typed by user, observable
      // emitted by this.searchTerms
      const inputMarbles = '^-a 300ms b-c 300ms';

      // each emitted response by each service call
      const outputMarbles = '-- 300ms a-- 300ms c';

      // verify that service is called N times
      // verify that it's passed with certain argument per run


      searchServiceSpy = spyOn(heroService, 'searchHeroes').and.returnValue(
        cold(outputMarbles)
      );
      const source$ = hot(inputMarbles);

      const output$ = source$.pipe(searchResults$);

      expectObservable(output$).toBe(outputMarbles);

      /* expect(fakeSearchService.getMatches).toHaveBeenCalledTimes(2); */
    });
  });
</code></pre>
<p>I just can't get it working.</p>
",https://stackoverflow.com/questions/62849543/how-to-unit-test-search-functionality,"['angular', 'unit-testing', 'jasmine', 'tdd']",1367,True,0,1
How do I write a UI test in Swift to test whether a label becomes visible if a button is tapped on?,"<p>I am a total beginner in both Swift and UI/Unit testing. </p>

<p>The goal is to test if a label is visible when a view is tapped on. Yes, a view.
The problem is that my 'button' is a UIView class and my label is an @IBInspectable computed property inside of this UIView class. So, I am kind of perplexed about how I test. </p>

<p>Would appreciate any recommendations on where I can find nice explanations about UI/Unit Testing in general. :) Thanks!</p>
",https://stackoverflow.com/questions/59895893/how-do-i-write-a-ui-test-in-swift-to-test-whether-a-label-becomes-visible-if-a-b,"['ios', 'swift', 'ui-testing']",788,False,0,1
python - mock module AND the method,"<p>I'm writing a unit test for aws serverless using lambda layers.
I need to run test in a CI/CD. This means, the layer - utils.py module is NOT available during the test.
I need to:</p>
<ol>
<li>mock MODULE</li>
<li>mock METHOD calls on module level</li>
<li>mock METHOD calls on method level</li>
<li>mock decorators</li>
</ol>
<p>How do I do that? Thanks.</p>
<p>I've been running unit test successfully but the module has to be available during the unit testing.</p>
<pre><code>#functional module func_module.py
from app.lib_common import utils
log_level = utils.get_logging_level()

@utils.log_performance
def lambda_handler()
   utils.get_code('abc')
</code></pre>
<p>Module that's NOT AVAILABLE during the unit testing:</p>
<pre><code># utils.py

# regular function
def get_code(input)
    return input + 'def'

# method called from class level
def get_logging_level():
    return 1

# wrapper function
def log_performance(func):
'''Decorator to log the amount of time it takes for a function to execute.'''
if not callable(func):
    raise ValueError('This method is to be used as a decorator only.')
    def wrapper_func(*func_args, **func_kwargs):
        start_time = time.time()
        result = func(*func_args, **func_kwargs)
        elapsed_time = time.time() - start_time
        logger.info(f'Elapsed time: {time.strftime(&quot;%H:%M:%S&quot;, time.gmtime(elapsed_time))}')
        return result
    return wrapper_func
</code></pre>
<p>And the unit test:</p>
<pre><code># test.py
import func_module
from unittest.mock import patch
from unittest.mock import Mock
sys.modules['utils'] = Mock()

class Test_Get_By_Entity(unittest.TestCase):
    @patch('app.lib_common.utils', autospec=True, spec_set=True)
    def test_cam_get_by_entity_event_none_return_400(self, mock_utils):
        mock_utils.get_code = {}
        mock_utils.get_loggging_level.return_value = 3
        response = func_module.lambda_handler()
        self.assertEqual(response['statusCode'], 200)
</code></pre>
",https://stackoverflow.com/questions/64212700/python-mock-module-and-the-method,"['python', 'amazon-web-services', 'unit-testing', 'python-unittest.mock']",132,False,1,0
How to unit test Durable Functions with errors and retry,"<p>I've read these two Microsoft documentation on Unit Testing and Error Handling</p>

<p>Unit testing:
<a href=""https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-unit-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-unit-testing</a></p>

<p>Error handling - with the retry
<a href=""https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-error-handling?tabs=csharp"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-error-handling?tabs=csharp</a></p>

<p>What I am trying to do in my unit test the following:</p>

<p>1) have activity throw exception</p>

<p>2) verify Orchestrator will call <code>CallActivityRetryAsync</code> based on my retry options, e.g. 3 times</p>

<p>3) verify my try/catch block catches the exception once and my error handler is called. (aside: is the exception wrapped in a <code>FunctionFailedException</code>?) </p>

<p>So for example, based on the MS documentation, if this is my orchestrator:</p>

<pre><code>    [FunctionName(""E1_HelloSequence"")]
    public static async Task&lt;List&lt;string&gt;&gt; Run(
        [OrchestrationTrigger] IDurableOrchestrationContext context)
    {
    try
    {
        var outputs = new List&lt;string&gt;();
        var retryOptions = new RetryOptions(
                firstRetryInterval: TimeSpan.FromSeconds(5),
                maxNumberOfAttempts: 3);


        outputs.Add(await context.CallActivityRetryAsync&lt;string&gt;(""E1_SayHello"", retryOptions, ""Tokyo""));
        outputs.Add(await context.CallActivityRetryAsync&lt;string&gt;(""E1_SayHello"", retryOptions, ""Seattle""));


        // returns [""Hello Tokyo!"", ""Hello Seattle!""]
        return outputs;
    }
    catch (Exception ex)
    {
            await context.CallActivityAsync&lt;string&gt;(""E1_SayHello"", ""I Failed...""));
            throw;
    }
    }

    [FunctionName(""E1_SayHello"")]
    public static string SayHello([ActivityTrigger] IDurableActivityContext context)
    {
        string name = context.GetInput&lt;string&gt;();
        return $""Hello {name}!"";
    }
</code></pre>

<p>And my test would be something like this:</p>

<pre><code>public class HelloSequenceTests
{
    [Fact]
    public async Task Run_returns_multiple_greetings()
    {
        var mockContext = new Mock&lt;IDurableOrchestrationContext&gt;();
        mockContext.Setup(x =&gt; x.CallActivityRetryAsync&lt;string&gt;(""E1_SayHello"", ""Tokyo"")).ReturnsAsync(""Hello Tokyo!"");
        mockContext.Setup(x =&gt; x.CallActivityRetryAsync&lt;string&gt;(""E1_SayHello"", ""Seattle"")).ReturnsAsync(""Hello Seattle!"");

        var result = await HelloSequence.Run(mockContext.Object);

        Assert.Equal(2, result.Count);
        Assert.Equal(""Hello Tokyo!"", result[0]);
        Assert.Equal(""Hello Seattle!"", result[1]);
    }
}
</code></pre>

<p>So in the example above, how would I</p>

<p>1) have the Activity <code>E1_SayHello</code> thrown an exception</p>

<p>2) verify that there were 3 retries</p>

<p>3) verify that my catch block executed once?</p>
",https://stackoverflow.com/questions/62306462/how-to-unit-test-durable-functions-with-errors-and-retry,"['c#', 'unit-testing', 'azure-functions', 'moq', 'azure-durable-functions']",990,False,1,0
Tests not working for multiple datasource with spring boot liquibase,"<p>I am creating unittesting for spring boot application having multiple datasources. (Configuration is heavily inspired from <a href=""https://stackoverflow.com/a/43541844/1534925"">this</a> answer)</p>

<blockquote>
<pre><code>@Configuration
public class DatasourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = ""datasource.primary"")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = ""datasource.primary.liquibase"")
    public LiquibaseProperties primaryLiquibaseProperties() {
        return new LiquibaseProperties();
    }

    @Bean
    public SpringLiquibase primaryLiquibase() {
        return springLiquibase(primaryDataSource(), primaryLiquibaseProperties());
    }

    @Bean
    @ConfigurationProperties(prefix = ""datasource.secondary"")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = ""datasource.secondary.liquibase"")
    public LiquibaseProperties secondaryLiquibaseProperties() {
        return new LiquibaseProperties();
    }

    @Bean
    public SpringLiquibase secondaryLiquibase() {
        return springLiquibase(secondaryDataSource(), secondaryLiquibaseProperties());
    }

    private static SpringLiquibase springLiquibase(DataSource dataSource, LiquibaseProperties properties) {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setDataSource(dataSource);
        liquibase.setChangeLog(properties.getChangeLog());
        liquibase.setContexts(properties.getContexts());
        liquibase.setDefaultSchema(properties.getDefaultSchema());
        liquibase.setDropFirst(properties.isDropFirst());
        liquibase.setShouldRun(properties.isEnabled());
        liquibase.setLabels(properties.getLabels());
        liquibase.setChangeLogParameters(properties.getParameters());
        liquibase.setRollbackFile(properties.getRollbackFile());
        return liquibase;
    }


...

}
</code></pre>
</blockquote>

<p>and</p>

<blockquote>
<pre><code>datasource:
  primary:
    url: jdbc:mysql://localhost/primary
    username: username
    password: password
    liquibase:
      change-log: classpath:/db/changelog/db.primary.changelog-master.xml
  secondary:
    url: jdbc:mysql://localhost/secondary
    username: username
    password: password
    liquibase:
      change-log: classpath:/db/changelog/db.secondary.changelog-master.xml
</code></pre>
</blockquote>

<p>The application is running properly. </p>

<p>The problem is unit testing is failing with this configuration. I have used <code>h2</code> as embedded DB. Added h2 as test dependency and added h2 in datasource URL as well in application.yaml for testing.</p>

<p>application.yaml for testing</p>

<pre><code>management:
  endpoints.web.exposure.include: ""*""
  security.enabled: false
spring:
  zipkin:
    discoveryClientEnabled: false
    sender:
      type: kafka
      #type: web
  liquibase:
    enabled: false
  datasource:
    url: ""jdbc:h2:mem:testdb""
    jdbc-url: ""jdbc:h2:mem:testdb""
    username: sa
    password:
  secondary-datasource:
    url: ""jdbc:h2:mem:testdb""
    jdbc-url: ""jdbc:h2:mem:testdb""
    username: sa
    password:
datasource:
 primary-liquibase:
   liquibase:
     url: ""jdbc:h2:mem:testdb""
     username: sa
     password:
 secondary-liquibase:
   liquibase:
     url: ""jdbc:h2:mem:testdb""
     username: sa
     password:
liquibase:
  enable: false
</code></pre>

<p>Unit testing file</p>

<pre><code>package com.foo.bar.car;

import com.foo.bar.car.utils.KSUIDGenerator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureTestDatabase
// https://stackoverflow.com/a/58786742/1534925
//@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
//@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
class CarApplicationTests {

    @Test
    public void contextLoads() {
        String h = ""Hello World!"";
        Assertions.assertEquals(h, ""Hello World!"");
    }

    @Test
    public void testKSUIDGeneration() {
        Assertions.assertNotNull(KSUIDGenerator.generateKSUID());
    }
}
</code></pre>

<p>I have created a <a href=""https://github.com/akshayat/multidatasource/"" rel=""nofollow noreferrer"">repository</a> to demonstrate this. </p>

<p>When I do <code>gradlew clean check</code> it gives me following error</p>

<pre><code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [liquibase.integration.spring.SpringLiquibase]: Factory method 'primaryLiquibase' threw exception; nested exception is java.lang.IllegalArgumentException: No visible constructors in class org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean
</code></pre>

<p>Not sure what configuration change I am missing. </p>
",https://stackoverflow.com/questions/61123061/tests-not-working-for-multiple-datasource-with-spring-boot-liquibase,"['spring-boot', 'unit-testing', 'liquibase', 'spring-boot-test']",1300,True,1,1
CMock mock some functions but not others from same module,"<pre><code>//myfuncs.h
void func1(void);

void func2(void;
</code></pre>

<p>I'm doing unit testing. Using CMock with ceedling, is there any way to mock func1(), but run func2() as it was originally written?</p>
",https://stackoverflow.com/questions/60972043/cmock-mock-some-functions-but-not-others-from-same-module,"['c', 'unit-testing', 'cmock', 'ceedling']",697,True,0,1
Mocha Unit Testing: Uncaught TypeError: Cannot read property &#39;apply&#39; of undefined,"<p>I want to write unit testing for Restful Endpoint, but whenever I run npm test. I get the error  Uncaught TypeError: Cannot read property 'apply' of undefined .</p>
<pre><code>let chai = require('chai')
let chaiHttp = require('chai-http')
let home = require('../routes/home')
let user = require('../routes/users')
//Assertion Style
chai.should()

chai.use(chaiHttp)

describe('chow Api', () =&gt; {
  //  users
    describe(&quot;GET /api/chow/home&quot;, () =&gt; {
        it('it should render Welcome to Homepage', (done) =&gt;{
            chai.request(home)
            .get(&quot;/api/chow/home&quot;)
            .end((err, response) =&gt;{
                response.should.have.status(200)
                response.body.should.be('string')
                done()
            })
        })
    })

    describe('GET /api/chow/users', () =&gt; {
        it('it should GET all the users', (done) =&gt; {
            chai.request(user)
            .get(&quot;/api/chow/users&quot;)
            .end((err, response) =&gt;{
                response.should.have.status(200)
                response.should.be.a('array')
                done()
            })
        })
    })
})
</code></pre>
",https://stackoverflow.com/questions/65419488/mocha-unit-testing-uncaught-typeerror-cannot-read-property-apply-of-undefine,"['javascript', 'node.js', 'testing']",3432,True,4,3
What&#39;s the difference between the JUnit and the TestNG,"<p>Both Testng and Junit are Testing framework used for Unit Testing. So what are the diffrences and advantages of JUnit and the TestNG?</p>
",https://stackoverflow.com/questions/63965963/whats-the-difference-between-the-junit-and-the-testng,"['junit', 'testng']",170,True,0,1
H2 schema disappears after connection is closed,"<p>after setting up a schema in an H2 database for unit testing, the unit tests relying on the schema could not find it.</p>

<pre><code>import java.sql.DriverManager
Class.forName(""org.h2.Driver"")

val setupConn = DriverManager.getConnection(""jdbc:h2:mem:test_data_metrics;MODE=PostgreSQL"", ""sa"", """")
val setupStmt = setupConn.createStatement

// setup schema at the beginning of our test
setupStmt.execute(""CREATE SCHEMA IF NOT EXISTS my_test_schema AUTHORIZATION sa;"")
setupStmt.execute(""GRANT ALL ON SCHEMA my_test_schema TO sa;"")
setupStmt.execute(""CREATE TABLE IF NOT EXISTS my_test_schema.my_test_table (test_id VARCHAR(255), test_column VARCHAR(255));"")
setupStmt.executeQuery(""select * from my_test_schema.my_test_table"")
// res4: java.sql.ResultSet = rs3: org.h2.result.LocalResultImpl@3eb10d62 columns: 2 rows: 0 pos: -1
// this seems to work correctly ^^^

setupStmt.close
setupConn.close

// now run our test using the schema we just set up
val conn = DriverManager.getConnection(""jdbc:h2:mem:test_data_metrics;SCHEMA=my_test_schema;MODE=PostgreSQL"", ""sa"", """")
val stmt = conn.createStatement

stmt.executeQuery(""select * from my_test_table where test_id = '1'"")
// org.h2.jdbc.JdbcSQLSyntaxErrorException: Schema ""MY_TEST_SCHEMA"" not found; SQL statement:
// SET SCHEMA my_test_schema [90079-200]
// ^^^^ something has gone horribly wrong
</code></pre>
",https://stackoverflow.com/questions/61281393/h2-schema-disappears-after-connection-is-closed,"['sql', 'scala', 'h2']",466,True,0,2
java.lang.IllegalStateException: Failed to load ApplicationContext in spring JPA unit test,"<p>I am newbie in spring when i try to run unit testing for github project it doesn't work and 
    give me this exception.  </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.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
            at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
            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$4.run(ParentRunner.java:331)
            at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
            at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
            at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
            at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
            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$3.evaluate(ParentRunner.java:306)
            at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
            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 'entityManagerFactory' defined in com.guitar.db.config.JpaConfiguration: Invocation of init method failed; nested exception is org.hibernate.cfg.beanvalidation.IntegrationException: Error activating Bean Validation integration
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
            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.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
            at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
            at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
            at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
            at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
            at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
            at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
            at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
            at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
            ... 25 more
        Caused by: org.hibernate.cfg.beanvalidation.IntegrationException: Error activating Bean Validation integration
            at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:154)
            at org.hibernate.internal.SessionFactoryImpl.&lt;init&gt;(SessionFactoryImpl.java:312)
            at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
            at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852)
            at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845)
            at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
            at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)
            at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
            at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
            at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
            at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
            ... 40 more
        Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/ValidationException
            at java.base/java.lang.ClassLoader.defineClass1(Native Method)
            at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
            at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
            at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
            at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
            at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
            at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
            at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
            at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
            at org.hibern`enter code here`ate.validator.internal.engine.ConfigurationImpl.&lt;init&gt;(ConfigurationImpl.java:110)
            at org.hibernate.validator.internal.engine.ConfigurationImpl.&lt;init&gt;(ConfigurationImpl.java:86)
            at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:41)
            at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:276)
            at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:110)
            at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:459)
            at org.hibernate.cfg.beanvalidation.TypeSafeActivator.activate(TypeSafeActivator.java:97)
            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:567)
            at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:148)
            ... 52 more
        Caused by: java.lang.ClassNotFoundException: javax.xml.bind.ValidationException
            at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
            at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
            at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
            ... 73 more

</code></pre>
",https://stackoverflow.com/questions/62301440/java-lang-illegalstateexception-failed-to-load-applicationcontext-in-spring-jpa,"['spring', 'unit-testing', 'spring-data-jpa']",84,False,0,0
"Check if a function has been called, Angular unit testing","<p>I have called a function inside ngOnInit,</p>

<pre><code>ngOnInit() {
 this.isSubscribable();
}
</code></pre>

<p>I wan to do unit testing for this ngOnInit like this:</p>

<pre><code>    it('Check isSubscribable is called from ngOnInit', async(async() =&gt; {
      spyOn(component, 'isSubscribable').and.callThrough();
      fixture.detectChanges();
      await fixture.whenStable();
      expect(component.isSubscribable).toHaveBeenCalled();

    }))
</code></pre>

<p>This is not working. I need some help on this.</p>
",https://stackoverflow.com/questions/59820272/check-if-a-function-has-been-called-angular-unit-testing,"['angular', 'jasmine']",4254,True,4,2
Android Unit Test ViewModel Wanted but not invoked,"<p>I'm new on unit testing. I'm trying to do unit testing on my view model class but my test fail with error:</p>
<p><em>Wanted but not invoked:
toggleMovieFavorite.invoke(
Movie(id=1, title=Title, overview=Overview, releaseDate=01/01/2025, posterPath=, backdropPath=, originalLanguage=ES, originalTitle=Title, popularity=5.0, voteAverage=7.0, favorite=false)
);
-&gt; at xyz.jonthn.usescases.ToggleMovieFavorite.invoke(ToggleMovieFavorite.kt:7)
Actually, there were zero interactions with this mock.</em></p>
<p>This is my test file</p>
<pre><code>@RunWith(MockitoJUnitRunner::class)
class DetailViewModelTest {

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Mock
    lateinit var findMovieById: FindMovieById

    @Mock
    lateinit var toggleMovieFavorite: ToggleMovieFavorite

    @Mock
    lateinit var observer: Observer&lt;Movie&gt;

    private lateinit var vm: DetailViewModel

    @ExperimentalCoroutinesApi
    @Before
    fun setUp() {

        Dispatchers.setMain(Dispatchers.Unconfined)

        vm = DetailViewModel(1, findMovieById, toggleMovieFavorite, Dispatchers.Unconfined)
    }

    @ExperimentalCoroutinesApi
    @After
    fun tearDown() {
        Dispatchers.resetMain()
    }

    @Test
    fun `when favorite clicked, the toggleMovieFavorite use case is invoked`() {
        runBlocking {

            val movie = mockedMovie.copy(id = 1)

            whenever(findMovieById.invoke(1)).thenReturn(movie)

            whenever(toggleMovieFavorite.invoke(movie)).thenReturn(movie.copy(favorite = !movie.favorite))

            vm.movie.observeForever(observer)

            vm.onFavoriteClicked()

            verify(toggleMovieFavorite).invoke(movie)
        }
    }

    val mockedMovie = Movie(
    0,
    &quot;Title&quot;,
    &quot;Overview&quot;,
    &quot;01/01/2025&quot;,
    &quot;&quot;,
    &quot;&quot;,
    &quot;ES&quot;,
    &quot;Title&quot;,
    5.0,
    7.0,
    false)
}   
</code></pre>
<p>This is my DetailViewModel:</p>
<pre><code>class DetailViewModel(
private val movieId: Int, private val findMovieById: FindMovieById,
private val toggleMovieFavorite: ToggleMovieFavorite,
uiDispatcher: CoroutineDispatcher) : ScopedViewModel(uiDispatcher) {

private val _movie = MutableLiveData&lt;Movie&gt;()
val movie: LiveData&lt;Movie&gt; get() = _movie

init {
    launch {
        _movie.value = findMovieById.invoke(movieId)
    }
}

fun onFavoriteClicked() {
    launch {
        movie.value?.let {
            _movie.value = toggleMovieFavorite.invoke(it)
        }
    }
}
</code></pre>
<p>}</p>
<p>And my use case ToggleMovieFavorite:</p>
<pre><code> class ToggleMovieFavorite(private val moviesRepository: MoviesRepository) {
    suspend fun invoke(movie: Movie): Movie = with(movie) {
        copy(favorite = !favorite).also { moviesRepository.update(it) }
    }
    }
</code></pre>
<p>Thank you so much for your help guys!!!</p>
",https://stackoverflow.com/questions/64131157/android-unit-test-viewmodel-wanted-but-not-invoked,"['android', 'unit-testing', 'mockito', 'android-viewmodel']",393,True,0,1
MarkLogic unit test not running any tests,"<p>I thought it would be a good idea to set up MarkLogic unit testing, so I've been following the <a href=""https://github.com/marklogic-community/ml-gradle/tree/master/examples/unit-test-project"" rel=""nofollow noreferrer"">unit-test-project</a> as best as I can. Everything seems to work, but no unit tests are being performed. I've copied the four unit tests to <code>src/test/ml-modules/root/suites/My Tests</code> and the one module to <code>src/main/ml-modules/root/</code>. Everything deploys correctly. But running the unit tests gives me:</p>
<pre><code>$ gradle mlUnitTest

&gt; Task :mlUnitTest
Constructing DatabaseClient that will connect to port: 8021
Run teardown scripts: true
Run suite teardown scripts: true
Run code coverage: false
Running all suites...
Done running all suites; time: 1791ms


0 tests completed, 0 failed
</code></pre>
<p>The unit testing UI loads in a browser, but it also displays no tests.</p>
<p>This is my <code>build.gradle file</code>:</p>
<pre><code>buildscript {
  repositories {
    jcenter()
    mavenLocal()
  }
  dependencies {
    classpath &quot;com.marklogic:marklogic-unit-test-client:1.0.0&quot;
    classpath &quot;com.marklogic:ml-gradle:4.1.0&quot;
  }
}
plugins { id &quot;com.marklogic.ml-gradle&quot; version &quot;4.1.0&quot; }
repositories {
  jcenter()
}
dependencies {
  mlBundle &quot;com.marklogic:marklogic-unit-test-modules:1.0.0&quot;
}
</code></pre>
<p>And <code>gradle.properties</code>:</p>
<pre><code>mlAppName=unitTestApp
mlHost=localhost
mlUsername=admin
mlPassword=*****
mlRestPort=8020
mlTestRestPort=8021
mlModulePaths=src/main/ml-modules,src/test/ml-modules
</code></pre>
<p>I'm using MarkLogic 10, on 64 bit Linux, ml-gradle 4.0</p>
",https://stackoverflow.com/questions/64722637/marklogic-unit-test-not-running-any-tests,"['unit-testing', 'marklogic', 'ml-gradle', 'marklogic-10']",119,True,2,1
How to test methods in eclipse through JUnit?,"<p>I just learned the the unit testing this week and I'm supposed to find the at least a bug in the following piece of code. I have done some unit testing, but I'm not sure how I can actually find the bug. Every test that I have done has turned out correct so far. If someone can help me by showing me how I'm supposed to find the bug, I would greatly appreciate in advance.</p>

<p>The give code is:</p>

<pre><code> import java.util.Calendar;
 public class Time {





  private static final int SECONDS_PER_MINUTE = 60;
  private static final int MINUTES_PER_HOUR = 60;
  private static final int SECONDS_PER_HOUR = 3600;
  private static final int HOURS_PER_DAY = 24;



  private int hours;
  private int minutes;
  private int seconds;


  /**
   * Creates a Time object representing the current time.
   */
  public Time()
  {
    Calendar now = Calendar.getInstance();

    hours = now.get(Calendar.HOUR_OF_DAY);
    minutes = now.get(Calendar.MINUTE);
    seconds = now.get(Calendar.SECOND);
  }


  /**
   * Creates a Time object representing a user-specified time.
   *
   * Note that the hours component must be specified using the
   * 24-hour clock.
   *
   * @param h hours
   * @param m minutes
   * @param s seconds
   *
   */
  public Time(int h, int m, int s)
  {

      setHours(h);
      setMinutes(m);
      setSeconds(s);
  }


  /**
   * Creates a Time object representing a user-specified time.
   *
   * The time is supplied as a string containing two integer values
   * representing hours and minutes or three integer values representing
   * hours, minutes and seconds, hours being specified using the 24-hour
   * clock in either case. The values must be separated from each other by
   * a colon.
   *
   * @param timeString string containing hours, minutes and seconds
   * 
   */
  public Time(String timeString)
  {
    String[] parts = timeString.split("":"");
    if (parts.length &lt; 2 || parts.length &gt; 3) {

        System.out.println(""invalid time "");
    }
    else{

    setHours( Integer.parseInt(parts[0]));
    setMinutes( Integer.parseInt(parts[1]));
    setSeconds( Integer.parseInt(parts[2]));
    }
  }


  /**
   * @return Hours component of this time
   */
  public int getHours()
  {
    return hours;
  }


  /**
   * @return Minutes component of this time
   */
  public int getMinutes()
  {
    return minutes;
  }


  /**
   * @return Seconds component of this time
   */
  public int getSeconds()
  {
    return seconds;
  }


  /**
 * @param hours the hours to set
 */
public void setHours(int hours) {
    if (hours &lt; 0 || hours &gt; HOURS_PER_DAY) {
       //System.out.println(""invalid  hours number"");
        this.hours = 1;
    }
    else{
        this.hours = hours;
    }

}


/**
 * @param minutes the minutes to set
 */
public void setMinutes(int minutes) {
    if (minutes &lt; 0 || minutes &gt;= MINUTES_PER_HOUR){
        //System.out.println(""invalid  minutes number"");
        this.minutes = 1;
    }
    else{
        this.minutes = minutes;
    }

}


/**
 * @param seconds the seconds to set
 */
public void setSeconds(int seconds) {
    if (seconds &lt; 0 || seconds &gt;= SECONDS_PER_MINUTE) {
        //System.out.println(""invalid  seconds number"");
        this.seconds = 1;
    }
    else{
    this.seconds = seconds;
    }
}


/**
   * Formats this time as a string containing hours, minutes and seconds.
   *
   * Leading zeroes are added to values if necessary and components are
   * separated from each other by a colon.
   *
   * @return String representation of this time
   */
   public String getTimeString()
  {
    return String.format(""%02d:%02d:%02d"", getHours(), getMinutes(), getSeconds());
  }


  /**
   * Expresses this time as a single integer value - the number of seconds
   * since midnight.
   *
   * @return Number of seconds
   */
  public int inSeconds()
  {
    int hourSec = SECONDS_PER_HOUR * hours;
    int minSec = SECONDS_PER_MINUTE * minutes;
    return hourSec + minSec + seconds;
  }


  /**
   * Creates a Time object advanced in time relative to this one by
   * a user-specified number of seconds.
   *
   * @param sec number of seconds to advance
   * @return String object advanced in time relative to this one
   * 
   */
  public String getTimePlus(int sec)
  {
      int h = 0;
      int m = 0;
      int s = 0;
      int future = 0;
      int remainder = 0;
    if (sec &lt; 0) {
     System.out.println(""invalid number of seconds"");
    }
    else {
       future = this.inSeconds() + sec;
       h = (future / SECONDS_PER_HOUR) % HOURS_PER_DAY;
       remainder = future % SECONDS_PER_HOUR;
       m = remainder / SECONDS_PER_MINUTE;
       s = remainder % SECONDS_PER_MINUTE;

    }
    return String.format(""%02d:%02d:%02d"",h, m, s);
  }

}
</code></pre>

<p>The test code that I have written is:</p>

<pre><code> import static org.junit.jupiter.api.Assertions.*;

 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;

class TestTime {
 private Time test;
@BeforeEach
void setUp() throws Exception {
    test = new Time(2, 45, 23);
}

@AfterEach
void tearDown() throws Exception {
    test = null;
}

@Test
public void constructorHourNegativeNegative() {
    Time t = new Time(-1, 35, 40);
    assertEquals(1, t.getHours());
}

@Test
public void constructorHourNegativeAbove24() {
    Time t = new Time(25, 45, 30);
    assertEquals(1, t.getHours());
}

@Test
public void constructorHourBoundary() {
    Time t = new Time(0, 45, 30);
    assertEquals(0, t.getHours());
}

@Test
public void constructorHourPositive() {
    Time t = new Time(12, 45, 30);
    assertEquals(12, t.getHours());
}

@Test
public void constructorMinutesNegativeNegative() {
    Time t = new Time(11, -1, 30);
    assertEquals(1, t.getMinutes());
}

@Test
public void constructorMinutesNegativeEdge() {
    Time t = new Time(11, 60, 30);
    assertEquals(1, t.getMinutes());
}

@Test
public void constructorMinutesBoundary() {
    Time t = new Time(11, 0, 30);
    assertEquals(0, t.getMinutes());
}

@Test
public void constructorMinutePositive() {
    Time t = new Time(11, 38, 30);
    assertEquals(38, t.getMinutes());
}

@Test
public void constructoSecondsNegativeNegative() {
    Time t = new Time(11, 24, -1);
    assertEquals(1, t.getSeconds());
}

@Test
public void constructoSecondsNegativeEdge() {
    Time t = new Time(11, 24, 60);
    assertEquals(1, t.getSeconds());
}

@Test
public void constructoSecondsBoundary() {
    Time t = new Time(11, 24, 59);
    assertEquals(59, t.getSeconds());
}

@Test
public void constructorSecondsPositive() {
    Time t = new Time(11, 24, 30);
    assertEquals(30, t.getSeconds());
}
}
</code></pre>
",https://stackoverflow.com/questions/61789725/how-to-test-methods-in-eclipse-through-junit,"['java', 'unit-testing', 'junit']",58,False,0,1
how to unittest in python for a logger function,"<p>I am new to unit testing in Python, So I am thinking to start with this snippet, how I can unit test this function? </p>

<pre><code>def log():

    log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')

    logFile = './df_logger.log'

    handler = RotatingFileHandler(logFile, mode='a', maxBytes=1*1024*1024*1024, 
                                 backupCount=2, encoding=None, delay=0)

    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(log_formatter)
    handler.setFormatter(log_formatter)
    handler.setLevel(logging.INFO)

    logger = logging.getLogger('root')
    logger.setLevel(logging.INFO)

    logger.addHandler(handler)
    logger.addHandler(console_handler)
    return logger
</code></pre>
",https://stackoverflow.com/questions/59732816/how-to-unittest-in-python-for-a-logger-function,"['python', 'unit-testing']",421,False,0,1
Is it possible to test a js function which returns nothing with chai?,"<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>async executeEventEndSuccess(statusData) {
        if (storageType.toUpperCase() !== common.Blob) {
            let appStatus = status.getStatus(statusData.tenantId, statusData.viewerId, statusData.excutionId);
            uploadHelper.renameFileOnEndEvent(statusData.tenantId, statusData.viewerId, statusData.excutionId);
            appStatus.forEach(async ele =&gt; {
                if (ele.executionID === parseInt(statusData.excutionId) &amp;&amp; ele.tenant === statusData.tenantId &amp;&amp; ele.panel === statusData.viewerId &amp;&amp; ele.tableName === common.type.panelWatch) {
                    try {
                        const updateDataPanelStatus = await panelStatusData.updatePanelStatus(statusData.tenantId, statusData.viewerId, ele.path)
                        eventRepo.updatePanelStatus(statusData.tenantId, statusData.viewerId, updateDataPanelStatus);
                    }
                    catch (error) {
                        throw error;
                    }
                };
            });
        }

        try {
            console.log(statusData.tenants);
            
            await eventRepo.executeEndProcedure(statusData);
        }
        catch (error) {
            throw error;
        }
    }</code></pre>
</div>
</div>
</p>

<p>Here i need to test whether appStatus is existing in my executeEventEndSuccess function or not? I need to perform unit testing for this function??</p>
",https://stackoverflow.com/questions/59630397/is-it-possible-to-test-a-js-function-which-returns-nothing-with-chai,"['javascript', 'function', 'unit-testing', 'chai']",89,False,0,1
Pytest coverage.py errror,"<p>I unit testing python code and running command <code>pytest --cov</code>, test is running fine but coverage is not getting displayed and error is </p>

<pre><code>INTERNALERROR&gt;raise CoverageException(""Couldn't use data file {!r}:{}"".format(self.filename, msg))
INTERNALERROR&gt; coverage.misc.CoverageException: Couldn't use data file'C:\\Users\\Desktop\\Pytest\\.coverage': Safety level may not be changed inside a transaction
</code></pre>

<p>Need help with this problem?</p>
",https://stackoverflow.com/questions/59885688/pytest-coverage-py-errror,"['python', 'pytest', 'coverage.py', 'pytest-cov']",3539,True,2,3
Error during loading: Uncaught ReferenceError: module is not defined in http://localhost:9876/_karma_webpack_/scripts.js line 1,"<p><a href=""https://i.stack.imgur.com/rtYse.png"" rel=""nofollow noreferrer"">Error image</a></p>
<p>I was doing jasmine karma unit testing using angular and i received this error. Please help</p>
<p>This is my karma.conf.js</p>
<p>Karma. conf.js</p>
<pre><code>// Karma configuration file, see link for more information //&lt;br&gt; https://karma-runner.github.io/1.0/config/configuration-file.html&lt;br&gt;

module.exports = function (config) {   config.set({&lt;br&gt;
    basePath: '',&lt;br&gt;
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [&lt;br&gt;
      require('karma-jasmine'),&lt;br&gt;
      require('karma-chrome-launcher'),&lt;br&gt;
      require('karma-jasmine-html-reporter'),&lt;br&gt;
      require('karma-coverage-istanbul-reporter'),&lt;br&gt;
      require('@angular-devkit/build-angular/plugins/karma')&lt;br&gt;
    ],&lt;br&gt;
    client: {&lt;br&gt;
      clearContext: false // leave Jasmine Spec Runner output visible in browser&lt;br&gt;
    },
    coverageIstanbulReporter: {&lt;br&gt;
      dir: require('path').join(__dirname, './coverage/Certification-Portal'),&lt;br&gt;
      reports: ['html', 'lcovonly', 'text-summary'],&lt;br&gt;
      fixWebpackSourcePaths: true&lt;br&gt;
    },&lt;br&gt;
    reporters: ['progress', 'kjhtml'],&lt;br&gt;
    port: 9876,
    colors: true,&lt;br&gt;
    logLevel: config.LOG_INFO,&lt;br&gt;
    autoWatch: true,&lt;br&gt;
    browsers: ['Chrome'],&lt;br&gt;
    singleRun: false,&lt;br&gt;
    restartOnFileChange: true   }); };&lt;br&gt;
</code></pre>
",https://stackoverflow.com/questions/63554440/error-during-loading-uncaught-referenceerror-module-is-not-defined-in-http-l,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1211,True,0,1
How to use faker in yii2 in advance template,"<p>I am generating random data for project and for unit testing. So i want to use faker. But unable to how to use faker in yii2?</p>
",https://stackoverflow.com/questions/61612152/how-to-use-faker-in-yii2-in-advance-template,"['yii2', 'yii2-advanced-app']",187,True,1,1
How to perform unit testing on the methods which print to console using console.log in angualr9?,"<p>I have a method defined as :</p>

<pre><code> public log(...logMsg) {
    if (isDebug)
      consoleLog('log', logMsg);
  }
</code></pre>

<p>Is there any possible way that we can conduct unit testing on this method using jasmine and karma frameworks?</p>
",https://stackoverflow.com/questions/62320351/how-to-perform-unit-testing-on-the-methods-which-print-to-console-using-console,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",343,False,0,1
Mapper function in Web API Controller returns null during unit testing,"<p>I am making a ASP.NET core web api and I have used Entity Framework Core. I am trying to unit test the controllers using N-Unit
I am mocking the mapper and the repository. The APIs work fine and I have even created the front end or the API but I am having issues with the unit testing.</p>
<p>Controller Code-</p>
<pre><code>[AllowAnonymous]
    [HttpGet(&quot;{id}&quot;)]
    public async Task&lt;IActionResult&gt; GetMovie(int id)
    {
        var movie = await _repo.GetMovie(id);
        if (movie == null)
        {
            return BadRequest(&quot;Object with Id not found&quot;);
        }
        var movieToReturn = _mapper.Map&lt;MovieForDetailedDto&gt;(movie);
        return Ok(movieToReturn);
    }

    [AllowAnonymous]
    [HttpPost()]
    public async Task&lt;IActionResult&gt; AddMovie(MovieForDetailedDto movieForDetailedDto)
    { 
        if (await _repo.MovieExists(movieForDetailedDto.ATitle))
            return BadRequest(&quot;movie already exists&quot;);

        else if(!ModelState.IsValid || movieForDetailedDto.ATitle == null || movieForDetailedDto.APrice == null || movieForDetailedDto.AMovieDescription ==null)
        {
            return BadRequest(&quot;movie details not valid&quot;);
        }

        var movieToCreate = _mapper.Map&lt;TblMovie&gt;(movieForDetailedDto);

        var createdMovie = await _repo.AddMovie(movieToCreate);

        return Ok(createdMovie);
    }
</code></pre>
<p>In all my functions, in the line where I map the DTO to the Model, the Line returns a null object during unit testing but the they work fine outside of unit testing.</p>
<p>My Unit Test Code for the controller-</p>
<pre><code>[TestFixture]
public class MoviesControllerTests
{
    private Mock&lt;IMovieRepository&gt; _mockMovieRepository;
    private Mock&lt;IMapper&gt; _mockMovieMapper;
    private MoviesController _moviesController;
    [Test]
    public async Task CallGetRequest_WhenCalledWithId_ReturnsTheMovieWithTheSameId()
    {
        getMoviesHelper getMoviesHelper = new getMoviesHelper();
        List&lt;TblMovie&gt; movieList = getMoviesHelper.getMovieFromList();
        var movie = getMoviesHelper.movieById(3);
        _mockMovieRepository = new Mock&lt;IMovieRepository&gt;();
        _mockMovieMapper = new Mock&lt;IMapper&gt;();
        _mockMovieMapper.Setup(mapper =&gt; mapper.Map&lt;TblMovie&gt;(It.IsAny&lt;MovieForDetailedDto&gt;()))
            .Returns(getMoviesHelper.movieById(3));
        _mockMovieRepository.Setup(repo =&gt; repo.GetMovie(3))
                .ReturnsAsync(getMoviesHelper.movieById(3));
        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.GetMovie(3);
        var okResult = tblMovie as OkObjectResult;
        //Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(tblMovie);
        Assert.IsAssignableFrom&lt;OkObjectResult&gt;(tblMovie);
        var result = ((OkObjectResult)tblMovie).Value;
        var resultValue = ((OkObjectResult)tblMovie).Value as TblMovie;
        Assert.AreEqual(resultValue.ATitle,&quot;Raging Bull&quot;);
        Assert.NotNull(result);
        Assert.IsAssignableFrom&lt;TblOrder&gt;(result);
    }

    [Test]
    public async Task GivenAValidMovie_WhenIPostANewMovie_ThenItReturnsOkWithResponse()
    {
        _mockMovieRepository = new Mock&lt;IMovieRepository&gt;();
        _mockMovieMapper = new Mock&lt;IMapper&gt;();
        _mockMovieMapper.Setup(mapper =&gt; mapper.Map&lt;TblMovie&gt;(It.IsAny&lt;MovieForDetailedDto&gt;()))
            .Returns(new TblMovie());
        _mockMovieRepository.Setup(repo =&gt; repo.AddMovie(It.IsAny&lt;TblMovie&gt;()))
            .ReturnsAsync((TblMovie movie) =&gt; movie);

        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.AddMovie(new MovieForDetailedDto
        {
            AMovieId = 55,
            ATitle = &quot;redemption&quot;,
            AMovieDescription = &quot;An action comedy adventure about brilliant robotics prodigy Hiro Hamada, who finds himself in the grips of a criminal plot that threatens to destroy the fast-paced, high-tech city of San Fransokyo. With the help of his closest companion-a robot named Baymax-Hiro joins forces with a reluctant team of first-time crime fighters on a mission to save their city.&quot;,
            ADuration = &quot;105 min&quot;,
            APrice = &quot;10&quot;,
            APurchasePrice = &quot;25&quot;,
            ARating = 5,
            AImageLink = &quot;http://upload.wikimedia.org/wikipedia/en/4/4b/Big_Hero_6_%28film%29_poster.jpg&quot;,
            ATrailerLink = &quot;//www.youtube.com/embed/z3biFxZIJOQ&quot;,
            AGenre = &quot;Comedy&quot;,
            AWideImage = &quot;https://github.com/tushar23091998/MovieRentalApp-FrontEnd/blob/master/src/app/images/bighero6.jpg?raw=true&quot;
        });
        var okResult = tblMovie as OkObjectResult;
        Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(okResult);
        Assert.IsAssignableFrom&lt;OkObjectResult&gt;(tblMovie);
        var result = ((OkObjectResult)tblMovie).Value;
        Assert.NotNull(result);
        Assert.IsAssignableFrom&lt;TblMovie&gt;(result);
    }
</code></pre>
<p>In both the test cases and even in other test cases, the repo setup works fine but after defining the controller and when I call the controller function to get the value, I found in debugging that the mapper line in controller code returns null.</p>
<p>I am not sure how go about setting up the mockmapper now and how should I pass the value.</p>
<p>Debugging Output -
<a href=""https://i.stack.imgur.com/9gsTf.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9gsTf.png"" alt=""Mapper return object value during debugging"" /></a></p>
",https://stackoverflow.com/questions/64329254/mapper-function-in-web-api-controller-returns-null-during-unit-testing,"['c#', 'unit-testing', 'nunit', 'automapper', 'asp.net-core-webapi']",863,True,1,1
Cannot use import statement outside a module in .spec.ts files NodeJs,"<p>For unit testing, I use mocha + chai.
I run the command with <code>""test"": ""mocha --require ts-node/register 'src/**/*spec.ts'""</code>.</p>

<p>When I use import in *spec.ts files (for example <code>import { expect } from 'chai';</code>)</p>

<p>I get error <code>SyntaxError: Cannot use import statement outside a module</code></p>

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

<pre><code>{
  ""compilerOptions"": {
    ""baseUrl"": ""src"",
    ""target"": ""esnext"",
    ""module"": ""esnext"",
    ""moduleResolution"": ""node"",
    ""lib"": [""dom"", ""es2018""],
    ""allowSyntheticDefaultImports"": true,
    ""noUnusedLocals"": true,
    ""removeComments"": true,
    ""resolveJsonModule"": true,
    ""strict"": true,
    ""typeRoots"": [""node_modules/@types""]
  },
  ""exclude"": [""node_modules""],
  ""include"": [""src/**/*.ts""]
}
</code></pre>
",https://stackoverflow.com/questions/60937565/cannot-use-import-statement-outside-a-module-in-spec-ts-files-nodejs,"['node.js', 'typescript', 'mocha.js', 'chai']",5949,False,1,2
Spring security jwt unit test,"<p>New to unit testing, how would I go about testing this class in</p>

<pre><code>@RestController
@CrossOrigin
public class JwtAuthenticationController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtUserDetailsService userDetailsService;

    @PostMapping(value = ""/authenticate"")
    public ResponseEntity&lt;?&gt; createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {
        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new JwtResponse(token));
    }

    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception(""USER_DISABLED"", e);
        } catch (BadCredentialsException e) {
            throw new Exception(""INVALID_CREDENTIALS"", e);
        }enter code here
    }
}
</code></pre>

<p>here is the rest of the code:</p>

<p><a href=""https://www.javainuse.com/spring/boot-jwt"" rel=""nofollow noreferrer"">https://www.javainuse.com/spring/boot-jwt</a></p>
",https://stackoverflow.com/questions/61647513/spring-security-jwt-unit-test,"['java', 'spring', 'spring-boot', 'spring-security']",144,False,0,1
How to delete the collection data on mongodb while doing unit testing with mocha and chai,"<p>I am stuck one issue where I am unit testing of API's with mongodb. I am using Mocha and Chai for unit testing, however I am facing issue that when I am test second case I need to empty the mongodb collection so new data will come and test automatically, but I could not find anything how to delete the collection every time before unit test code run. </p>

<p>Please see below my unit test code</p>

<p>test.js</p>

<pre><code>process.env.NODE_ENV = 'test';
let mongoose = require(""mongoose"");
let chai = require('chai');
let chaiHttp = require('chai-http');
const expect = require('chai').expect;
const request = require('supertest');

const app = require('../../../app.js');
const conn = require('../../../db/index.js');

chai.use(chaiHttp);
describe('notes', () =&gt; {
  beforeEach((done) =&gt; { //Before each test we empty the database
      Book.remove({}, (err) =&gt; { 
         done();           
      });        
  });
});


describe('GET /notes', () =&gt; {
  before((done) =&gt; {
    conn.connect()
      .then(() =&gt; done())
      .catch((err) =&gt; done(err));
  })

  after((done) =&gt; {
    conn.close()
      .then(() =&gt; done())
      .catch((err) =&gt; done(err));
  })

  it('OK, getting notes has no notes', (done) =&gt; {
    request(app).get('/notes')
      .then((res) =&gt; {
        const body = res.body;
        expect(body.length).to.equal(0); // getting error here as collection have data
        // res.should.have.status(200);

        done();
      })
      .catch((err) =&gt; done(err));
  });
</code></pre>

<blockquote>
  <p>app.js</p>
</blockquote>

<pre><code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const Note = require('./db/models/note.js').Note;

app.use(bodyParser.json());

app.get('/notes', (req, res) =&gt; {
  Note.find()
    .then((notes) =&gt; res.status(200).send(notes))
    .catch((err) =&gt; res.status(400).send(err));
});

app.post('/notes', (req, res) =&gt; {
  const body = req.body;
  const note = new Note({
    name: body.name,
    text: body.text
  });
  note.save(note)
    .then((note) =&gt; res.status(201).send(note))
    .catch((err) =&gt; res.status(400).send(err));
});

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

<p>please suggest me how can I delete the mongodb collection before the unit test?</p>

<p>Thanks in advance </p>
",https://stackoverflow.com/questions/60053457/how-to-delete-the-collection-data-on-mongodb-while-doing-unit-testing-with-mocha,"['node.js', 'mongodb', 'mocha.js', 'chai']",666,False,0,0
Error during loading: Uncaught ReferenceError: jqxBaseFramework is not defined,"<p>Error during loading: Uncaught ReferenceError: jqxBaseFramework is not defined in <a href=""http://localhost:9876/_karma_webpack_/vendor.js"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/vendor.js</a> line 125124
getting this error in jasmin unit testing</p>

<p>switch (item) {</p>

<pre><code>  case 'Add Privilage':
    selectedItem = this.myTree.getSelectedItem();
   // document.getElementById(""Update"").click();
    if (selectedItem != null) {
      this.selectedParentName = selectedItem.label;
      this.selectedParentUId = selectedItem.value.privilegeId;
      this.showAddPrivilageDiv = true;
      // this.myTree.addTo({ label: 'Item' }, selectedItem.element);
    }
</code></pre>
",https://stackoverflow.com/questions/61499214/error-during-loading-uncaught-referenceerror-jqxbaseframework-is-not-defined,"['karma-jasmine', 'jqxtreegrid', 'jqxtree']",406,False,1,0
Using select statement as unit test data instead of specified data Oracle,"<p>I am new at Oracle unit testing. I have been trying to unit test procedures, which uses tables in its script. I want to use select statement for unit test (to have a single row of input instead of alot of rows). The problem is oracle sql developer unit testing automatically uses existing tables for testing and I do not wish to create more tables to test. Is there are way to do it? I tried writing a script in startup process but It sql developer just takes data from tables instead.</p>
<p>Script:</p>
<pre><code>DECLARE SALARY NUMBER;    
COMMISION_PCT NUMBER;    
EMPLOYEE_ID NUMBER;    
    
BEGIN      
    select 8400 as salary, 0.2 as COMMISSION_PCT, 1001 AS EMPLOYEE_ID      
    INTO SALARY, COMMISION_PCT, EMPLOYEE_ID    
    FROM DUAL;      
END;      
</code></pre>
",https://stackoverflow.com/questions/63372274/using-select-statement-as-unit-test-data-instead-of-specified-data-oracle,"['oracle', 'unit-testing']",149,True,-1,1
How to Unit Test HTTP Handlers in C#,"<p>I want to unit Test my HTTP Handlers. I am Using XUnit framework for unit testing, My Sample Handler Code is</p>
<pre><code> public class MyHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = &quot;text/plain&quot;;
            context.Response.Write(&quot;Hello World&quot;);
            var data = context.Request.InputStream;
            //Here logic read the context.Request.InputStream
            //All the data will be posted to this Stream
            //Calling of business logic layer Methods
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
</code></pre>
<p>I am new to Unit testing and I just want to know What are the possible test cases for testing my HandleS Since the return type of handlers is Void so I am confuse how can I write the Test for Handlers...</p>
<p><strong>Note : I know HttpContextBase can called using an HttpContextWrapper, I am not asking this I am just asking What are the possible test cases for HttpHandlers</strong></p>
",https://stackoverflow.com/questions/64224670/how-to-unit-test-http-handlers-in-c,"['c#', 'asp.net', 'nunit', 'moq', 'xunit']",461,True,-1,1
Trying to compare Home Object to String Object in unit testing,"<p>I'm trying to test whether a method works or not in my unit testing. As seen in the code below in my error, I'm trying to compare my Home Object to my String Object and when printing out both of them, they are certainly equal to each other. My question is how do I change my Home Object to be a String Object or my String Object to be a Home Object so the test passes. Also if it helps this is in-memory database testing too. Thanks!</p>

<p><strong>Unit testing code</strong></p>

<pre><code>from unittest import TestCase
from main import ContactApp
from database import CombinedDatabase, Home, Person, Location, Contact

     class TestContactApp(TestCase):
         def test_commit_data(self):
         url = CombinedDatabase.construct_in_memory_url()
         contact_database = CombinedDatabase(url)
         contact_database.ensure_tables_exist()
         session = contact_database.create_session()
         home_address = Home(address='3069 U St.')
         patient1 = Person(patient_name='Mike Piazza')
         ContactApp.commit_data(session, str(patient1), str(home_address), '456324A', 96.4, 'USA',  'Nebraska', 'Omaha', '54229')
         actual = session.query(Home).one()
         actual2 = session.query(Person).one()
         print(home_address, actual.address)
         self.assertEqual(home_address, actual.address)
         self.assertEqual(patient1, actual2.patient_name)
</code></pre>

<p><strong>Error</strong></p>

<pre><code>&lt;database.Home object at 0x7fe4ae20ce48&gt; &lt;database.Home object at 0x7fe4ae20ce48&gt;
#printed out objects

&lt;database.Home object at 0x7fe4ae20ce48&gt; != &lt;database.Home object at 0x7fe4ae20ce48&gt;

&lt;database.Home object at 0x7fe4ae20ce48&gt;
&lt;database.Home object at 0x7fe4ae20ce48&gt;
&lt;Click to see difference&gt;

Traceback (most recent call last):
  File ""/home/cse/Pycharmedu2019.1.1/pycharm-edu-2019.1.1/helpers/pycharm/teamcity/diff_tools.py"", line 32, in _patched_equals
old(self, first, second, msg)
  File ""/usr/lib64/python3.6/unittest/case.py"", line 829, in assertEqual
assertion_func(first, second, msg=msg)
  File ""/usr/lib64/python3.6/unittest/case.py"", line 822, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: &lt;database.Home object at 0x7fe4ae20ce48&gt; != '&lt;database.Home object at 0x7fe4ae20ce48&gt;'
</code></pre>
",https://stackoverflow.com/questions/61451152/trying-to-compare-home-object-to-string-object-in-unit-testing,"['python', 'unit-testing', 'in-memory-database']",141,True,0,1
How to unit test controllers in node.js applications?,"<p>I am using fastify framework for my node.js application and sequelize as an ORM. I am using mocha, chai, and Sinon for unit testing. I have to unit test my controller function. The following is the sample controller function.</p>
<pre><code>// controllers.js;

const service = require('../services');

exports.create = (req, reply) =&gt; {
  const attributes = req.body;
  service.create(attributes)
    .then((result) =&gt; {
      reply.code(201).send(result);
    })
    .catch((error) =&gt; {
      reply.send(error);
    });
};
</code></pre>
<p>and my services file is as follows,</p>
<pre><code>// services.js;

const { Model } = require('../models');

function create(attributes) {
  return Model.create(attributes);
}

module.exports = { create };

</code></pre>
<p>In the above code, I want to unit test only the 'create' function in controllers.js. The problem is, it should not call the database, since it is unit testing. But the Model.create in service.js file will make a call to the database. How can I unit test controller function only?</p>
",https://stackoverflow.com/questions/62536251/how-to-unit-test-controllers-in-node-js-applications,"['node.js', 'unit-testing', 'controller', 'mocha.js', 'chai']",5952,True,3,1
API testing: Can I reduce my API functional testing effort by increasing my unit tests? Can I replace a functional test for a unit test?,"<p>I am trying to optimize my API (both restful and SOAP services) testing effort. I am thinking, one way to do so is by eliminating the redundant functional tests. I am calling them redundant because the same tests might be executed at unit testing level. </p>

<p>I understand that there's developer bias to unit testing so independent functional testing is crucial. I am not trying to replace functional tests by performing extensive unit testing but I am trying to optimize my testing effort by eliminating some of the functional tests while covering them at unit test level.</p>

<p>How can I achieve this? What’s the correlation between unit tests and functional tests?</p>

<p>Let's take an example of customerAccount/add service. Say if I have 6 tests, 2 positive (happy-path) tests, 2 exceeding boundary-value tests, 1 customer not found test, 1 invalid customer test. Can I eliminate one of 2 positive tests and one of 2 'exceeding boundary-value’ tests provided those 2 are tested at unit testing level? So now, 2 tests are covered at unit test level, 4 are at functional testing level. </p>

<p>Developers may not be testing services against the end points, they may test classes and methods instead. But in the above example, we are still testing the end points. So that’s covered.</p>

<p>What do you think of this approach?</p>
",https://stackoverflow.com/questions/59869038/api-testing-can-i-reduce-my-api-functional-testing-effort-by-increasing-my-unit,"['rest', 'api', 'unit-testing', 'testing', 'soap']",118,False,0,1
How to access private property (with prefix # syntax) in TypeScript,"<p>How do I acccess private property of a class denoted by prefix # symbol in TypeScript.
I need it for unit testing.</p>

<pre class=""lang-js prettyprint-override""><code>class A {
    #pr: number;
    pu: number
    constructor(pr: number, pu: number) {
        this.#pr = pr;
        this.pu = pu;
    }
}

let a = new A(10, 9);

console.log(a.pu, a.#pr);
</code></pre>

<p>Tried this, <code>console.log(a.pu, a[""#pr""]);</code> but no success.</p>
",https://stackoverflow.com/questions/61886351/how-to-access-private-property-with-prefix-syntax-in-typescript,"['typescript', 'access-modifiers', 'private-members']",1035,True,0,1
How to do something like Assertions.assertAllFalse()?,"<p>I'm using <code>import static org.junit.jupiter.api.Assertions.*;</code> for unit testing and I have to assert for many items if they are false. For instance:</p>
<pre class=""lang-java prettyprint-override""><code>boolean item1 = false;
boolean item2 = false;
boolean item3 = false;
boolean item4 = false;

// is something like this possible
Assertions.assertAllFalse(item1, item2, item3, item4);
</code></pre>
<p>What method should I use and how?</p>
",https://stackoverflow.com/questions/65357308/how-to-do-something-like-assertions-assertallfalse,"['java', 'unit-testing', 'junit', 'assertion']",119,True,0,3
Karma coverage HTML coverage report is empy,"<p>I am new to Karma with Angular 8. I have few queries and I am not getting correct result.</p>

<p>My queries are:</p>

<p>1) I have karma conf file where I have configured for code Coverage to view in HTML coverage directory was created but I am not seeing statement percentage and etc in the HTML page.</p>

<p>Here is my karma-config code</p>

<pre><code> 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/my-app'),
    reports: ['html', 'lcovonly', 'text-summary'],
    fixWebpackSourcePaths: true
  },
  reporters: ['progress', 'kjhtml'],
  port: 9876,
  colors: true,
  logLevel: config.LOG_INFO,
  autoWatch: true,
  browsers: ['Chrome'],
  singleRun: false
});
</code></pre>

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

<p>2) As I am new to unit testing I want to understand how to do unit testing for the below method</p>

<pre><code>navigateToStudy(row){
 this.favoriteUserId = row.id;
 this.router.navigate(['studydetails', row.id]);
}
</code></pre>

<p>Here is what I am trying for this code.</p>

<p>My Spec</p>

<pre><code>describe('navigatetoStudy', () =&gt; {
   it('should navigate', () =&gt;{
    const navigate  = navigateToStudy();
    expect(navigate).toBe
   });
});
</code></pre>

<p>I am getting error at navigatetoStudy.</p>
",https://stackoverflow.com/questions/59704920/karma-coverage-html-coverage-report-is-empy,"['angular', 'karma-jasmine', 'code-coverage', 'karma-coverage']",736,False,3,0
to_dict() changes dtype from int32 to int64,"<p>I am using</p>
<pre class=""lang-py prettyprint-override""><code>pd.testing.assert_frame_equal(expected,actual)
</code></pre>
<p>for unit testing,</p>
<pre><code>expected = pd.Dataframe(actual.to_dict()) .
</code></pre>
<p>But pandas to_dict() function is implicitly changing the dtype from int32 to int64. How should I avoid it?
Any help is highly appreciated.</p>
",https://stackoverflow.com/questions/62646896/to-dict-changes-dtype-from-int32-to-int64,"['python-3.x', 'pandas', 'unit-testing']",247,True,2,1
Testing ErrorInterceptor in Angular 8,"<p>I am trying to write unit-testing for ErrorInterceptor:</p>
<pre><code>import { TestBed } from '@angular/core/testing';

import { HttpErrorInterceptorService } from './http-error-interceptor.service';
import { HTTP_INTERCEPTORS, HttpClient, HttpErrorResponse } from '@angular/common/http';

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { AuthService } from './auth.service';

const testUrl = '/api/v1/auth/signin';

describe('HttpErrorInterceptorService', () =&gt; {
  let service: HttpErrorInterceptorService;
  let httpMock: HttpTestingController;
  let httpClient: HttpClient;
  let authService: AuthService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpErrorInterceptorService,
          multi: true,
        },
      ],
    });
    service = TestBed.inject(HttpErrorInterceptorService);
    httpMock = TestBed.inject(HttpTestingController);
    httpClient = TestBed.inject(HttpClient);
    authService = TestBed.inject(AuthService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

  it('should catch error when calling api', async() =&gt; {
    const fakeURL = '/api/v1/auth/signin';
    const fakeDataToBeSend = {
      password: 'Daniel',
      email: 'daniel.danielecki@foo.com'
    };

    spyOn(window, 'alert');

    await authService.login(fakeDataToBeSend).subscribe();

    httpMock
      .expectOne(fakeURL)
      .error(new ErrorEvent('Network error.'));

    expect(window.alert).toHaveBeenCalledWith('Network error.');

  });  

});
</code></pre>
<p>In the <code>http-error-interceptor.service.ts</code> I have :</p>
<pre><code>import { Injectable } from '@angular/core';
import {
  HttpEvent,  HttpInterceptor,  HttpHandler,  HttpRequest,  HttpResponse,  HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class HttpErrorInterceptorService implements HttpInterceptor {
  constructor() {}

  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    console.log('--------------')
    return next.handle(request).pipe(
      retry(1),
      catchError((error: HttpErrorResponse) =&gt; {
      console.log('kkkkkkkkkkk')

        let errorMessage = '';
        if (error.error instanceof ErrorEvent) {
          errorMessage = `Error: ${error.error.message}`;
        } else {
          errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
        }
        window.alert(errorMessage);
        return throwError(errorMessage);
      })
    );
  }
}
</code></pre>
<p>In the auth.service I have</p>
<pre><code>  login(user: ILoginUser): Observable&lt;any&gt; {
    return this.http.post&lt;any&gt;('/api/v1/auth/signin', user);
  }
</code></pre>
<p>I tried hard but <code>should catch error when calling api</code> is not working.</p>
<p>Please help</p>
",https://stackoverflow.com/questions/63370014/testing-errorinterceptor-in-angular-8,"['angular', 'jasmine']",95,False,0,0
Testing kIsWeb constant in flutter,"<p>in my code i have a <code>lookup</code> method:</p>

<p><strong><em>lookup.dart</em></strong></p>

<pre><code>Future&lt;http.Response&gt; httpLookup(String address) {
    return kIsWeb
        ? _httpClient.get(address)
        : _httpClient.get(
            Uri.https(address, ''),
          );
  }
</code></pre>

<p>how can i test the <code>kIsWeb</code> constant during unit testing? this is what i have tried so far but the coverage is not going though.</p>

<p><strong><em>lookup_test.dart</em></strong></p>

<pre><code>@TestOn('browser')
void main (){
test('shoud test lookup', () {
    InternetLookup lookup = InternetLookup();
    when(mockInternetLookup.httpLookup(any))
        .thenAnswer((realInvocation) async =&gt; http.Response('success', 200));
    lookup.httpLookup('www.google.com');
  });
}
</code></pre>
",https://stackoverflow.com/questions/60334121/testing-kisweb-constant-in-flutter,"['unit-testing', 'flutter', 'dart']",1174,True,5,3
How i can install junit 5 on VSCode,"<p>i'm trying to learn unit testing in java and JUnit frame but i'm on how i can and use junit on visual studio code.
should i create maven project to that.
i tried to import that  but it does not work.</p>
",https://stackoverflow.com/questions/60961140/how-i-can-install-junit-5-on-vscode,"['java', 'junit', 'junit5']",16889,True,11,2
"I am using fakeAsync and tick in unit test case of angular , getting error 2 periodic timer(s) still in the queue","<p>i m quiet new to unit testing in angular, getting error Periodic timer still in queue, Please check below code, i tried discardPeriodicTasks(), did not work for me</p>

<pre><code>it('navigate to """" redirects you to /orders', fakeAsync(() =&gt; {
    tick(15000);
    router.navigate([""""]).then(() =&gt; {
      expect(location.path()).toBe(""/home"");
    });
  }));

</code></pre>
",https://stackoverflow.com/questions/60950343/i-am-using-fakeasync-and-tick-in-unit-test-case-of-angular-getting-error-2-per,"['angular', 'unit-testing', 'karma-jasmine']",1822,False,-1,1
Sinon Calling a function passed as an argument to a constructor,"<p>I have the following classes A and B,</p>

<pre><code>class A {
    listenResponse(port, callback) {
        const server = new CustomServer(port, (error, response) =&gt; {
            if (error) return callback(error);
            callback(null, response);
        });
    }
}

class CustomServer {
   constructor(port, callback) {
      this.port = port;
      this.server = http.createServer((request, response) =&gt; {
         if(// condition) { return callback(error); }
         callback(null, response);
      });
   }
}
</code></pre>

<p>How do I test the function passed to CustomServer constructor while unit testing class A? Any help is highly appreciated.</p>
",https://stackoverflow.com/questions/60084056/sinon-calling-a-function-passed-as-an-argument-to-a-constructor,"['node.js', 'unit-testing', 'mocha.js', 'chai', 'sinon']",161,False,0,1
Getting Context into Test Classes with Junit5,"<p>We're using the Junit 5 framework for unit testing in your Android project. How can I get context into these test classes?</p>
<p>Used Plugin; <a href=""https://github.com/mannodermaus/android-junit5"" rel=""nofollow noreferrer"">https://github.com/mannodermaus/android-junit5</a></p>
",https://stackoverflow.com/questions/62495410/getting-context-into-test-classes-with-junit5,"['android', 'unit-testing', 'junit', 'android-testing', 'junit5']",1338,False,1,2
Android viewmodel unit test with livedata,"<p>I am unit testing my viewmodel and I always keep getting <code>NullPointerException</code>.</p>

<p>Here is my viewmodel code -</p>

<pre><code>class LoginViewModel(private val myUseCase: MyUseCase) :BaseViewModel() {

    private val viewState = LoginViewState()

    fun onLoginClicked() =
        Transformations.map(
            myUseCase.performUseCaseAction(
                MyAction.LoginUser(
                    email,password)
            )
        ) {
            when (it) {
                is MyResult.Loading -&gt; viewState.copy(loading = true)
                is MyResult.UserLoggedIn -&gt; viewState.copy(
                    loading = false,
                    userLoggedIn = true
                )
                is MyResult.Error -&gt; viewState.copy(loading = false, error = it.error)
            }
        }
}
</code></pre>

<p>Here is the MyUseCase interface code - </p>

<pre><code>interface MyUseCase {

    fun performUseCaseAction(action: MyAction): LiveData&lt;MyResult&gt;
}
</code></pre>

<p>Here is the unit test for the same -</p>

<pre><code>@RunWith(MockitoJUnitRunner::class)
class LoginViewModelTest {

    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    private lateinit var viewModel: LoginViewModel

    @Mock
    private lateinit var myUseCase: MyUseCase

    @Mock
    private lateinit var observer: Observer&lt;LoginViewState&gt;

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        viewModel = LoginViewModel(useCase)
    }

    @Test
    fun login_loginClicked_userLoggedInExpected() {
        //Given
        val viewState = LoginViewState()

        //When
        val liveData1 = MutableLiveData&lt;MyResult&gt;()
        `when`(useCase.performUseCaseAction(
            MyAction.LoginUser(""email"",""password"")
        )).thenReturn(liveData1)
        liveData1.postValue(MyResult.UserLoggedIn)

        viewModel.onLoginClicked().observeForever(observer)

        //Then
        verify(observer).onChanged(viewState.copy(loading = true))
        verify(observer).onChanged(viewState.copy(loading = false, userLoggedIn = true))
    }
}
</code></pre>

<p>Here is the output I get -</p>

<pre><code>java.lang.NullPointerException
at androidx.lifecycle.MediatorLiveData$Source.plug(MediatorLiveData.java:141)
at androidx.lifecycle.MediatorLiveData.onActive(MediatorLiveData.java:118)
at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:437)
at androidx.lifecycle.LiveData.observeForever(LiveData.java:232)
at com.client.personaldiary.view.viewmodel.LoginViewModelTest.onLoginClicked(LoginViewModelTest.kt:88)
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.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
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 org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:74)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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)
</code></pre>
",https://stackoverflow.com/questions/59552006/android-viewmodel-unit-test-with-livedata,"['android', 'kotlin', 'junit', 'kotlin-coroutines', 'android-mvvm']",5102,True,7,1
How to set a base url in Laravel 7.x phpunit tests,"<p>Trying to set a base url in Laravel 7.x php unit testing. In Laravel 5.8, this is what worked for me:</p>

<p>In tests/TestCase.php</p>

<pre><code>protected function setUp(): void
{
    parent::setUp();

    config(['app.url' =&gt; 'http://' . env('TEST_DOMAIN')]);
}
</code></pre>

<p>This no longer works in Laravel 7.x.</p>
",https://stackoverflow.com/questions/61521904/how-to-set-a-base-url-in-laravel-7-x-phpunit-tests,"['laravel', 'laravel-7']",1529,True,4,1
Create &quot;In Memory Database&quot; in mysql with NodeJs for Jasmine unit testing,"<p>I have a ExpressJs application and unit testing with was done using Jasmine. Currently I'm using real database to run unit tests as well. But I want to do unit testing without using the real database. When I'm searching for a solution I came a cross with the concept of 'In Memory Database'. I read the <a href=""https://dev.mysql.com/doc/refman/8.0/en/memory-storage-engine.html"" rel=""noreferrer"">mysql documentation</a>. And it says we can create a table in memory by giving the engine as Memory </p>

<pre><code>CREATE TABLE t (i INT) ENGINE = MEMORY;
</code></pre>

<p>Is there any possibility that I can create a Memory database and run my all unit tests by staring from creating the memory database, creating all tables and inserting data into that database in runtime by using a backedup .sql file?</p>
",https://stackoverflow.com/questions/60181391/create-in-memory-database-in-mysql-with-nodejs-for-jasmine-unit-testing,"['mysql', 'node.js', 'unit-testing', 'express', 'jasmine']",3495,False,8,2
Create Junit test for Void method,"<p>I am learning unit testing, I have some confusion, I have one Void method, Can you please explain to me how can I create a unit test for this method.</p>

<pre><code>public void eat(Food food){

mAmountOfEatenFood += food.eatFood(mNeededAmountOfFood - mAmountOfEatenFood);
if(mAmountOfEatenFood == mNeededAmountOfFood){
    System.out.println(mName + "" has eaten "" + mAmountOfEatenFood + "" and will not be hungry for a while.."");
    mAmountOfEatenFood = 0;
    mIsHungry = false;  
}else{
    System.out.println(mName + "" has eaten "" + mAmountOfEatenFood + "" and is still hungry.."");
    System.out.println(""Needs= "" + mNeededAmountOfFood);
    mIsHungry = true;
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/59941543/create-junit-test-for-void-method,"['java', 'android', 'unit-testing', 'mockito', 'junit4']",203,True,1,1
Unit-testing on a database,"<p>I want to do a unit-testing on a database through overriding or mocking without bringing any changes to the database. Is there any simple way to do it?</p>

<pre><code>import sqlite3
from customer import Customer

class DataChecker:
    def __init__(self):
        self.conn = sqlite3.connect('pos.db')
        self.cursor = self.conn.cursor()

    def customer_has_equipment_attached(self, customerID):
        cursor.execute(""""""SELECT * FROM Customers WHERE ID == ?;"""""", (customerID,))
        conn.commit()
        customers = cursor.fetchall()

        if len(customers) == 0:
            print(""Customer ID not found in DB"")
            return False

        customer = customers[0]
        tmp_customer = Customer(ID=customer[0], Firstname=customer[1], Lastname=customer[2],        

        Age=customer[3], Sex=customer[4], Street=customer[5], Zip=customer[6], City=customer[7],  Nationality=customer[8], IMSIPtr=customer[9], IMEIPtr=customer[10], SubscriptionPtr=customer[11], Email=customer[12], Password=customer[13])

        # Fetch equipment
        if tmp_customer.IMEIPtr != None:
            cursor.execute(""""""SELECT * FROM Equipment WHERE ID = ?;"""""", (tmp_customer.IMEIPtr,))
            conn.commit()
            equipment = cursor.fetchone()

            if len(equipment) == 0:
                print('Customer has equipment ID but ID cant be found in DB.')
                return False

        else:
            print('Customer has no equipment attached to profile.')
            return False
</code></pre>
",https://stackoverflow.com/questions/61122554/unit-testing-on-a-database,"['python', 'python-3.x', 'database', 'sqlite', 'unit-testing']",61,False,0,1
Activate Unit Test in Development and Test Phase and not Production phase,"<p>Goal:<br />
Unit testing method TestMethod1 can only be used in development and test phase.
If it being used in production phase, everything will be canceled or similar.</p>
<p>Problem:<br />
When I tried removing the string value &quot;Development&quot; from useEnvironment() method, the code is still working.</p>
<p>Is it possbile to activate the unit testing  in development and test phase and not in production phase?</p>
<p>Info:<br />
*Source code is taken from <a href=""https://www.meziantou.net/testing-an-asp-net-core-application-using-testserver.htm"" rel=""nofollow noreferrer"">https://www.meziantou.net/testing-an-asp-net-core-application-using-testserver.htm</a><br />
*Please take account that you might have about 500 unit test.<br />
*Using asp.net core mvc v3</p>
<p>Thank you!</p>
<hr />
<pre><code>------

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using System.Net.Http;
using System.Threading.Tasks;
using Testtest;

namespace XUnitTestProject1.Test
{
    /// &lt;summary&gt;
    /// https://www.meziantou.net/testing-an-asp-net-core-application-using-testserver.htm
    /// &lt;/summary&gt;
    public class Tests
    {
        [Fact]
        public async Task TestMethod1()
        {
            var webHostBuilder =
                  new WebHostBuilder()
                        .UseEnvironment(&quot;Development&quot;) // You can set the environment you want (development, staging, production)
                        .UseStartup&lt;Startup&gt;(); // Startup class of your web app project

            using (var server = new TestServer(webHostBuilder))
            using (var client = server.CreateClient())
            {
                string result = await client.GetStringAsync(&quot;/api/values&quot;);
                Assert.Equal(&quot;[\&quot;value1\&quot;,\&quot;value2\&quot;]&quot;, result);
            }
        }
    }
}
</code></pre>
<hr />
<pre><code>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Testtest.Controllers
{
    /// &lt;summary&gt;
    /// ValuesController
    /// &lt;/summary&gt;
    [ApiController]
    [Route(&quot;api/[controller]&quot;)]
    public class ValuesController : Controller
    {
        [HttpGet]
        public IEnumerable&lt;string&gt; Get()
        {
            return new string[] { &quot;value1&quot;, &quot;value2&quot; };
        }
    }
}
</code></pre>
<hr />
<p><a href=""https://i.stack.imgur.com/xHxgG.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xHxgG.png"" alt=""enter image description here"" /></a></p>
<hr />
<p>Updated:</p>
<p><a href=""https://i.stack.imgur.com/Lwrwf.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Lwrwf.png"" alt=""enter image description here"" /></a></p>
<pre><code>[CustomTestsFact]
[Fact]
public async Task TestMethod2()
{
    using (var client = _server.CreateClient())
    {
        string result = await client.GetStringAsync(&quot;/api/values&quot;);
        Assert.Equal(&quot;[\&quot;value1\&quot;,\&quot;value2\&quot;]&quot;, result);
    }
}
</code></pre>
",https://stackoverflow.com/questions/65476821/activate-unit-test-in-development-and-test-phase-and-not-production-phase,"['c#', 'unit-testing', 'asp.net-core-mvc', 'asp.net-core-3.1']",125,True,-5,1
TypeError: Cannot read property &#39;apply&#39; of undefined in NodeJS using JEST unit testing,"<p>I am new to jest unit testing as well as NodeJS and i'm trying to test my API using the following code.</p>

<pre><code>const request = require('supertest');
const quick_registration = require('../../../routes/register/quick_registration_of_user')

describe('Quick Registration of users', () =&gt; {
    beforeAll(() =&gt; {
        con.connect();
    });

    describe(""GET / "", () =&gt; {
        test(""It should respond with an array of students"", async () =&gt; {
          const response = await request(quick_registration).get(""/api/quickregistration"");
          expect(response.status).toBe(200);
        });
      });
})
</code></pre>

<p>But the test keep failing and throws me an error</p>

<pre><code> FAIL  tests/routes/register/quick_registration_of_user.test.js
  Quick Registration of users
    GET /
      × It should respond with an array of students (20ms)

  ● Quick Registration of users › GET /  › It should respond with an array of students

    TypeError: Cannot read property 'apply' of undefined

      at node_modules/express/lib/router/index.js:635:15
      at next (node_modules/express/lib/router/index.js:260:14)
      at Function.handle (node_modules/express/lib/router/index.js:174:3)
      at Server.router (node_modules/express/lib/router/index.js:47:12)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.649s, estimated 2s
Ran all test suites.
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>
",https://stackoverflow.com/questions/60011710/typeerror-cannot-read-property-apply-of-undefined-in-nodejs-using-jest-unit-t,"['node.js', 'api', 'unit-testing', 'jestjs']",1447,True,2,1
How to view test results in tSQLt?,"<p>We are using tSQLt for unit testing our database and executed below:</p>
<pre><code>EXEC tSQLt.Run '[testComplianceDimensions].[test CountOfPropertiesWithLatestRepairJob]'
EXEC tSQLt.Run '[testComplianceDimensions].[test FactPropertyLatestRepairJobAgg]'
</code></pre>
<p>This is the output Message:</p>
<pre><code>(1 row(s) affected)
[testComplianceDimensions].[test CountOfPropertiesWithLatestRepairJob] failed: (Failure) Fact_PropertyLatestRepairJobAgg failure - property counts do not match Expected: &lt;324211&gt; but was: &lt;0&gt;
 
+----------------------+
|Test Execution Summary|
+----------------------+
 
|No|Test Case Name                                                        |Dur(ms)|Result |
+--+----------------------------------------------------------------------+-------+-------+
|1 |[testComplianceDimensions].[test CountOfPropertiesWithLatestRepairJob]|  16037|Failure|
-----------------------------------------------------------------------------
Msg 50000, Level 16, State 10, Line 1
Test Case Summary: 1 test case(s) executed, 0 succeeded, 1 failed, 0 errored.
-----------------------------------------------------------------------------

(1 row(s) affected)
 
+----------------------+
|Test Execution Summary|
+----------------------+
 
|No|Test Case Name                                                  |Dur(ms)|Result |
+--+----------------------------------------------------------------+-------+-------+
|1 |[testComplianceDimensions].[test FactPropertyLatestRepairJobAgg]|     14|Success|
-----------------------------------------------------------------------------
Test Case Summary: 1 test case(s) executed, 1 succeeded, 0 failed, 0 errored.
-----------------------------------------------------------------------------
</code></pre>
<p>Is there a table where all test results are saved?</p>
<p>Thanks for your help.</p>
",https://stackoverflow.com/questions/64204248/how-to-view-test-results-in-tsqlt,"['sql-server', 'tsql', 'tsqlt']",1177,True,1,3
How do unit test the rules of vuetify v-text field with jest?,"<p>For an vuetify v-text field which is having rules element for validation purpose. May I know how to do unit testing for those rules part using Jest unit test.</p>
",https://stackoverflow.com/questions/61945480/how-do-unit-test-the-rules-of-vuetify-v-text-field-with-jest,"['vue.js', 'vuetify.js']",1778,False,0,2
TypeError: __init__() takes 5 positional arguments error while creating aiopg Pool,"<p>I have written the below code for some unit testing. Wondering if someone can point me in the right direction.I know I am missing somthing but cant figure it out.</p>
<pre><code>class testing(tornado.testing.AsyncHTTPTestCase):

    def setUp(self):
        super().setUp()
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.reset())

    async def reset(self):
        async with self.get_db().acquire() as conn:
            async with conn.cursor() as cur:
                await cur.execute('DELETE FROM vehicles')

    def get_db(self):
        '''
        Instantiate the database.
        '''
        return aiopg.Pool(
            None, 1, 10, None, 5,
            enable_json=True, enable_hstore=True,
            enable_uuid=True, echo=True, on_connect=None,
            pool_recycle=True,
            host='db' if os.getenv('IN_DOCKER') == 'true' \
                else options.db_host,
            port=options.db_port,
            user=options.db_user,
            password=options.db_password,
            dbname=options.db_database
        )

    def get_app(self):
        return Application(self.get_db())
</code></pre>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
  File &quot;tests.py&quot;, line 33, in setUp
    loop.run_until_complete(self.reset())
  File &quot;/usr/local/lib/python3.6/asyncio/base_events.py&quot;, line 488, in run_until_complete
    return future.result()
  File &quot;tests.py&quot;, line 36, in reset
    async with self.get_db().acquire() as conn:
  File &quot;tests.py&quot;, line 54, in get_db
    dbname=options.db_database
TypeError: __init__() takes 5 positional arguments but 6 positional arguments (and 6 keyword-only arguments) were given
</code></pre>
",https://stackoverflow.com/questions/63035341/typeerror-init-takes-5-positional-arguments-error-while-creating-aiopg-po,"['python', 'python-asyncio', 'tornado', 'aiopg']",130,True,-1,1
object is possibly undefined angular unit testing,"<p>I was working on unit testing I am getting below error</p>
<blockquote>
<p>Object is possibly 'undefined'</p>
</blockquote>
<pre><code> it('should set the dataSource filter to the provided argument', () =&gt; {
  component.applyFilter('filterValue');
   expect(this.dataSource.filter).toEqual('filterValue');
  })

it('should set the dataSource filter to the provided argument', () =&gt; {
   component.applyFilter('filterValue');
   expect(this.DMDataSource.filter).toEqual('filterValue');
 })
</code></pre>
<p>I am getting error inside expect(this) what is the mistake here.</p>
<p>Please let me know.</p>
",https://stackoverflow.com/questions/63970068/object-is-possibly-undefined-angular-unit-testing,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",900,True,-1,1
How to access objects of exported functions for unit testing using jest,"<p>How to access objects of exported functions for unit testing using jest(node JS) Basically I'm looking for a way to access objects of exported functions and test them
Please help</p>

<pre><code>//function.js
async function createTempUsageStatisticsTable(athenaExpress) {
let athenaQueryParam = {
    sql: getSqlQueries.CREATE_DEVICE_USAGE_STATS_TEMP_TABLE_QUERY,
    db: ""testdb""
};
try {
    await athenaExpress.query(athenaQueryParam);
}
catch (error) {
    console.error;
}
}
module.exports = {
  createTempUsageStatisticsTable: createTempUsageStatisticsTable
};

//function.test.js
const index = require('./function')
//require a test to check if sql has 
//getSqlQueries.CREATE_DEVICE_USAGE_STATS_TEMP_TABLE_QUERY

//require a 2nd test to check if db is testdb
</code></pre>
",https://stackoverflow.com/questions/59873601/how-to-access-objects-of-exported-functions-for-unit-testing-using-jest,"['javascript', 'node.js', 'jestjs']",260,True,0,1
What are the tools for generating the Test report for iOS Swift?,"<p>I am doing the Unit Testing And UI Testing for My App. Now I want to know the entire Test case report with Success and failure like ExtentReport Tool [1]: <a href=""https://extentreports.com/"" rel=""nofollow noreferrer"">https://extentreports.com/</a></p>
",https://stackoverflow.com/questions/62368922/what-are-the-tools-for-generating-the-test-report-for-ios-swift,"['ios', 'unit-testing', 'user-interface', 'testing']",193,False,1,0
Testing a function and not getting correct result for .toHaveBeenCalled() method,"<p>I am testing the following function:</p>
<pre><code>onSubmit = e =&gt; {
        e.preventDefault()
        if (!this.state.measureURI) return
        this.setState({ foodId: this.props.food.foodId }, () =&gt; this.props.fetchServing({
            quantity: parseInt(this.state.quantity),
            measureURI: this.state.measureURI,
            foodId: this.state.foodId
        }))
    }
</code></pre>
<p>test:</p>
<pre><code>    test('should test onSubmit prop for valid form submission', () =&gt; {
        const onSubmit = jest.fn()
        const fetchServing = jest.fn()
        const arg = {
            quantity: expect.any(Number),
            measureURI: expect.any(String),
            foodId: expect.any(Number)
        }
        const wrapper = shallow(&lt;ServingForm food={food} onSubmit={onSubmit} fetchServing={fetchServing} /&gt;)
        wrapper.find('form').simulate('submit', {
            preventDefault: () =&gt; { }
        })
        expect(fetchServing).toHaveBeenCalled()
    })
</code></pre>
<p>However, I am getting the following error:</p>
<pre><code>● &lt;ServingForm /&gt; › should test onSubmit prop for valid form submission
    expect(jest.fn()).toHaveBeenCalled()
    Expected number of calls: &gt;= 1
    Received number of calls:    0
      37 |             preventDefault: () =&gt; { }
      38 |         })
    &gt; 39 |         expect(fetchServing).toHaveBeenCalled()
         |                              ^
      40 |     })
      41 | 
      42 | })
</code></pre>
<p>What am I doing wrong?</p>
<p>I am using jest and enzyme to do unit testing with spies.</p>
",https://stackoverflow.com/questions/63496194/testing-a-function-and-not-getting-correct-result-for-tohavebeencalled-method,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",28,True,0,1
Where we can put sample input datas for unit testing in angular,"<p>I am creating unit test for my angular application. I want to know <strong>the better place</strong> where we can store or configure datas like user name, password ..etc for unit testing. </p>

<pre><code>it('loging with existing account', (done) =&gt; {
    authService.login('sahalXXX@gmail.com', 'secretPass')
        .subscribe(res =&gt; {
            expect(res).toBeTruthy();
            done();
        },
            err =&gt; {
                expect(err).toBeFalsy();
                done();
            });
});
</code></pre>
",https://stackoverflow.com/questions/62427642/where-we-can-put-sample-input-datas-for-unit-testing-in-angular,"['angular', 'unit-testing', 'jasmine']",13,False,0,0
How to mock repository livedata &amp; ViewModel methods for unit testing,"<p>What is the proper way to test verify <code>viewModel.getMoviesByReleaseDate()</code> gets a <code>List&lt;DiscoverMovie&gt;</code> when <code>repository.getMoviesByReleaseDate()</code> is called on <code>viewModel.init()</code>.</p>

<p>My method <code>testRepoFetchDataSuccess()</code> doesn't achieve the above mentioned.
Kindly provide code example if possible as I'm new to unit testing.</p>

<pre><code>public class TMDbRepository {

    private static final String TAG = ""TMDbRepository"";

    private static final String RELEASE_DATE_LTE = ""2020-02-02"";
    private static final String RELEASE_DATE_DESC = ""release_date.desc"";
    private static final int PAGES_NO = 1;

    private final TMDbWebService webService;

    @Inject
    public TMDbRepository(TMDbWebService webService) {
        this.webService = webService;
    }

    public Single&lt;DiscoverMovieResponse&gt; getMoviesByReleaseDate() {
        return webService
                .getMoviesByReleaseDate(RELEASE_DATE_LTE, RELEASE_DATE_DESC, PAGES_NO);
    }

    public Single&lt;MovieDetails&gt; getMovieDetails(int id) {
        return webService.getMovieDetails(id);
    }
}
</code></pre>

<pre><code>public class MasterFragmentViewModel extends ViewModel {
    private static final String TAG = ""MasterFragmentViewModel"";

    private final RxSingleSchedulers rxSingleSchedulers;
    private final TMDbRepository repository;
    private CompositeDisposable disposable;

    private final MutableLiveData&lt;List&lt;DiscoverMovie&gt;&gt; movies = new MutableLiveData&lt;&gt;();
    private final MutableLiveData&lt;Boolean&gt; error = new MutableLiveData&lt;&gt;();
    private final MutableLiveData&lt;Boolean&gt; loading = new MutableLiveData&lt;&gt;();

    @Inject
    public MasterFragmentViewModel(TMDbRepository repository, RxSingleSchedulers rxSingleSchedulers) {
        this.repository = repository;
        this.rxSingleSchedulers = rxSingleSchedulers;
        disposable = new CompositeDisposable();
    }

    public void init() {
        fetchMoviesByReleaseDate();
    }

    private void fetchMoviesByReleaseDate() {
        loading.setValue(true);

        disposable.add(
                repository.getMoviesByReleaseDate()
                        .compose(rxSingleSchedulers.applySchedulers())
                        .subscribeWith(new DisposableSingleObserver&lt;DiscoverMovieResponse&gt;() {
                            @Override
                            public void onSuccess(DiscoverMovieResponse discoverMovieResponse) {
                                error.setValue(false);
                                movies.setValue(discoverMovieResponse.getMovieList());
                                loading.setValue(false);
//                                Log.d(TAG, ""onSuccess: "" + discoverMovieResponse.getTotalResults());
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.d(TAG, ""onError: "" + e);
                                error.setValue(true);
                                loading.setValue(false);
                            }
                        })
        );
    }

    public LiveData&lt;List&lt;DiscoverMovie&gt;&gt; getMoviesByReleaseDate() {
        return movies;
    }

    public LiveData&lt;Boolean&gt; getError() {
        return error;
    }

    public LiveData&lt;Boolean&gt; getLoading() {
        return loading;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        disposable.clear();
        Log.d(TAG, ""onCleared: disposable cleared!"");
    }
}
</code></pre>

<pre><code>public class MasterFragmentTest {

    @Rule
    public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();
    @Mock
    TMDbRepository repository;
    @Mock
    LifecycleOwner lifecycleOwner;
    @Mock
    Observer&lt;List&lt;DiscoverMovie&gt;&gt; moviesObserver;
    Lifecycle lifecycle;
    private MasterFragmentViewModel viewModel;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        lifecycle = new LifecycleRegistry(lifecycleOwner);
        viewModel = new MasterFragmentViewModel(repository, RxSingleSchedulers.TEST_SCHEDULER);
        viewModel.getMoviesByReleaseDate().observeForever(moviesObserver);
    }

    @Test
    public void testNull() {
        when(repository.getMoviesByReleaseDate()).thenReturn(null);
        assertNotNull(viewModel.getMoviesByReleaseDate());
        assertTrue(viewModel.getMoviesByReleaseDate().hasObservers());
    }

    @Test
    public void testRepoFetchDataSuccess() {
        List&lt;DiscoverMovie&gt; mockList = new ArrayList&lt;&gt;();
        DiscoverMovie discoverMovie = Mockito.mock(DiscoverMovie.class);
        mockList.add(discoverMovie);

        when(repository.getMoviesByReleaseDate()).thenReturn(Single.just(new DiscoverMovieResponse()));
        viewModel.init();
        verify(moviesObserver).onChanged(mockList);
    }

    @After
    public void tearDown() throws Exception {
        repository = null;
        viewModel = null;
    }
}
</code></pre>

<p>Test Result:</p>

<pre><code>Argument(s) are different! Wanted:
moviesObserver.onChanged(
    [Mock for DiscoverMovie, hashCode: 990897274]
);
-&gt; at com.sulaz.tmdb.MasterViewModelTest.testRepoFetchDataSuccess(MasterViewModelTest.java:72)
Actual invocation has different arguments:
moviesObserver.onChanged(
    null
);
-&gt; at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)
</code></pre>
",https://stackoverflow.com/questions/60062395/how-to-mock-repository-livedata-viewmodel-methods-for-unit-testing,"['android', 'junit', 'mockito', 'rx-java2', 'android-livedata']",1823,False,3,0
How to write unittest for function that accepts csv file?,"<p>My function looks like this</p>

<pre><code>import pandas as pd 

def my_function( file_path ):
    df = pd.read_csv( filepath )
    #some other operations on df here 
    return df 
</code></pre>

<p>I do not want to access an external file for unit test. Is there any way to create a csv file like object on the fly for unit testing.    </p>
",https://stackoverflow.com/questions/60982270/how-to-write-unittest-for-function-that-accepts-csv-file,"['python', 'pandas', 'unit-testing']",1694,True,2,1
How to mock sqlalchemy execution output inside `with` context manager,"<p>I'm trying to write unit tests for my python script which uses <code>sqlalchemy</code> to connect to MySQL.</p>

<p>My function looks like this:</p>

<pre class=""lang-py prettyprint-override""><code>def check_if_table_exists(db):
    with db.connect() as cursor:
        table_exists = cursor.execute(f""SHOW TABLES LIKE '{PRIMARY_TABLE_NAME}';"")
        if not table_exists.rowcount:
            cursor.execute(f""CREATE TABLE...
</code></pre>

<p>I can't find any resources on how to first mock out <code>db.connect()</code>, which in turn also needs to have its <code>execute</code> mocked so that I can test different <code>table_exists</code> scenarios. It's also possible that my code is simply not cohesive to proper unit testing and I need to call the function with a cursor object to begin with.</p>

<p>For reference, <code>db</code> is the output of <code>sqlalchemy.create_engine</code>.</p>

<p><strong>TLDR I need help getting started on unit testing for cases where I get rows back for the <code>SHOW</code> statement and when I don't.</strong></p>
",https://stackoverflow.com/questions/62145009/how-to-mock-sqlalchemy-execution-output-inside-with-context-manager,"['python', 'unit-testing', 'testing', 'sqlalchemy', 'pymysql']",3127,True,1,1
Unit testing for REST API using node Js,"<p>I want to write unit testing for my REST API calls(Using mocha and chai).
Can anyone provide me better guide or any previously written code ,so that I can perform easily.</p>
",https://stackoverflow.com/questions/64692710/unit-testing-for-rest-api-using-node-js,"['api', 'unit-testing', 'mocha.js', 'chai']",399,True,0,1
Redshift 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 make sure that it always returns something?</p>
",https://stackoverflow.com/questions/60415665/redshift-connection-unit-testing-in-python,"['python', 'python-3.x', 'python-2.7', 'unit-testing', 'amazon-redshift']",376,False,0,1
Unit Testing Method Arguments,"<p>I hope this is doable. I want to use <strong>Unit Testing</strong> to validate method parameters.
I want to ensure that zero is not passed through as an argument. </p>

<blockquote>
  <p>Code to Test    </p>
</blockquote>

<pre><code> public class TestParameter
 {
    public double divide(int dividend, int divisor)
    {
        double quotient = 0;

        if (divisor!=0)
        quotient= dividend / divisor;

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

<blockquote>
  <p>Unit Test</p>
</blockquote>

<pre><code>[TestClass]
public class UnitTestIntro
{
    [TestMethod]
    public void ZeroDivision()
    {
        TestParameter test = new TestParameter();
        double ans = test.divide(10, 0);
        //Assert.IsTrue();
        //I want to assert that divide does not allow 0 divisor as an argument
    }
}
</code></pre>
",https://stackoverflow.com/questions/60434731/unit-testing-method-arguments,"['c#', 'unit-testing']",2121,True,0,2
How can I check in nativescript unit that unit test is occur for iOS or Android?,"<p>While unit test in nativescript angular how can we check that this unit testing occurs for iOS or Android. I have written specific platform code so I want to test in unit test.</p>
",https://stackoverflow.com/questions/62470366/how-can-i-check-in-nativescript-unit-that-unit-test-is-occur-for-ios-or-android,"['android', 'ios', 'unit-testing', 'nativescript', 'nativescript-angular']",34,False,0,0
How to stub the below senario using mocha chai sinon,"<p>I want to stub the mock response for below code how can i do that ?</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 { Storage } from ""@google-cloud/storage"";
const storage = new Storage();
import a from ""./a.js""

export function abc(req, res) {
  a().then(result -&gt;{
  const bucketName = result.bucketName;
  const fileName = ""Sample.json"";
  const file = storage.bucket(bucketName).file(result.fileName);
  const myfile = file.createReadStream();
  let buffer = """";
  myfile
    .on(""data"", function(a) {
      buffer += a;
    })
    .on(""end"", function() {
      console.log(buffer);
      res.status(200).send(buffer);
    });
    });
}</code></pre>
</div>
</div>
</p>

<p>import a from ""./a.js"" is async function and i need to use mocha chai to write unit testing.</p>
",https://stackoverflow.com/questions/59639859/how-to-stub-the-below-senario-using-mocha-chai-sinon,"['unit-testing', 'google-cloud-functions', 'sinon', 'sinon-chai']",500,False,0,1
How to test Test Multiple classes objects Doubles in Unit testing,"<p>What i need</p>
<ul>
<li>Need to access other classes function from base class.</li>
</ul>
<p>Problem</p>
<ul>
<li>cannot access $this-&gt;service-&gt;getDataAll another class service function.</li>
<li>Error: Call to a member function getDataAll() on null</li>
</ul>
<p>Class A</p>
<p>function Abc(){
$records = $this-&gt;getData($arg1, $arg2, $arg3);
}</p>
<p>function getData($arg1, $arg2, $arg3)
{
$this-&gt;service-&gt;getDataAll($arg1, $arg2, $arg3);
}</p>
<blockquote>
<p>Unit testing code</p>
</blockquote>
<pre><code>     $services = $this-&gt;getMockBuilder(ClassA::class)
        //-&gt;setMethods(array('Abc'))            
        -&gt;disableOriginalConstructor()
        -&gt;getMock();
    
   
    
    $data = array('name' =&gt;'name');
    $indexVal = '';
    $returnVal = UnitTesting::callMethod(
        $services,
        'Abc',
        array($data)
    );
     private static function callMethod($obj, $name, array $args)
    {
                
                $class = new \ReflectionClass($obj);
                $method = $class-&gt;getMethod($name);
                $method-&gt;setAccessible(true);
                return $method-&gt;invokeArgs($obj, $args);
    }

            
 
</code></pre>
<p>So by accessing function Abc  unit testing  halts in function getData  which was accessing
service func getDataAll.</p>
<p>Accessing service getDataAll works</p>
<pre><code>    $stub = $this-&gt;getMockBuilder(\App\Service::class)
                 -&gt;setMethods(array('getDataAll'))
                 -&gt;disableOriginalConstructor()
                 -&gt;disableOriginalClone()
                 -&gt;disableArgumentCloning()
                 -&gt;disallowMockingUnknownTypes()
                 -&gt;getMock();

    // Configure the stub.
    $stub-&gt;expects($this-&gt;any())
        -&gt;method('getDataAll')
        -&gt;willReturn(true);

    $this-&gt;assertTrue($stub-&gt;getDataAll($arg1, $arg2, $arg3));
</code></pre>
<ul>
<li><p>I need to access service class from Class A.</p>
</li>
<li><p>service function must return some data.</p>
</li>
<li><p>any solution is most welcome.</p>
</li>
</ul>
<p>Reference</p>
<p><a href=""https://phpunit.readthedocs.io/en/9.3/test-doubles.html"" rel=""nofollow noreferrer"">https://phpunit.readthedocs.io/en/9.3/test-doubles.html</a></p>
<p><a href=""https://stackoverflow.com/questions/46192311/phpunit-test-doubles"">PHPUnit test doubles</a></p>
",https://stackoverflow.com/questions/64870925/how-to-test-test-multiple-classes-objects-doubles-in-unit-testing,"['php', 'unit-testing', 'phpunit']",40,False,0,0
Unit test throw exception with retry policy,"<p>I am trying to write a unit test to test the policy WaitAndRetryAsync using <a href=""https://github.com/App-vNext/Polly"" rel=""nofollow noreferrer"">Polly</a>
To test the policy I need to simulate and throw a SqlException with certain sqlerror numbers.</p>

<p>I have followed their documentation on unit testing policies, specifically <a href=""https://github.com/App-vNext/Polly/wiki/Unit-testing-with-Polly---with-examples#2b-test-policies-with-unit-tests-independent-of-consuming-code"" rel=""nofollow noreferrer"">[2b] Test policies with unit-tests, independent of consuming code</a></p>

<p>Unit Test, I used Stackoverflow question <a href=""https://stackoverflow.com/questions/1386962/how-to-throw-a-sqlexception-when-needed-for-mocking-and-unit-testing/1387030#1387030"">How to throw a SqlException when needed for mocking and unit testing?</a> to create class SqlExceptionMocker</p>

<pre><code>//Arrange
var policy = new CustomPolicyClass();
var randomSqlException = 0;
var invocations = 0;
var generatedException = SqlExceptionMocker.MakeSqlException(randomSqlException);

//Act
var result = await policy.TimeoutExceptionPolicy()
    .ExecuteAsync&lt;bool&gt;(async () =&gt; invocations++ &lt;= 1 ? throw generatedException : true);

//Assert
Assert.True(result);
</code></pre>

<pre><code>public async Task&lt;IAsyncPolicy&gt; TimeoutExceptionPolicy() =&gt;
    Policy
        .Handle&lt;SqlException&gt;(ex =&gt; errorNumberArray.Contains(ex.Number))
        .WaitAndRetryAsync(3,
            retryAttempt =&gt; TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
            (ex, timeSpan) =&gt;
            {
                Console.WriteLine($""Exception: {ex.Message}"");
                Console.WriteLine($""Retrying in {timeSpan.Seconds} seconds"");
            });
</code></pre>

<h1>What I am trying to do:</h1>

<ol>
<li>Throw SqlException in ExecuteAsync 2 times</li>
<li>3rd time return true</li>
</ol>

<h1>What actually happens:</h1>

<ol>
<li>Throws SqlException in ExecuteAsync 1 time</li>
<li>Unit test fails</li>
<li>ExecuteAsync does not rerun 2 more times </li>
</ol>
",https://stackoverflow.com/questions/61460526/unit-test-throw-exception-with-retry-policy,"['c#', 'unit-testing', 'xunit', 'polly']",1200,False,0,0
How to test head() in nuxt.js using jest,"<p>I am using Nuxt.js with Jest for unit testing. I added a head function in my layout to change the title and I would like to unit test it.
Here is my 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-html lang-html prettyprint-override""><code>&lt;template&gt;
  &lt;h1 class=""title""&gt;HELLO&lt;/h1&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  data () {
    return {
      title: 'MY TITLE'
    }
  },
  head () {
    return {
      title: this.title,
      meta: [
        { hid: 'description', name: 'description', content: 'MY DESCRIPTION' }
      ]
    }
  }
}
&lt;/script&gt;</code></pre>
</div>
</div>
</p>

<p>I tried:</p>

<pre><code>const wrapper = shallowMount(index)
wrapper.vm.head() &lt;- fails
</code></pre>

<p>Any suggestions?</p>
",https://stackoverflow.com/questions/59964001/how-to-test-head-in-nuxt-js-using-jest,"['unit-testing', 'vue.js', 'jestjs', 'nuxt.js']",2512,True,3,2
Proper way of testing a NodeJS controller method using Jest,"<p>JavaScript unit testing newbie here. I'm writing an API using NodeJS and Mongoose and after doing a little bit of research I ended up using Jest and Supertest for unit testing. For now I want to test a simple controller method that fetches all the records from the database. </p>

<p>This is my controller method:</p>

<pre><code>const Gender = require(""../models/gender"");
exports.getMany = async (req, res) =&gt; {
  try {
    const genders = await Gender.find();

    return res.status(200).json({
      data: genders,
    });
  } catch (error) {
    console.error(error);
    res.status(400).end();
  }
};
</code></pre>

<p>The tests I wrote so far work fine but I feel that I'm not doing it properly. </p>

<p>Here's the two test that I wrote for this method:</p>

<pre><code>it(""Get an empty array if there are no genders in the database"", async (done) =&gt; {
  const response = await request.get(""/api/v1/genders"");

  expect(response.status).toBe(200);

  expect(response.body.data.length).toBe(0);

  done();
});

it(""Get an array with existing genders in the database"", async (done) =&gt; {
  const male = await request.post(""/api/v1/genders"").send({ name: ""Male"" });

  const female = await request
    .post(""/api/v1/genders"")
    .send({ name: ""Female"" });

  const response = await request.get(""/api/v1/genders"");

  expect(response.status).toBe(200);

  expect(response.body.data.length).toBe(2);

  expect(male.body.data.name).toBe(""Male"");

  expect(female.body.data.name).toBe(""Female"");

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

<p>Am I doing it correctly? </p>

<p>Would it be more appropriate to call the <code>getMany()</code> method inside the test instead of accessing the route? </p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/62281595/proper-way-of-testing-a-nodejs-controller-method-using-jest,"['node.js', 'unit-testing', 'controller', 'jestjs']",514,False,0,1
Unit Test for a function with got module using sinon,"<p>I have 2 functions,</p>

<pre><code>const callAndParseHttp = async (url) =&gt; {
      const response = await got(url);
       return await parseXml(response.body);
};

const parseXml = async xmlData =&gt; {
      try {
            const json = parser.toJson(xmlData.body);
            return JSON.parse(json);
      } catch (err) {
            return err;
      }
 };
</code></pre>

<p>And I have wrote a unit test in sinon for that looks like,</p>

<pre><code>describe('/ handler', () =&gt; {
    let spy;
    before(() =&gt; {
        spy = sinon.spy(unitParser, 'callAndParseHttp');
    });
afterEach(() =&gt; {
    spy.restore();
});
it('unit parser testing', async () =&gt; {
    await unitParser.callAndParseHttp(
        'http://www.mocky.io/v2/5e34242423'
    );
    expect(spy.callCount).to.equal(1);
});
})
</code></pre>

<p>Do I need to create stub for this test ? I'm new to unit testing. Tests are passing correctly.</p>
",https://stackoverflow.com/questions/60378658/unit-test-for-a-function-with-got-module-using-sinon,"['javascript', 'node.js', 'mocha.js', 'chai', 'sinon']",309,False,1,1
How to mock RestTemplate in Java Spring boot?,"<p>I am trying to mock <code>RestTemplate</code> <code>getEntity()</code> method using below code but i am getting exception and i am new for Unit testing </p>

<p>can some one help me please what is my mistake</p>

<h2>Class</h2>

<pre><code>public List&lt;SampleObject1&gt; getGitHubUSersList(){

        try {
            ResponseEntity&lt;SampleObject1[]&gt;responseEntity = restTemplate.getForEntity(""https://api.github.com/users"", SampleObject1[].class);
            List&lt;SampleObject1&gt;arrayList  = Arrays.asList(responseEntity.getBody());
            System.out.println(""final list is----&gt;""+objectMapperl.writeValueAsString(arrayList));
            return arrayList;
        }catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }
</code></pre>

<h2>Test Class</h2>

<pre><code>public class SampleServiceTest1 {

    @Mock
    RestTemplate mockrestTemplate;

    @InjectMocks
    @Spy
    SampleService1 sampleService;

    @Before
    public void setup() {
    MockitoAnnotations.initMocks(this);
    }

@SuppressWarnings(""unchecked"")
@Test
public void getGitHubUSersListTest() {

    List&lt;SampleObject1&gt; sampleObject1s = new ArrayList&lt;&gt;();

    SampleObject1 sampoleObject1 = new SampleObject1();
    sampoleObject1.setId(1);
    sampoleObject1.setLogin(""sample1"");
    sampoleObject1.setNode_id(""sample2"");
    sampleObject1s.add(sampoleObject1);

    SampleObject1 sampoleObject2 = new SampleObject1();
    sampoleObject2.setId(2);
    sampoleObject2.setLogin(""sample3"");
    sampoleObject2.setNode_id(""sample4"");
    sampleObject1s.add(sampoleObject2);

    Mockito.doReturn(sampleObject1s).when(mockrestTemplate).getForEntity(Matchers.anyString(),  ArgumentMatchers.any(Class.class));

    List&lt;SampleObject1&gt; list = sampleService.getGitHubUSersList();

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

<p>}</p>

<h2>Error</h2>

<pre><code>org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to when() is null!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();
Also, if you use @Mock annotation don't miss initMocks()
    at com.example.microservice.service.SampleServiceTest1.getGitHubUSersListTest(SampleServiceTest1.java:50)
</code></pre>
",https://stackoverflow.com/questions/59731201/how-to-mock-resttemplate-in-java-spring-boot,"['java', 'mockito', 'resttemplate']",934,True,1,3
Getting Error while running Mutation testing on Python code : AttributeError: &#39;MutationTestRunnerThread&#39; object has no attribute &#39;isAlive&#39;,"<p>I am working on Python programming Mutation testing using <code>Mut.py</code>. Unit testing is passed and when I run the Mutation testing on command line using the command, I am getting error like this.</p>
<pre><code>C:\Users\pc\Desktop\My_Projects\Calculator01&gt;mut.py --target simpleCalculator.py --unit-test test_simpleCalculator.py --runner pytest --coverage
Traceback (most recent call last):
  File &quot;C:\Users\pc\AppData\Local\Programs\Python\Python39\Scripts\mut.py&quot;, line 7, in &lt;module&gt;
    commandline.main(sys.argv)
  File &quot;c:\users\pc\appdata\local\programs\python\python39\lib\site-packages\mutpy\commandline.py&quot;, line 10, in main
    run_mutpy(parser)
  File &quot;c:\users\pc\appdata\local\programs\python\python39\lib\site-packages\mutpy\commandline.py&quot;, line 61, in run_mutpy
    mutation_controller = build_controller(cfg)
  File &quot;c:\users\pc\appdata\local\programs\python\python39\lib\site-packages\mutpy\commandline.py&quot;, line 73, in build_controller
    return controller.MutationController(
  File &quot;c:\users\pc\appdata\local\programs\python\python39\lib\site-packages\mutpy\controller.py&quot;, line 60, in __init__
    self.runner = runner_cls(self.test_loader, self.timeout_factor, self.stdout_manager, mutate_covered)
  File &quot;c:\users\pc\appdata\local\programs\python\python39\lib\site-packages\mutpy\test_runners\base.py&quot;, line 150, in __init__
    self.init_modules = self.find_init_modules()
  File &quot;c:\users\pc\appdata\local\programs\python\python39\lib\site-packages\mutpy\test_runners\base.py&quot;, line 209, in find_init_modules
    test_runner.terminate()
  File &quot;c:\users\pc\appdata\local\programs\python\python39\lib\site-packages\mutpy\utils.py&quot;, line 357, in terminate
    if self.isAlive():
**AttributeError: 'MutationTestRunnerThread' object has no attribute 'isAlive'**
</code></pre>
<p>Can anyone help?</p>
",https://stackoverflow.com/questions/64940369/getting-error-while-running-mutation-testing-on-python-code-attributeerror-m,"['python-3.x', 'mutation']",921,True,1,1
Why my unit test is giving me an AssertionFailedError when I try to render another page,"<p>I am learning unit testing and trying to check if the login is valid on the <strong>HomePage</strong> and if so that the <strong>SuccessPage</strong> is rendered but it is giving me an <code>AssertionFailedError</code></p>

<p>.java:</p>

<pre><code>
    @Test
    public void validLogin(){
        tester.startPage(HomePage.class);

        FormTester form = tester.newFormTester(""userForm"");
        form.setValue(""username"", ""emile"");
        form.setValue(""password"", ""123"");
        form.submit();
        //onsubmit the Successpage is rendered in response
        tester.assertRenderedPage(SuccessPage.class);

    }
</code></pre>

<p>the error:</p>

<pre><code>[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket core library initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket extensions initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer (theme-uilightness)
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

junit.framework.AssertionFailedError: classes not the same, expected 'class com.mycompany.SuccessPage', current 'class com.mycompany.HomePage'

    at org.apache.wicket.util.tester.WicketTester.assertResult(WicketTester.java:798)
    at org.apache.wicket.util.tester.WicketTester.assertRenderedPage(WicketTester.java:697)
    at com.mycompany.TestHomePage.validLogin(TestHomePage.java:48)
    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.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
",https://stackoverflow.com/questions/60558864/why-my-unit-test-is-giving-me-an-assertionfailederror-when-i-try-to-render-anoth,"['wicket', 'wicket-tester']",113,True,0,1
Jest + MockImplementationOnce + is not working for 2nd time,"<p>I am using JEST framework for unit testing for my node.js project. I Used <code>mockImplementationOnce</code> for mocking thirdParty library methods as follows:</p>
<pre><code>jest.mock('abc', () =&gt; {
    return { a: { b: jest.fn() } };
  });
const abcjs= require('abc');

describe(&quot;1st test&quot;, () =&gt; { 
  test(&quot;should return true&quot;, async () =&gt; {
    abcjs.a.b.mockImplementationOnce(() =&gt; Promise.resolve(
      return true}
    ));
  });
});

describe(&quot;2nd test&quot;, () =&gt; { 
  test(&quot;should return false&quot;, async () =&gt; {
    abcjs.a.b.mockImplementationOnce(() =&gt; Promise.resolve(
      return false}
    ));
  });
});
</code></pre>
<p>1st test was executed successfully, but the <strong>2nd test Its calling the actual method, its not mocking.</strong>
I tried resetting the mocks <code>afterEach</code> but it didn't help.</p>
",https://stackoverflow.com/questions/64983001/jest-mockimplementationonce-is-not-working-for-2nd-time,"['node.js', 'unit-testing', 'jestjs']",20408,True,10,3
How to test a component that renders children as props in enzyme,"<p>I'm trying to test if a given component renders as many children as it receives. For now, it renders only two components. I'm stuck as I'm new to unit testing. Here's what I tried:</p>

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

<pre><code>
const Component = ({ children }) =&gt; {
    return &lt;div&gt;{children}&lt;/div&gt;;
};

</code></pre>

<p><strong>Component.test.js:</strong></p>

<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import Component from './Component';
import ChildComponent from './ChildComponent';
import ChildComponent2 from './ChildComponent';

it('show a ChildComponent component', () =&gt; {
    const wrapped = shallow(&lt;Component children /&gt;);

    expect(wrapped.find(ChildComponent).length).toEqual(1)
});

it('show a ChildComponent2 component', () =&gt; {
    const wrapped = shallow(&lt;Component children /&gt;);

    expect(wrapped.find(ChildComponent2).length).toEqual(1)
});

</code></pre>
",https://stackoverflow.com/questions/60320307/how-to-test-a-component-that-renders-children-as-props-in-enzyme,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",218,True,1,1
Testing Vue components that utilize cytoscape.js?,"<p>I am working on something that involves cytoscape.js and Vue.js. I am currently using jest.js for unit testing the Vue components. A lot of my components have their funtionality tied to a cytoscape graph that is mounted on a container.</p>

<p>This is how my test files look like: </p>

<pre><code>import graph from ""@/graph.vue""

import {
    mount,
    createLocalVue,
} from ""@vue/test-utils""

const localVue = createLocalVue();

describe('graph.vue', () =&gt; {

    it('should center the graph', () =&gt;{
        const wrapper = mount(graph, {
            localVue,
        })
        const button = wrapper.find('btn')
        expect(wrapper.vm.Cytoscape())).toHaveBeenCalled(0)
        button.trigger('click')
        expect(wrapper.vm.Cytoscape()).toHaveBeenCalled(1)
    })
}) 
</code></pre>

<p>If it uses any cytoscape, it gives the following error: </p>

<pre><code>Cannot read property 'className' of null

      11 | // run(): Startup-Function
      12 | export function run() {
    &gt; 13 |   cy = cytoscape({
         |        ^
      14 | 
      15 |     container: document.getElementById('cy'), // container to render in
      16 |     //builds graph 
      17 | }
</code></pre>

<p>I suspect that I have the wrong approach or even testing environment for this. What am I missing ?</p>

<p>Edit: I have found an alternative solution to the problem. Instead of unit testing with jest, there are many things that I needed to test that I could also test in E2E testing. I currently use Cypress to do that.</p>
",https://stackoverflow.com/questions/60047583/testing-vue-components-that-utilize-cytoscape-js,"['vue.js', 'vuejs2', 'jestjs', 'cytoscape.js', 'vue-test-utils']",549,False,2,0
Why viewModel returns null value while observeForever used in Unit test,"<p>I have written a test method like this:</p>
<pre><code>@Test
    fun testGetDoctorsFromServer() {
        val doctorViewModel = DoctorViewModel(ApplicationProvider.getApplicationContext())
        val observer = Observer&lt;List&lt;Doctor&gt;&gt; {}
        try {

            doctorViewModel.ldTestData.observeForever(observer)
            doctorViewModel.getDoctorsFromServer()
            val doctors = doctorViewModel.ldTestData.value
            assertEquals(5, doctors?.size)

        } finally {
            doctorViewModel.ldTestData.removeObserver(observer)
        }
    }
</code></pre>
<p>but when I run the test I always get assertionfailed error</p>
<pre><code>junit.framework.AssertionFailedError: 
Expected :5
Actual   :null
</code></pre>
<p>I am pretty beginner in unit testing, can anyone recorrect me from what I am missing?</p>
",https://stackoverflow.com/questions/65179302/why-viewmodel-returns-null-value-while-observeforever-used-in-unit-test,"['android', 'unit-testing', 'kotlin', 'android-livedata', 'android-viewmodel']",752,False,0,1
Angular 6 Unit testing Error of a particular component,"<p>I am getting the above error while doing unit testing of a particular component. I am a beginner in Angular 6.</p>

<blockquote>
  <p>StaticInjectorError(DynamicTestModule)[UtilsService -> TitleCasePipe]: 
  StaticInjectorError(Platform: core)[UtilsService -> TitleCasePipe]: 
  NullInjectorError: No provider for TitleCasePipe!/</p>
</blockquote>
",https://stackoverflow.com/questions/59717890/angular-6-unit-testing-error-of-a-particular-component,"['angular', 'unit-testing', 'angular6', 'components']",41,False,0,0
Angular: How to write a unit test for template variable,"<p>I'm working page auto scroll when click on the button and I'm using template variable as target point. How to write a unit testing for <code>scrollToSecondPage</code> function which has template var as param.</p>

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

<pre><code>&lt;section&gt;
  &lt;p&gt;section 1&lt;/p&gt;
  &lt;button (click)=""scrollToSecondPage(slide2)""&gt;Go to section 2&lt;/button&gt;
&lt;/section&gt;  
&lt;section #slide2&gt;
  &lt;p&gt;section 2&lt;/p&gt;
&lt;/section&gt;
</code></pre>

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

<pre><code>scrollToSecondPage(el: any): void {
  el.scrollIntoView({ behavior: 'smooth' });
}
</code></pre>

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

<pre><code>it('should scroll down to section two', () =&gt; {
  let component = fixture.componentInstance;
  let spy = spyOn(component, 'scrollToSecondPage').and.callThrough();
  expect(spy).toHaveBeenCalled();
});
</code></pre>
",https://stackoverflow.com/questions/61673344/angular-how-to-write-a-unit-test-for-template-variable,"['angular', 'unit-testing', 'jasmine', 'angular-unit-test']",880,True,0,1
"How to recognize what unit testing framework is used in a project in Visual Studio, .NET?","<p>I am working with a Visual Studio C# project and I need to know what unit testing framework is it using, but there is no one to ask about it.</p>

<p>How could I check it?</p>
",https://stackoverflow.com/questions/59746989/how-to-recognize-what-unit-testing-framework-is-used-in-a-project-in-visual-stud,"['c#', 'visual-studio', 'unit-testing', 'automated-tests', 'visual-studio-2019']",699,True,0,3
testing component with react-aad-msal,"<p>I need to write unit test cases for below class by mocking react-aad-msal.
how can I mock it? I have read that enzyme mock the components, but I get error as </p>

<pre><code>console.error node_modules/react-aad-msal/dist/commonjs/Logger.js:69
      [ERROR] ClientAuthError: User login is required.
</code></pre>

<p>Which I think is not related to Unit testing</p>

<pre><code>    import React, { Component } from ""react"";
    import ""./App.css"";
    import { authProvider } from ""./authProvider"";
    import { AzureAD, AuthenticationState, IAzureADFunctionProps } from ""react-aad-msal"";
    import Home from ""./pages/Home"";
    import { ThemeProvider } from ""styled-components"";
    import { lightTheme } from ""./themes"";

    export default class App extends Component&lt;{}, { theme: any }&gt; {
      static displayName = App.name;
      constructor(props: any) {
        super(props);

        this.state = {
          theme: lightTheme
        };
      }

      render() {
        return (
          &lt;AzureAD provider={authProvider} forceLogin&gt;
            {({ authenticationState, accountInfo, error }: IAzureADFunctionProps) =&gt; {
              switch (authenticationState) {
                case AuthenticationState.Authenticated:
                  return (
                    &lt;ThemeProvider theme={this.state.theme}&gt;
                      &lt;Home userInfo={accountInfo!=null? accountInfo.account.name: """"} /&gt;
                    &lt;/ThemeProvider&gt;
                  );
                case AuthenticationState.Unauthenticated:
                  return (
                    &lt;div&gt;
                      {
                        &lt;p&gt;
                          &lt;span&gt;
                            An error {error} occured during authentication, please try
                            again!
                          &lt;/span&gt;
                        &lt;/p&gt;
                      }
                      &lt;p&gt;
                        &lt;span&gt;Hey stranger, you look new!&lt;/span&gt;
                      &lt;/p&gt;
                    &lt;/div&gt;
                  );
                case AuthenticationState.InProgress:
                  return &lt;p&gt;Authenticating...&lt;/p&gt;;
              }
            }}
          &lt;/AzureAD&gt;
        );
      }
    }
</code></pre>
",https://stackoverflow.com/questions/60275938/testing-component-with-react-aad-msal,"['javascript', 'reactjs', 'jestjs', 'react-aad-msal']",4194,False,6,1
How to test @RestController when all of the mapping return with ResponseEntity?,"<p>I need to do unit testing on a @RestController where every method returns with a ResponseEntity.
I have a CRUD repository to use but I don't know how can I test it with the ResponseEntities.</p>

<pre><code>@RestController
@RequestMapping(""/events"")
public class EventController {
    @Autowired
    private EventRepository eventRepository;

    @GetMapping("""")
    public ResponseEntity&lt;Iterable&lt;Event&gt;&gt; getAll() {
        return ResponseEntity.ok(eventRepository.findAll());
    }

    @GetMapping(""/{id}"")
    public ResponseEntity&lt;Event&gt; get(@PathVariable Integer id) {
        Optional&lt;Event&gt; event= eventRepository.findById(id);
        if (event.isPresent()) {
            return ResponseEntity.ok(event.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("""")
    public ResponseEntity&lt;Event&gt; post(@RequestBody Event event) {
        EventsavedEvent = eventRepository.save(event);
        return ResponseEntity.ok(savedEvent);
    }
.
.
.

</code></pre>
",https://stackoverflow.com/questions/61143558/how-to-test-restcontroller-when-all-of-the-mapping-return-with-responseentity,"['java', 'unit-testing', 'spring-mvc', 'testing', 'spring-restcontroller']",365,True,0,1
How to mock Fastify plugin,"<p>I am trying to write unit testing for fastify application which also has custom fastify plugin. 
Is there a way we can mock fastify plugin? I tried mocking using Jest and Sinon without much success.</p>
",https://stackoverflow.com/questions/59965807/how-to-mock-fastify-plugin,"['unit-testing', 'mocking', 'fastify']",3782,True,0,4
How to create unit test cases for Ansible functionalities?,"<p>I want to add unit testing for my ansible playbook. I am new to this and have tried few things but didn't understood much. How can I start on this and write a test case properly?</p>

<p>Following is the simple example:</p>

<pre><code>  yum: 
    name: httpd 
    state: present
</code></pre>
",https://stackoverflow.com/questions/61243490/how-to-create-unit-test-cases-for-ansible-functionalities,"['unit-testing', 'ansible', 'yaml']",658,True,4,1
Flutter Integartion testing using Gitlab ci,"<p>I am trying to do integration testing of an app built with flutter. I am using cirrusci/flutter docker image for unit testing. I am unable to find any tutorials for integration testing. can anyone help me? Thanks</p>
",https://stackoverflow.com/questions/61712256/flutter-integartion-testing-using-gitlab-ci,"['android', 'docker', 'flutter', 'gitlab-ci', 'gitlab-ci-runner']",245,False,2,0
How to handle and mock InterruptedException in Kafka producer,"<p>Kafka producer returns <strong>InterruptedException</strong> while producing message in some cases. I want to know about the way to handle and mock <strong>InterruptedException</strong> for unit testing rise by Kafka producer. In below my producer code added. Thank you.</p>

<pre class=""lang-java prettyprint-override""><code>
public void MyProducer(String msg, String key)
      throws ExecutionException, InterruptedException {
    // statements....
  }

</code></pre>
",https://stackoverflow.com/questions/60866687/how-to-handle-and-mock-interruptedexception-in-kafka-producer,"['apache-kafka', 'kafka-producer-api']",473,False,1,0
"How to unit test java code, which is using Reflections to populate subTypesOf a class?","<p>This is my code:</p>

<pre><code>protected void loadConverters() {
        // load all available converters
        Reflections reflections = new Reflections(""com.mypackage.MyClass"");

        Set&lt;Class&lt;? extends ContentConverter&gt;&gt; processors = reflections.getSubTypesOf(ContentConverter.class);
        for(Class&lt;? extends ContentConverter&gt; processorClass : processors) {
            try {
                if(Modifier.isAbstract(processorClass.getModifiers())) {
                    continue;
                }

                ContentConverter processor = processorClass.getDeclaredConstructor().newInstance();
                ReportOutputType type = processor.getOutputType();
                if(type == null) {
                    LOGGER.warn(""Class {} does not return a valid ReportOutputType, is not being loaded for processing."", processorClass);
                    continue;
                }

                // register
                AVAILABLE_CONVERTERS.put(type, processor);
            } catch (Exception e) {
                LOGGER.error(""Cannot instantiate step processor class"", e);
            }
        }
    }
</code></pre>

<p>So I'm writing the output to a variable AVAILABLE_CONTAINERS. I want to know if there is a way I can mimic the sub classes &amp; conduct unit testing of the above code. </p>
",https://stackoverflow.com/questions/59709823/how-to-unit-test-java-code-which-is-using-reflections-to-populate-subtypesof-a,"['java', 'spring-mvc', 'junit', 'reflection', 'spring-mvc-test']",39,False,0,0
Cannot find module &#39;react&#39; from &#39;/react/node_modules/react-redux/lib/components&#39;,"<p>Error: Cannot find module <code>react</code> from <code>/home/react/node_modules/react-redux/lib/components</code></p>

<p>I am using cypress for unit testing of the components and when I am running the tests I am facing the above error and 'react' is already installed in the dependencies.</p>
",https://stackoverflow.com/questions/60482744/cannot-find-module-react-from-react-node-modules-react-redux-lib-components,"['reactjs', 'react-redux', 'jestjs']",246,True,0,2
Vue how to test response to event emitted by child in parent,"<p>I'm trying to setup unit testing on a new Vue project that I'm working on. This is my first time doing unit testing on the frontend.  I'm using Jest and Vue-test-utils.</p>

<p>I've gotten stuck on how to test one of my components. The basic set up is like this:</p>

<pre><code>&lt;Grid&gt;
    &lt;GridItem @clicked=""toggleItem""/&gt;
&lt;/Grid&gt;
</code></pre>

<p>The toggleItem method on the parent emits an 'input' event. I'm trying to test that when the  emits a 'clicked' event, the parent emits an 'input' event.</p>

<p>I have setup my test to shallowMount the parent component. This is what my test looks like:</p>

<pre><code>it('clicking a GridItem should emit and input event', async () =&gt; {
  const gridItems = wrapper.findAll(GridItem);
  await gridItems.at(0).vm.$emit('clicked');
  expect(wrapper.emitted().input.length).toBe('1');
});
</code></pre>

<p>However, when I run this test, I get this error</p>

<pre><code>TypeError: _vm.toggleItem is not a function
</code></pre>

<p>Any ideas on why this is happening?</p>
",https://stackoverflow.com/questions/61681662/vue-how-to-test-response-to-event-emitted-by-child-in-parent,"['javascript', 'unit-testing', 'vue.js', 'jestjs']",141,False,1,0
hibernate mixes vividsolutions.jts Geometry with locationtech.jts.Geometry,"<p>In my JPA entity I have following:</p>

<pre><code>import org.locationtech.jts.geom.Geometry;
....
....
@Column(name = ""geometry"")
    private Geometry geometry;
</code></pre>

<p>I am using h2 gis for unit testing. When tests execute, it gives error:</p>

<pre><code>Caused by: org.h2.jdbc.JdbcSQLException: Feature not supported: ""converting to class com.vividsolutions.jts.geom.Geometry""
</code></pre>

<p>Why is that it is trying to map to a different class.</p>

<p>My deps are:</p>

<pre><code>&lt;dependency&gt;
            &lt;groupId&gt;org.locationtech.jts&lt;/groupId&gt;
            &lt;artifactId&gt;jts&lt;/artifactId&gt;
            &lt;version&gt;1.15.0&lt;/version&gt;
            &lt;type&gt;pom&lt;/type&gt;
        &lt;/dependency&gt;
&lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
            &lt;version&gt;1.4.197&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
&lt;dependency&gt;
            &lt;groupId&gt;org.orbisgis&lt;/groupId&gt;
            &lt;artifactId&gt;h2gis&lt;/artifactId&gt;
            &lt;version&gt;1.4.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>
",https://stackoverflow.com/questions/62323809/hibernate-mixes-vividsolutions-jts-geometry-with-locationtech-jts-geometry,"['hibernate', 'h2', 'jts']",1404,True,-1,1
React - jest Use custom state to check conditions in component,"<p>I want to use different state values to check if else part in a function - react unit testing
So i can get full coverage[click here to view code-left- testing code right- function to check]
<a href=""https://i.stack.imgur.com/v9YYn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/v9YYn.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63376017/react-jest-use-custom-state-to-check-conditions-in-component,"['reactjs', 'redux', 'jestjs', 'enzyme']",293,False,-1,2
Inserting a line of code in a method only when unit-testing,"<p>Hello i am unit testing a method which deals some <code>I/O</code> operations.I was wondering if there is some kind of way to pause that method for a specific time , <strong>at a specific line</strong> , without altering the original code.</p>

<p><strong>Original Method</strong></p>

<pre><code>public async Task&lt;int&gt; SomeMethodAsync()
{
    var x=DoSomething1();
    int value=await DoSomething2Async(); 
    return value;
}
</code></pre>

<p>Look at the method above.Is there any way from a <code>TestCase</code> to add a delay or a pause at a specific location in the target method?
I would like my method to become something like this <strong>Only when unit testing</strong> !:</p>

<p><strong>Desired method when unit testing</strong></p>

<pre><code>  public async Task&lt;int&gt; SomeMethodAsync()
    {
         var x=DoSomething1();   //line index=0
    #    await Task.Delay(delay) //delay set in the testcase
         int x=await DoSomething2Async();  //line index=1
         return x;  
    }
</code></pre>

<p><strong>Unit Test</strong></p>

<pre><code>[TestCase]
public void TestSomeMethodWithDelay()
{
    var delay=1000;
    int desiredLineIndex=1;
    int result=await SomeMethodAsync();
}
</code></pre>

<p>As you can see i would like when testing a method to insert some code before a target line , in my case an <code>await Task.Delay(interval)</code> where <code>interval</code> is set in the <code>TestCase</code>.
I do not want to modify/pollute the source code with preprocessor directives for testing.The only other way i could think is to use something like <code>System.Reflection.Emit</code> and rewrite the target method when testing.</p>

<p>Is there some other elegant way?</p>

<p><strong>P.S</strong> I just want , when running a particular set of tests to insert a delay between two <code>lines of code</code> without altering the original code.</p>

<p><strong>Update</strong>
The <code>SomeMethodAsync</code> is from another <code>dll</code>.The code must not be changed  ! The <code>DoSomething2Async</code> is an external call.</p>
",https://stackoverflow.com/questions/60548326/inserting-a-line-of-code-in-a-method-only-when-unit-testing,"['unit-testing', '.net-core', 'reflection', 'preprocessor', 'lines-of-code']",154,False,0,0
"While unit React-native test files with Mocha, it gives error unexpected tocken","<p>In a React-native project, I want to setup unit testing, For this I am using Mocha and Chai. When I run command <code>npm test</code> it executes <code>mocha __tests__/*.js</code> internally. In test file my code is following: </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 { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import { RefundedEmd } from './RefundedEmd';
import React from 'react';
import renderer from 'react-test-renderer';

describe('App', () =&gt; {
  it('renders correctly', () =&gt; {
    renderer.create(&lt;App /&gt;);
  });
});</code></pre>
</div>
</div>
</p>

<p>I get following error in console:</p>

<pre><code>C:\Technical work\Lorex\slf-mobile-impl\__tests__\App-test.js:1
import { expect } from 'chai';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\lib\mocha.js:311:36
    at Array.forEach (&lt;anonymous&gt;)
    at Mocha.loadFiles (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\lib\mocha.js:308:14)
    at Mocha.run (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\lib\mocha.js:849:10)
    at Object.exports.singleRun (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\lib\cli\run-helpers.js:108:16)
    at exports.runMocha (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\lib\cli\run-helpers.js:143:13)
    at Object.exports.handler.argv [as handler] (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\lib\cli\run.js:305:3)
    at Object.runCommand (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\node_modules\yargs\lib\command.js:242:26)
    at Object.parseArgs [as _parseArgs] (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\node_modules\yargs\yargs.js:1087:28)
    at Object.parse (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\node_modules\yargs\yargs.js:566:25)
    at Object.exports.main (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\lib\cli\cli.js:68:6)
    at Object.&lt;anonymous&gt; (C:\Technical work\Lorex\slf-mobile-impl\node_modules\mocha\bin\mocha:133:29)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm ERR! Test failed.  See above for more details.
</code></pre>
",https://stackoverflow.com/questions/60387993/while-unit-react-native-test-files-with-mocha-it-gives-error-unexpected-tocken,"['react-native', 'mocha.js', 'enzyme', 'chai']",52,False,2,0
One Action returns Future[Result] while other returns Accumultor[],"<p>I have created the following two <code>Actions</code></p>
<pre><code>def action1: Action[Either[MaxSizeExceeded, AnyContent]] = silhouette.SecuredAction.async(parse.maxLength(maxAllowedBodySize, parse.anyContent)(materializer)) { ...}


def action2:Action[AnyContent] = silhouette.UserAwareAction.async { ...}
</code></pre>
<p>While unit testing them, I found that result of <code>action1</code>'s return is <code>Future[Result]</code> while that of <code>action2</code> is <code>Accumulator[ByteString, Result]</code></p>
<pre><code>val response:Accumulator[ByteString,Result] = testEnv.controller.action1(request)

val response:Future[Result] = userTestEnv.controller.action2(request)
</code></pre>
<p>I can't quite figure out why there is a difference? Why are return type different?</p>
",https://stackoverflow.com/questions/63371177/one-action-returns-futureresult-while-other-returns-accumultor,"['scala', 'playframework', 'playframework-2.6']",60,False,-2,1
How can i create Unit test case for SharedPreference?,"<p>I want to test Unit test for SharedPreference. I don't know how can i mock these values, I just started unit testing. Can anyone please give me solution of this method, how can i test this method. </p>

<pre><code>public static void oneMethod(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(""Constant"", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(""Value"", 3);
    editor.apply();
    Model.setValue(true);
}
</code></pre>
",https://stackoverflow.com/questions/59954971/how-can-i-create-unit-test-case-for-sharedpreference,"['java', 'android', 'unit-testing', 'mockito', 'junit4']",196,False,0,1
Mock a method of a class inside action-result C# using moq and nunit,"<p>I am doing unit testing of controllers in my asp.net core project. In one section, there is a code like this instantiating an object of class and calling its method.</p>

<pre><code>public class ControllerNameController: ControllerBase{
    private IDependency _dependency;
    public ControllerNameController(IDependency dependency){
         _dependency = dependency
    }

       [HttpGet, Route(""Get"")]
        public ActionResult&lt;dynamic&gt; Get()
        {
            ......

            string someString = ""abcd"";
            ClassOne classOneObject = new ClassOne(_dependency);
            classOneObject.ClassOneMethod(someString);

            ..........

            return .....

        }
}
</code></pre>

<p>I am being unable to mock this function. How can I do this?</p>
",https://stackoverflow.com/questions/60145199/mock-a-method-of-a-class-inside-action-result-c-using-moq-and-nunit,"['c#', 'asp.net-core', 'nunit', 'moq']",324,True,4,1
ag-grid unit testing using jasmine karma in angular9,"<p>I have defined my ag-grid as follows:
.HTML page:</p>
<pre><code>&lt;button (click)=&quot;getSelectedRows()&quot;&gt;Get Selected Rows&lt;/button&gt;

&lt;ag-grid-angular
#agGrid
    style=&quot;width: 500px; height: 500px;&quot;
    class=&quot;ag-theme-alpine&quot;
    [rowData]=&quot;rowData | async&quot;
    [columnDefs]=&quot;columnDefs&quot;
    rowSelection=&quot;multiple&quot;
    &gt;
&lt;/ag-grid-angular&gt;
</code></pre>
<p>the TS page:</p>
<pre><code>import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { GridOptions } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';


@Component({
  selector: 'app-samplegrid',
  templateUrl: './samplegrid.component.html',
  styleUrls: ['./samplegrid.component.scss']
})
export class SamplegridComponent implements OnInit {
  @ViewChild('agGrid') agGrid: AgGridAngular;


 columnDefs = [
  {headerName: 'Make', field: 'make', sortable: true, filter: true,
  checkboxSelection: true},
  {headerName: 'Model', field: 'model', sortable: true, filter: true},
  {headerName: 'Price', field: 'price', sortable: true, filter: true}
];
rowData: any;

  constructor(private http:HttpClient) { }

  ngOnInit(){
    this.rowData = this.http.get('https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/sample-data/smallRowData.json');
    
    
  }
  getSelectedRows(){
    const selectedNodes = this.agGrid.api.getSelectedNodes();
        const selectedData = selectedNodes.map( node =&gt; node.data );
        const selectedDataStringPresentation = selectedData.map( node =&gt; node.make + ' ' + node.model).join(', ');
        alert(`Selected nodes: ${selectedDataStringPresentation}`);
        return selectedDataStringPresentation;
    }
  }
</code></pre>
<p>My requirement is to perform unit testing for this component  to check cell content and also when the particular row is selected.</p>
<p>I have written my test scripts as follows:</p>
<pre><code>it('the grid cells should be as expected', () =&gt; {
  const appElement = fixture.nativeElement;
  const cellElements = appElement.querySelectorAll('.ag-cell-value');
  console.log(cellElements,&quot;agGrid&quot;);
  expect(cellElements.length).toEqual(9);
  expect(cellElements[0].textContent).toEqual(&quot;Toyota&quot;);
  expect(cellElements[1].textContent).toEqual(&quot;Celica&quot;);
  expect(cellElements[2].textContent).toEqual(&quot;35000&quot;);
});
</code></pre>
<p>this is failing with error :TypeError: Cannot read property 'textContent' of undefined</p>
<p>Also i am trying to imitate a select event and in order to get the selectd row i have written a test script as :</p>
<pre><code> it('getting the selected row data from the grid.', () =&gt; {
    fixture.detectChanges();
    expect(component.agGrid.api).toBeTruthy();
    let user_Data=component.agGrid.api.getSelectedRows();
    expect(user_Data).toBeDefined();
    console.log(user_Data,&quot;@ user_Data&quot;)
    
});
</code></pre>
<p>this is not failing but throwing user_data as blank.I wanted to know if there is any particular way of mocking data for ag-grid or mock ag-grid as a whole for unit testing purpose.
ANy help is welcomed.TIA.</p>
",https://stackoverflow.com/questions/62635647/ag-grid-unit-testing-using-jasmine-karma-in-angular9,"['angular', 'unit-testing', 'karma-jasmine', 'ag-grid-angular']",2954,False,0,0
Is there anyway to mock terraform data source,"<p>I am working on unit testing for terraform. For some modules, I have to authorized into AWS to be able to retrieve terraform data source. Is there anyway to mock or override data source for something like below?</p>
<pre><code>data &quot;aws_region&quot; &quot;current&quot; {
}
</code></pre>
<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/62782091/is-there-anyway-to-mock-terraform-data-source,['terraform'],2491,True,4,2
Unable to Deserialize - Jackson LocalDate/Time - JUnit,"<p>I need to deserialize the Json to Java Objects in Junit. I have Json file like </p>

<pre><code>{
   ""studentId"":57,
   ""JoinedDate"":""31-12-2019"",
   ""DOB"":""08-06-1998""  

}
</code></pre>

<p>I have class for the same to map </p>

<pre><code>public class Student{

    private long studentId ;

    private LocalDate JoinedDate;

    private LocalDate DOB ;

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public LocalDate getJoinedDate() {
        return JoinedDate;
    }

    public void setJoinedDate(LocalDate joinedDate) {
        JoinedDate = joinedDate;
    }

    public LocalDate getDOB() {
        return DOB;
    }

    public void setDOB(LocalDate dOB) {
        DOB = dOB;
    }
</code></pre>

<p>I need to write centralized builder for Unit testing project similar like this </p>

<pre><code>builder.deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern(dateFormat)));
            builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
</code></pre>

<p>Main Class</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public class Main{
    @Test
    public void contextLoads() {
        assertTrue(true);
    }

}
</code></pre>

<p>Unit testing Project looks like</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public class StudentTest{

private ObjectMapper jsonObjectMapper;
@Before
public void setUp() throws IOException {

    jsonObjectMapper = new ObjectMapper();
    studentJson = IOUtils.toString(getClass().getResourceAsStream(CommonTestConstants.StudentPath+ ""/Student.json""));


}
</code></pre>

<p>I'm getting a error while mapping the objects -
<strong>com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type <code>java.time.LocalDate</code> from String ""31-12-2019"": Failed to deserialize java.time.LocalDate:</strong></p>

<p>Another Error - Sometimes.</p>

<blockquote>
  <p>com.fasterxml.jackson.databind.JsonMappingException: Text '31-12-2019'
  could not be parsed at index 0</p>
</blockquote>

<p>I assume LocalDate format mismatch is the issue. Any suggestion to make it centralized way instead of specifying the format above the fields. Any one please advise?</p>

<p>Reference - <a href=""https://stackoverflow.com/questions/51210284/spring-boot-jacksontester-custom-serializer-not-registered"">Spring Boot JacksonTester custom serializer not registered</a></p>
",https://stackoverflow.com/questions/62233024/unable-to-deserialize-jackson-localdate-time-junit,"['java', 'jackson', 'junit5', 'jackson-databind']",2129,True,0,2
How to resolve the error &quot;ERR! code ELIFECYCLE&quot;?,"<p>I am using the Jest to perform the unit testing.</p>
<pre><code>&quot;jest&quot;: &quot;^26.4.2&quot;,
&quot;jest-preset-angular&quot;: &quot;^8.3.1&quot;
</code></pre>
<p>All the test has been passed and ran but got an error as below</p>
<pre><code>Test Suites: 20 passed, 20 total
Tests:       26 passed, 26 total
Snapshots:   2 obsolete, 5 passed, 5 total
Time:        92.961 s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! idp@0.0.0 test:app: `jest --config ./jest.app.config.js --no-cache`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the idp@0.0.0 test:app 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!     /Users/macbook/.npm/_logs/2020-09-15T09_19_42_790Z-debug.log
</code></pre>
<p>I tried the below command from the google search, however, it is not working</p>
<pre><code>npm cache clean --force

rm -rf node_modules

npm install
</code></pre>
<h2>error from logs</h2>
<pre><code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'test:app' ]
2 info using npm@6.14.8
3 info using node@v14.5.0
4 verbose run-script [ 'pretest:app', 'test:app', 'posttest:app' ]
5 info lifecycle idp@0.0.0~pretest:app: idp@0.0.0
6 info lifecycle idp@0.0.0~test:app: idp@0.0.0
7 verbose lifecycle idp@0.0.0~test:app: unsafe-perm in lifecycle true
8 verbose lifecycle idp@0.0.0~test:app: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/macbook/Projects/Playtime Projects/IDP/Idp.Bx.Ui/idp/node_modules/.bin:/usr/local/opt/helm@2/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:~/.dotnet/tools:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Applications/Xamarin Workbooks.app/Contents/SharedSupport/path-bin
9 verbose lifecycle idp@0.0.0~test:app: CWD: /Users/macbook/Projects/Playtime Projects/IDP/Idp.Bx.Ui/idp
10 silly lifecycle idp@0.0.0~test:app: Args: [ '-c', 'jest --config ./jest.app.config.js --no-cache' ]
11 silly lifecycle idp@0.0.0~test:app: Returned: code: 1  signal: null
12 info lifecycle idp@0.0.0~test:app: Failed to exec test:app script
13 verbose stack Error: idp@0.0.0 test:app: `jest --config ./jest.app.config.js --no-cache`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.&lt;anonymous&gt; (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:314:20)
13 verbose stack     at ChildProcess.&lt;anonymous&gt; (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:314:20)
13 verbose stack     at maybeClose (internal/child_process.js:1051:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5)
14 verbose pkgid idp@0.0.0
15 verbose cwd /Users/macbook/Projects/Playtime Projects/IDP/Idp.Bx.Ui/idp
16 verbose Darwin 19.6.0
17 verbose argv &quot;/usr/local/bin/node&quot; &quot;/usr/local/bin/npm&quot; &quot;run&quot; &quot;test:app&quot;
18 verbose node v14.5.0
19 verbose npm  v6.14.8
20 error code ELIFECYCLE
21 error errno 1
22 error idp@0.0.0 test:app: `jest --config ./jest.app.config.js --no-cache`
22 error Exit status 1
23 error Failed at the idp@0.0.0 test:app script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
</code></pre>
",https://stackoverflow.com/questions/63898933/how-to-resolve-the-error-err-code-elifecycle,"['javascript', 'node.js', 'angular', 'jestjs', 'jest-preset-angular']",13114,True,2,3
Request user for (some kind of) process verification before merging,"<p>I have a Git repo, managed in GitHub. I want to be able to allow merge to <code>master</code>, only after a user would manually verify that they took some action.</p>
<p>I have an application that has some unit testing mechanism. For whatever reasons, I can't run those tests on CircleCI (or similar) which is automated solution. I require my developers to run this unit testing manually on their local machines. In order for them not to forget to do so, I want them to verify it (preferably on GitHub) before they can merge.</p>
<p>I imagined it as some kind of a checkbox that needs to be marked in order to be able to merge.</p>
",https://stackoverflow.com/questions/62874299/request-user-for-some-kind-of-process-verification-before-merging,"['github', 'git-merge', 'pull-request']",13,False,0,0
"How To Mock Repository, Service and Controller In NestJS (Typeorm &amp; Jest)","<p>I'm new at typescript. My Nestjs project app is something like this. I'm trying to use repository pattern, so i separated business logic (service) and persistance logic (repository)</p>

<p><strong>UserRepository</strong></p>

<pre><code>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { UserEntity } from './entities/user.entity';

@Injectable()
export class UserRepo {
  constructor(@InjectRepository(UserEntity) private readonly repo: Repository&lt;UserEntity&gt;) {}

  public find(): Promise&lt;UserEntity[]&gt; {
    return this.repo.find();
  }
}
</code></pre>

<p><strong><em>UserService</em></strong></p>

<pre><code>import { Injectable } from '@nestjs/common';
import { UserRepo } from './user.repository';

@Injectable()
export class UserService {
  constructor(private readonly userRepo: UserRepo) {}

  public async get() {
   return this.userRepo.find();
  }
}
</code></pre>

<p><strong><em>UserController</em></strong></p>

<pre><code>import { Controller, Get } from '@nestjs/common';

import { UserService } from './user.service';

@Controller('/users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  // others method //

  @Get()
  public async getUsers() {
    try {
      const payload = this.userService.get();
      return this.Ok(payload);
    } catch (err) {
      return this.InternalServerError(err);
    }
  }
}
</code></pre>

<p>How do i create unit testing for repository, service &amp; controller without actually persist or retrieve data to DB (using mock)?</p>
",https://stackoverflow.com/questions/60652617/how-to-mock-repository-service-and-controller-in-nestjs-typeorm-jest,"['node.js', 'typescript', 'jestjs', 'nestjs', 'typeorm']",21903,True,12,1
Execute logic inside RxJS pipe with unit tests,"<p>Trying to initialize the variable x inside the pipe() method when doing unit testing, but it does not get called. How do I run method calls/initialization logic inside pipe()? Simply calling <code>component.ngOnInit()</code> inside the unit test does not help.</p>
<pre><code>ngOnInit() {
    this.foo$ = this.myService.bar$.pipe(
      ....
      map(bar =&gt; {
        this.x = bar.x;        // how do I call this within unit test 
        return bar;
      })
    );  
}

it('should init x', () =&gt; {
    component.ngOnInit();
    expect(component.x).toEqual(bar.x); //fails
});
</code></pre>
",https://stackoverflow.com/questions/63924303/execute-logic-inside-rxjs-pipe-with-unit-tests,"['angular', 'unit-testing', 'rxjs', 'jasmine', 'karma-jasmine']",211,False,1,1
Get the query generated by LINQ toward EF Core SqLite In Memory,"<p>I am using EF core SQLite In memory for unit testing.
I want to see the query is generated by LINQ like SQL Profiler so that I could optimize the query.
Is there any way to check the query?</p>
",https://stackoverflow.com/questions/60921160/get-the-query-generated-by-linq-toward-ef-core-sqlite-in-memory,"['c#', 'entity-framework', 'sqlite', 'asp.net-core']",528,True,1,3
Unit testing with inject annotation,"<p>How do I unit test a class that uses <code>@inject</code> annotation:class A{</p>
<pre><code>@inject
private B b;

void foo(){
    b.funcInClassB();
}
</code></pre>
<p>I am new to unit testing and having troubles testing this function because when calling <code>b.funcInClassB()</code> it throws NullPointerException because b is null.
I wrote the following test:</p>
<pre><code>class Atest{
   @MockBean
   private B b;
   @Test
   void foo(){
     when(b.funcInClassB()).willReturn(&quot;something&quot;);
      A a = new A();
      a.foo();
   }
}
</code></pre>
",https://stackoverflow.com/questions/63783609/unit-testing-with-inject-annotation,"['java', 'unit-testing', 'dependency-injection', 'mocking']",235,True,0,1
How to create and execute unit test cases for Xamarin.forms Android project like all the methods defined in MainActivity.cs class?,"<p>As per requirement, we need to write unit test cases in our Xamarin.Forms project. We want to do unit testing for Android and iOS projects as well. For example - creating and executing unit test cases for <code>MainActivity.cs</code> and <code>AppDelegate.cs</code> methods.</p>
",https://stackoverflow.com/questions/63603349/how-to-create-and-execute-unit-test-cases-for-xamarin-forms-android-project-like,"['c#', 'unit-testing', 'xamarin.forms', 'xamarin.android', 'xamarin.ios']",275,False,-1,1
Maven compile behavior when running `mvn install` followed by &#39;mvn deploy -Dmaven.install.skip=True&#39;,"<p>Working with a multi-module maven project. Executing following steps</p>

<pre><code>mvn clean install
</code></pre>

<p>to check if program works fine(compilation, Unit Testing, installation), followed by</p>

<pre><code>mvn deploy -DskipTests -Dmaven.install.skip=True
</code></pre>

<p>to deploy without installation. My question is, does <code>-Dmaven.install.skip=True</code> skips <code>install goal</code> or <code>install phase</code>. Will <code>compile phase</code> would potentially be running twice? Usiing <code>maven-compiler-plugin</code> version 3.1</p>
",https://stackoverflow.com/questions/61758859/maven-compile-behavior-when-running-mvn-install-followed-by-mvn-deploy-dmave,"['java', 'maven', 'maven-compiler-plugin']",69,False,1,0
How to disable Morgan (request logger) during unit test?,"<p>I use Morgan (default express generator request logger), and I'm trying to disable it during unit testing.</p>

<p>Currently I'm using the default configuration, which loads Morgan in <code>app.js</code></p>

<pre><code>const logger = require('morgan');
...
const app = express();
...
app.use(logger('dev'));
</code></pre>

<p>I tried moving the code to <code>bin/www</code> (which imports the express app and starts the server), but it wouldn't work...
Any ideas?</p>
",https://stackoverflow.com/questions/60129677/how-to-disable-morgan-request-logger-during-unit-test,"['javascript', 'node.js', 'unit-testing', 'express', 'jestjs']",2064,True,8,1
How to write the unit test case for angular material dialog,"<p>Question: How to perform unit test in angular on material dialog box. I tried many things but it seems to be not working. I am new to unit testing, please help <br>
<strong>Dialog-modal.component.ts</strong><br></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { DialogUnitTestComponent } from '../dialog-unit-test/dialog-unit-test.component';
@Component({
  selector: 'app-dialog-modal',
  templateUrl: './dialog-modal.component.html',
  styleUrls: ['./dialog-modal.component.scss']
})
export class DialogModalComponent implements OnInit {

  constructor(public dialog: MatDialog) { }

  ngOnInit(): void {
  }
  openModal() {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
    id: 1,
    Name: ""Keshav Sahu"",
    title: 'Angular Dialog Test'
    };
    const dialogRef = this.dialog.open(DialogUnitTestComponent, dialogConfig);
    dialogRef.afterClosed().subscribe(result =&gt; {
    console.log(""Dialog was closed"" );
    console.log(result)
    });
    }

}
</code></pre>

<p><strong>Dialog-Unit-Test.component.ts</strong><br></p>

<pre><code>import { DialogModalComponent } from './../dialog-modal/dialog-modal.component';
import { Component, OnInit , Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from ""@angular/material/dialog"";
@Component({
  selector: 'app-dialog-unit-test',
  templateUrl: './dialog-unit-test.component.html',
  styleUrls: ['./dialog-unit-test.component.scss']
})
export class DialogUnitTestComponent implements OnInit {

modalTitle: string;
  constructor(@Inject(MAT_DIALOG_DATA) public data: any,public dialogRef: MatDialogRef&lt;DialogUnitTestComponent&gt;) {
    this.modalTitle = data.title;
    console.log(data)
    }

  ngOnInit(): void {
  }

}
</code></pre>

<p><strong>Dialog-unit-test.component.html</strong>
<br></p>

<pre><code>&lt;h2 mat-dialog-title&gt;{{modalTitle}}&lt;/h2&gt;
&lt;mat-dialog-content&gt;Do you wish to continue previous shopping?&lt;/mat-dialog-content&gt;
&lt;mat-dialog-actions&gt;
&lt;button mat-button [mat-dialog-close]=""false""&gt;No&lt;/button&gt;
&lt;button mat-button [mat-dialog-close]=""true""&gt;Yes&lt;/button&gt;
&lt;/mat-dialog-actions&gt;
</code></pre>
",https://stackoverflow.com/questions/62284315/how-to-write-the-unit-test-case-for-angular-material-dialog,"['angular', 'angular-material', 'angular9', 'angular-unit-test']",2798,True,0,1
xunit testing to see if a specific value is there in the list,"<p>I am writing x-unit testing.</p>

<p>I want to check if list contains the newly added value.</p>

<p>I tried the below code but i am not getting the result</p>

<pre><code>_record.Add(new PortfolioCompanyLinkModel { Id = 3, PortfolioCompanyId = 1, URL = ""www.historiclreports2.com"", LinkName = ""Historical Reports"", ToBeDeleted = false, IsExternalLink = false, LinkId = 1 });
_record.Add(new PortfolioCompanyLinkModel { Id = 4, PortfolioCompanyId = 1, URL = ""www.SalesForce.com"", LinkName = ""SalesForce"", ToBeDeleted = false, IsExternalLink = false, LinkId = 2 });
var repo = new PortfolioCompanyLinkRepository(dbContext, obj.HttpContextAccessor);
var update = await repo.GetOne(2);
_record.Add(new PortfolioCompanyLinkModel { Id = update.Id, PortfolioCompanyId = update.PortfolioCompanyId, URL = ""www.historiclreportstest.com"", LinkName = update.Link.Name, ToBeDeleted = false, IsExternalLink = true, LinkId = update.LinkId });
var delete = await repo.GetOne(1);
_record.Add(new PortfolioCompanyLinkModel { Id = delete.Id, PortfolioCompanyId = delete.PortfolioCompanyId, URL = delete.URL, LinkName = delete.Link.Name, ToBeDeleted = true, IsExternalLink = delete.Link.IsExternalLink, LinkId = delete.LinkId });
await repo.AddUpdateDelete(_record);
await repo.SaveAsync();

var actual = await repo.GetAll();
Assert.Collection(actual, item =&gt; Assert.Contains(""www.historiclreports2.com"", item.URL));
</code></pre>

<p>How do i check if actual has www.historiclreports2.com as URL ?</p>
",https://stackoverflow.com/questions/59634690/xunit-testing-to-see-if-a-specific-value-is-there-in-the-list,"['c#', 'xunit']",1285,False,1,1
ReferenceError: formData is not defined,"<p>I am writing a unit testing code for the Ajax and Laravel project. I am trying to test one function.</p>

<pre><code>&lt;script&gt;
    $(document).ready(function () {
        $('#postAdd').click(function(e){

            e.preventDefault();

            var form = $('#addPost');
            formData.append('file', $('input[type=file]')[0].files[0]);

            $.ajax({
                type: ""POST"",
                url: ""{{ route('posts.store') }}"",
                data: formData,
                success: function (response) {
                    console.log(response)
                },
                error: function (error) {
                    console.log(error)
                }
            })
        })
    })
&lt;/script&gt;
</code></pre>

<p>In the browser, this works ok. but when testing I get below error in console</p>

<blockquote>
  <p>ReferenceError: formData is not defined</p>
</blockquote>
",https://stackoverflow.com/questions/61903175/referenceerror-formdata-is-not-defined,"['ajax', 'laravel-5.8']",12386,True,1,1
go/kubernetes - runtime.notRegisteredErr,"<p>I'm doing some unit testing and part of the function does this -</p>
<pre><code>    o := &amp;corev1.Secret{}
    if err := c.Scheme.Convert(c.Object, o, nil); err != nil {
        return o, err
    }

</code></pre>
<p>When I'm running the unit test it's throwing this error <code>&amp;runtime.notRegisteredErr{schemeName:&quot;pkg/runtime/scheme.go:101&quot;, gvk:schema.GroupVersionKind{Group:&quot;&quot;, Version:&quot;v1&quot;, Kind:&quot;secret&quot;}, target:runtime.GroupVersioner(nil)</code></p>
<p>even though I generate a new schema with CoreV1 Secret &amp; SecretList</p>
<pre><code>func schemeGet() *runtime.Scheme {
    s := runtime.NewScheme()
    s.AddKnownTypes(corev1.SchemeGroupVersion,
        &amp;corev1.Secret{},
        &amp;corev1.SecretList{},
    )
    return s
}
</code></pre>
<p>Any help is appreciated.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/62648908/go-kubernetes-runtime-notregisterederr,"['go', 'kubernetes']",497,True,0,1
Firebase - cloud firestore - unit testing fails with error - TypeError: The &quot;path&quot; argument must be of type string,"<p>Firebase - cloud firestore - unit testing fails with error 
- TypeError: The ""path"" argument must be of type string.</p>

<p>Otherwise, it works fine when run with NodeJS command 'node index.js'
I use service account and NodeJS</p>

<p><strong>myservice.js</strong></p>

<pre><code>
var admin = require(""firebase-admin"");

var serviceAccount = require(""./sakey.json"");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: ""https://myapp.firebaseio.com""
});

const db = admin.firestore();


const getData = async () =&gt; {
    const snapshot = await db.collection('users').get()
    return snapshot.docs.map(doc =&gt; doc.data())
}

module.exports = { getData }

</code></pre>

<p><strong>Test Case</strong></p>

<pre><code>const { getData } = require('./myservice')

describe('my test suite', () =&gt; {

    it('Retrieve data', async () =&gt; {
        let result = await getData();
        return result().then(data =&gt; expect(data).toBeDefined())
    }
}

</code></pre>

<p><strong>Error</strong></p>

<pre><code>TypeError: The ""path"" argument must be of type string. Received type objectTypeError [ERR_INVALID_ARG_TYPE]: The ""path"" argument must be of type string. Received type object

      at GrpcClient.loadProto (node_modules/google-gax/src/grpc.ts:166:23)
      at new FirestoreClient (node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js:113:38)
      at ClientPool.clientFactory (node_modules/@google-cloud/firestore/build/src/index.js:329:26)
      at ClientPool.acquire (node_modules/@google-cloud/firestore/build/src/pool.js:87:35)
      at ClientPool.run (node_modules/@google-cloud/firestore/build/src/pool.js:164:29)
      at node_modules/@google-cloud/firestore/build/src/index.js:957:30
      at Firestore._retry (node_modules/@google-cloud/firestore/build/src/index.js:822:38)
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>...
  ""dependencies"": {
    ""dotenv"": ""^8.2.0"",
    ""firebase-admin"": ""^8.10.0"",
    ""moment"": ""^2.24.0""
  },
  ""devDependencies"": {
    ""@types/jest"": ""^25.1.4"",
    ""jest"": ""^25.1.0""
  }
...
</code></pre>
",https://stackoverflow.com/questions/60802569/firebase-cloud-firestore-unit-testing-fails-with-error-typeerror-the-pat,"['node.js', 'firebase', 'google-cloud-firestore', 'jestjs']",319,True,0,1
How to unit test services.AddHttpClient() registration in dotnet core V2.2,"<p>I am working on Web API dotnet core V2.2 project. I have the below named client registered in my Startup.cs file. I want to do unit testing using NSubstitute to make may code coverage for the below method. Can someone help me on this. Thanks in advance.</p>

<pre><code>public void ConfigureServices(IServiceCollection services) {
    services.AddHttpClient(""myapi"", (serviceProvider, client) = &gt;{
    var config = serviceProvider.GetService &lt; IConfiguration &gt; ();
    client.BaseAddress = new URI(config[""mybaseURL""]);
});
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/59706073/how-to-unit-test-services-addhttpclient-registration-in-dotnet-core-v2-2,"['c#', 'unit-testing', 'asp.net-core', '.net-core']",701,False,6,1
Unit testing with Jasmine Marbles does not cover code in Code Coverage report,"<p>When I use Jasmine marbles for unit testing margeMap and switchMap, those specific blocks don't cover in code coverage report.</p>

<p>Is there a way to unit test margeMap and switchMap blocks so that they would be covered in code coverage report?</p>
",https://stackoverflow.com/questions/60275916/unit-testing-with-jasmine-marbles-does-not-cover-code-in-code-coverage-report,"['angular', 'jasmine', 'karma-coverage', 'jasmine-marbles']",81,False,0,0
Spark unit test -- Mock Azure SQLJDBC connection,"<p>I want to unit test the below piece of code so that i can get good code coverage. I am using <strong>FunSuite with Mockito</strong>. Can you please let me know how can i mock the database connectiion and do the unit testing.</p>
<pre><code>def getSummaryConfig() : Config = {
    Config(Map(
      &quot;url&quot;            -&gt; configUtil.getProperty(&quot;azure.host.name&quot;),
      &quot;databaseName&quot;   -&gt; configUtil.getProperty(&quot;azure.database.name&quot;),
      &quot;dbTable&quot;        -&gt; configUtil.getProperty(&quot;azure.summary.table&quot;),
      &quot;user&quot;           -&gt; configUtil.getProperty(&quot;azure.user.name&quot;),
      &quot;password&quot;       -&gt; configUtil.getProperty(&quot;azure.database.password&quot;)
    ))
  }

def getSummaryDF(summaryConfig : Config) : DataFrame = {
    val summaryDF = spark.read.option(&quot;driver&quot;, &quot;com.microsoft.sqlserver.jdbc.SQLServerDriver&quot;).sqlDB(summaryConfig)
    summaryDF
  }

val summaryConfig = getSummaryConfig()
val summaryDF  = getSummaryDF(summaryConfig)
</code></pre>
",https://stackoverflow.com/questions/63533823/spark-unit-test-mock-azure-sqljdbc-connection,"['scala', 'unit-testing', 'apache-spark', 'apache-spark-sql', 'mockito']",132,False,2,0
how to update state in mockstore in ngrx unit testing?,"<p>I have a object defined as:</p>

<pre class=""lang-js prettyprint-override""><code>obj:{
  name:""string"",
  system:""string""
}
</code></pre>

<p>however I am trying to update the value in mockstore as:</p>

<pre class=""lang-js prettyprint-override""><code>store.setState({
  name:""Rose"",
  system:""Updated Dummy""
});
store.refreshState();
fixture.detectChanges();
</code></pre>

<p>but the value  is not updating. How can I update the value and then verify that it has been updated as a part of unit testing?</p>
",https://stackoverflow.com/questions/62134764/how-to-update-state-in-mockstore-in-ngrx-unit-testing,"['angular', 'unit-testing', 'ngrx']",2092,True,2,1
Go interface: Cannot assign value to unexported field,"<p>I try to mock some struct for unit testing and I use following <a href=""https://blog.codecentric.de/2019/07/gomock-vs-testify/#testifymock"" rel=""nofollow noreferrer"">site</a></p>

<p>I wrote following:</p>

<p><strong>Doer</strong></p>

<pre><code>package user

import ""errors""

type Doer interface {
    Do(int, string) error
}

type DoerImp struct {

}

func (d *DoerImp)Do(val int, str string) error{
    if val == 3{
        return errors.New(""Some error"")
    }
    return nil
}
</code></pre>

<p><strong>User</strong></p>

<pre><code>package user

type User struct {
    doer Doer
}

func (u *User) UseDoer() {
    u.doer.Do(1, ""abc"")
}
</code></pre>

<p>And from the main I want to run this code:</p>

<pre><code>c := &amp;user.DoerImp{}
u := user.User{c}
u.UseDoer()
</code></pre>

<p>However I get an error: <code>Cannot assign value to unexported field 'doer'</code></p>

<p>What I'm doing wrong?<br>
my <code>c</code> value has <code>Doer</code> interface signature</p>
",https://stackoverflow.com/questions/60109478/go-interface-cannot-assign-value-to-unexported-field,['go'],5723,True,2,1
Jest unit test - SyntaxError: Cannot use import statement outside a module,"<p>I'm trying to set up unit testing in Vue using Jest. However, I'm getting this error:</p>
<pre><code>● Test suite failed to run
...
SyntaxError: Cannot use import statement outside a module

 &gt;1 | import editUser from '@/components/forms/editUser.vue';
    | ^
  2 | import TestComponent from '@/pages/user/UserMyProfile.vue';
  3 | import { shallowMount } from '@vue/test-utils';
  4 | import { expect } from 'chai';
  5 | import 'jest';
</code></pre>
<p>My Jest configuration in <code>package.json</code>looks like this:</p>
<pre><code>&quot;jest&quot;: {
    &quot;moduleFileExtensions&quot;: [
        &quot;js&quot;,
        &quot;ts&quot;,
        &quot;json&quot;,
        &quot;vue&quot;
    ],
    &quot;transform&quot;: {
        &quot;.*\\.(vue)$&quot;: &quot;vue-jest&quot;,
        &quot;^.+\\.tsx?$&quot;: &quot;ts-jest&quot;
    },
    &quot;testURL&quot;: &quot;http://localhost/&quot;,
    &quot;moduleNameMapper&quot;: {
        &quot;^@/(.*)$&quot;: &quot;&lt;rootDir&gt;/src/$1&quot;
    },
    &quot;modulePaths&quot;: [
        &quot;&lt;rootDir&quot;
    ],
    &quot;moduleDirectories&quot;: [
        &quot;node_modules&quot;,
        &quot;src&quot;
    ],
    &quot;preset&quot;: &quot;@vue/cli-plugin-unit-jest/presets/no-babel&quot;
},
</code></pre>
<p>I have tried countless examples from other questions, but I can't seem to solve the issue.</p>
<p>Edit: For the record, I'm using TypeScript</p>
",https://stackoverflow.com/questions/63389757/jest-unit-test-syntaxerror-cannot-use-import-statement-outside-a-module,"['javascript', 'unit-testing', 'vue.js', 'jestjs']",7486,True,5,1
Jasmin Angular : Checkbox select unselect not working as expected,"<pre><code>    it('Reset filter works properly', () =&gt; {
     fixture.detectChanges();
     fixture.whenStable().then(() =&gt; {
        const hostElement = fixture.nativeElement;
        const checkBox: HTMLInputElement = hostElement.querySelector('#filter ion-item:first-child ion-checkbox');
        console.log('checkBox', checkBox);
        expect(checkBox.checked).toBe(false);
        checkBox.click();
        fixture.detectChanges();
        expect(checkBox.checked).toBe(true);
</code></pre>

<p>trying unit testing the basic checkbox functionality in angular 9, Jasim framework</p>

<p>Here initially checkbox will be unchecked, then selecting it with a click, But not working as expected. </p>

<blockquote>
  <p>console.log prints checkbox element  </p>
</blockquote>

<pre><code>&lt;ion-checkbox _ngcontent-a-c154="""" color=""selection"" mode=""md"" slot=""start"" class=""ion-margin-start""&gt;&lt;/ion-checkbox&gt;
</code></pre>

<p>Error message
     <strong>Error: Expected undefined to be false.</strong></p>
",https://stackoverflow.com/questions/60987887/jasmin-angular-checkbox-select-unselect-not-working-as-expected,"['angular', 'jasmine', 'karma-jasmine', 'ionic4']",493,True,0,1
Unit testing a void method that returns a value using pytest,"<p>For example, how could I go about unit testing the following method?</p>

<pre><code>def list_append():
    data = []
    for file in files_list:
        with open(file) as f:
            data.append(json.load(f))
    return data
</code></pre>

<p>From my knowledge, there's no way to individually test the values of a local variable in a method, but please correct me if I'm wrong. Thanks in advance</p>
",https://stackoverflow.com/questions/60554768/unit-testing-a-void-method-that-returns-a-value-using-pytest,"['python', 'json', 'unit-testing', 'testing', 'pytest']",375,False,0,0
Unit test for functions drilled down,"<p>I had a file with the following handler passing it down to the child component</p>
<pre><code>const [state, dispatch] = useReducer(returnsReducer, initialState);
const selectItemHandler = (salesOrderLineId: number) =&gt; {
  dispatch({ type: SET_SELECTED_ITEMS, salesOrderLineId });
};


const selectQuantityHandler = (
  selectedQuantity: number,
  salesOrderLineId: number
) =&gt; {
  const item = { salesOrderLineId, selectedQuantity };
  dispatch({ type: SET_SELECTED_QUANTITY, item });
};
</code></pre>
<p>Passing it down like this:</p>
<pre><code>const renderEligibleItems = () =&gt; {
    return eligibleItems.map((item, i) =&gt; {
      return (
        &lt;ProductTileWrapper
          key={i}
          {...item}
          onItemSelect={selectItemHandler}
          onQuantityChange={selectQuantityHandler}
          selectedItems={selectedItems}
        /&gt;
      );
    });
  };
</code></pre>
<p>Not able to write unit testing for this(using react-testing library with jest), any suggestions on how I should approach?</p>
",https://stackoverflow.com/questions/63279116/unit-test-for-functions-drilled-down,"['javascript', 'jestjs', 'react-testing-library']",27,False,0,1
Error in failure indication with unit test plugin(C/C++ Unit) used in eclipse,"<p>Error in Red bar display and failure indication in test cases, when used C/C++Unit(Cpputest plugin) with eclipse platform for unit testing.
I have downloaded the CppuTest package from the link;&quot;https://github.com/cpputest/cpputest &quot; and i have set it up in eclipse 4.16 for unit testing in eclipse platform using cygwin.</p>
<p>As i started integrating the unit test for our project, i noticed that only the test cases which were passing were listed under the test runs and neither is the red bar displayed indicating that some test cases have failed.</p>
<p>There are 18 test cases, but only 15 have been listed under the test run. Evidently neither are the failures indicated nor is the red bar displayed.</p>
<p><a href=""https://i.stack.imgur.com/OHYip.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/OHYip.png"" alt="""" /></a></p>
",https://stackoverflow.com/questions/64063849/error-in-failure-indication-with-unit-test-pluginc-c-unit-used-in-eclipse,"['eclipse', 'unit-testing', 'cpputest']",121,False,1,0
How to mockup unit test redis helper is any if else statements,"<p><strong>I have code like this</strong> </p>

<pre><code>const client = redis.createClient({
      retry_strategy: function (options) {
        if (options.error) {
          if (options.error.code === 'ECONNREFUSED') {
            // End reconnecting on a specific error
            // and flush all commands with a individual errors
            logger.log('redis', 'The server refused the connection', 'error');
            return new Error('The server refused the connection');
          }
          if (options.error.code === 'ECONNRESET') {
            logger.log('redis', 'The server reset the connection', 'error');
            return new Error('The server reset the connection');
          }
          if (options.error.code === 'ETIMEDOUT') {
            logger.log('redis', 'The server timeouted the connection', 'error');
            return new Error('The server timeouted the connection');
          }
        }
        if (options.total_retry_time &gt; 1000 * 60 * 60) {
          // End reconnecting after a specific timeout and flush all commands
          // with a individual error
          logger.log('redis', 'Retry time exhausted', 'error');
          return new Error('Retry time exhausted');
        }
        if (options.attempt &gt; 10) {
          // End reconnecting with built in error
          logger.log('redis', 'Retry attempt exceed', 'error');
          return undefined;
        }
        // reconnect after
        return Math.min(options.attempt * 100, 3000);
      },
      ...config,
    });
</code></pre>

<p>I have made unit testing but apparently not much handling everything, how to handle the statement if else as in the code above</p>

<p>my unit test be like this</p>

<pre><code>sinon.stub(redis, 'createClient').resolves({err: true});
const res = await connection.createConnectionPool(config);
redis.createClient.restore();
</code></pre>

<p>how to create unit test for this ?</p>
",https://stackoverflow.com/questions/61096134/how-to-mockup-unit-test-redis-helper-is-any-if-else-statements,"['javascript', 'node.js', 'unit-testing', 'sinon', 'node-redis']",326,False,0,1
TypeError: seamless immutable _1.default is not a function - React native jest unit testing (Typescript),"<p>I am trying jest unit testing for typescript based react native project.Now I am stuck on one issue when do npm test. Error mentioned below</p>
<p>● Test suite failed to run</p>
<pre><code>TypeError: seamless_immutable_1.default is not a function

  34 | 
  35 | 
&gt; 36 | export const INITIAL_STATE: ImmutableAppReducerState = Immutable({
     |                                                                 ^
  37 |   activeTab: 0,
  38 |   showTab: false,
  39 |   tabName: &quot;&quot;,
</code></pre>
<p>My actual code was follows</p>
<p>import Immutable from &quot;seamless-immutable&quot;;</p>
<pre><code>export interface AppReducerState {
  activeTab?: number | undefined;
  showTab?: boolean | undefined;
  tabName?: string | undefined;
  isDrawerOpen: boolean;
  retryAction: AnyAction[];

}

/* ------------- Initial State ------------- */

type ImmutableAppReducerState = Immutable.Immutable&lt;AppReducerState&gt;


export const INITIAL_STATE: ImmutableAppReducerState = Immutable({
  activeTab: 0,
  showTab: false,
  tabName: &quot;&quot;,
  isDrawerOpen: false,
  retryAction: [],

});
</code></pre>
",https://stackoverflow.com/questions/64216428/typeerror-seamless-immutable-1-default-is-not-a-function-react-native-jest-u,"['typescript', 'react-native', 'unit-testing', 'jestjs', 'ts-jest']",911,True,0,1
Unable to read JSON file in Swift inside Unit Test Project,"<p>I am not sure why but I am not able to read a json file in my Swift Unit Testing Project. What am I missing. the url is empty object and it is just jumping to the completion(nil) line 20. </p>

<p><a href=""https://i.stack.imgur.com/2GDj8.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2GDj8.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/61113086/unable-to-read-json-file-in-swift-inside-unit-test-project,"['ios', 'swift']",927,True,0,1
test an http call inside a promise with jasmine,"<p>I am learning angular and unit testing and can't seem to get past this issue. Perhaps I am doing it all wrong but i want to test that an http call was made.</p>

<p>app.service.ts:</p>

<pre><code>transformData(data):Promise&lt;any&gt;{
    return new Promise((resolve, reject) =&gt; {
          this.http.post&lt;any&gt;('https://www.example.com',data).subscribe(
        resp =&gt; {
         resolve(resp);
         },
        err =&gt; {
         reject(err);
         }
      );

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

<p>my test is now:</p>

<pre><code>fit(""should submit data for processing"", fakeAsync(() =&gt; {

    const service = TestBed.get(AppService);

    let response = {
      processedData: 100
    };

    service
    .transformData({'data':'data'})
    .then(result =&gt; {
      expect(result).toEqual(response);
    });

   // Expect a call to this URL
  const req = httpTestingController.expectOne(
  ""https://www.example.com/""
    );
  expect(req.request.method).toEqual(""POST"");
  req.flush(response);
  tick();

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

<p>It says:</p>

<pre><code>Error: Expected one matching request for criteria ""Match URL: https://www.example.com/"", found none.
</code></pre>
",https://stackoverflow.com/questions/60456324/test-an-http-call-inside-a-promise-with-jasmine,"['angular', 'jasmine']",618,False,0,1
Configuring DbContext for InMemoryDatabase that also depends on IOptions,"<p>I want to create InMemoryDatabase for unit testing.</p>
<p>My DbContext is deriving from <code>ApiAuthorizationDbContext&lt;ApplicationUser&gt;</code> and I cannot instantiate my DbContext in test code because <code>operationalStoreOptions</code> is missing from constructor.</p>
<p>What should I do to create <code>operationalStoreOptions</code> for my context?</p>
<p><strong>DbContext</strong></p>
<pre><code>public class ApplicationDbContext : ApiAuthorizationDbContext&lt;ApplicationUser&gt;
{
   
    public ApplicationDbContext(
                DbContextOptions options,
                IOptions&lt;OperationalStoreOptions&gt; operationalStoreOptions) : base(options, operationalStoreOptions) { }

    public virtual DbSet&lt;Assignment&gt; Assignment { get; set; }
    public virtual DbSet&lt;Course&gt; Course { get; set; } 
                           ...........
    // More DbSet and OnModelCreating method
 }
</code></pre>
<p><strong>My test code</strong></p>
<pre><code> var options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()
           .UseInMemoryDatabase(databaseName: &quot;TestDbContext&quot;)
           .Options;
    

 //ApplicationDbContext needs 2 constructor parameter
 using (var _context = new ApplicationDbContext(options))
 {
   _context.Assignment.Add(new Assignment(1, &quot;Test&quot;));
   _context.SaveChanges();
 }
</code></pre>
",https://stackoverflow.com/questions/65003938/configuring-dbcontext-for-inmemorydatabase-that-also-depends-on-ioptions,"['c#', 'asp.net-core', 'entity-framework-core', 'asp.net-core-webapi', 'xunit.net']",399,True,0,1
How to unit test for the given code in Angular 8,"<p>I am trying to execute unit testing for the below code</p>
<pre><code>  applyFilter(filterValue: string) {
   this.dataSource.filter = filterValue.trim().toLowerCase();
   this.DMDataSource.filter = filterValue.trim().toLowerCase();
   // console.log(this.dataSource.filter);
 }
</code></pre>
<p>Here is my Spec code for that</p>
<pre><code>  it('apply filter', () =&gt; {
    spyOn(component, 'applyFilter');
    component.applyFilter('filterValue');
    expect(component.applyFilter);
  })
</code></pre>
<p>Still in the browser showing that code is highlighted in red, meaning it was not covered. What am I doing wrong here?</p>
",https://stackoverflow.com/questions/63916283/how-to-unit-test-for-the-given-code-in-angular-8,"['angular', 'unit-testing', 'karma-jasmine']",770,True,0,1
Instantiated a struct which is a part of iOS framework and has internal access control,"<p>I would like to instantiate a struct which is a part of third party iOS framework and cannot be instantiated from outside means has internal init. But I need to create for Unit testing. Any idea how to achieve this?</p>
",https://stackoverflow.com/questions/64967196/instantiated-a-struct-which-is-a-part-of-ios-framework-and-has-internal-access-c,"['ios', 'swift', 'unit-testing']",59,True,0,1
Python/Pandas: Unit testing with hypothesis - reproducing falsifying example,"<p>Using the <code>hypothesis</code> library for unit testing, I am wondering how I can reproduce a falsifying example <code>pd.DataFrame</code>?</p>
<p>The output looks like this:</p>
<pre><code>Falsifying example: test_data_frame_data(
    data=                            sec_1  sec_2  sec_3
    2020-01-01 00:00:00.000001    0.0   -0.0    0.0
    2020-01-01 00:00:00.000000    0.0   -0.0    0.0
    2020-01-01 00:00:00.000257    0.0   -0.0    0.0
    2020-01-01 00:00:00.000258    0.0   -0.0    0.0
    2020-01-01 00:00:00.000261    0.0   -0.0    0.0
    ...                           ...    ...    ...
    2020-01-01 00:00:01.526858    0.0   -0.0    0.0
    2020-01-01 01:00:01.065796    0.0   -0.0    0.0
    2020-01-01 01:00:01.065797    0.0   -0.0    0.0
    2020-01-01 01:01:01.065795    0.0   -0.0    0.0
    2020-01-01 00:01:01.000020    0.0   -0.0    0.0

    [300 rows x 3 columns],
)
</code></pre>
<p><code>Hypothesis</code> didn't print a <code>seed</code> or a hint to <code>@reproduce_failure</code>.</p>
<p>I simply would like to use the falsifying example to debug my code.</p>
",https://stackoverflow.com/questions/63685033/python-pandas-unit-testing-with-hypothesis-reproducing-falsifying-example,"['python', 'pandas', 'debugging', 'python-hypothesis']",235,True,0,1
How to test AgRendererComponent component in Angular Ag Grid,"<p>I have a custom cell renderer component which wil convert the text to link. Its all working fine. I am trying to unit test the renderer component. The issue am facing in unit testing is Grid is displaying with link but its not available when I query through native element, I am getting the value as empty other grid values are already present I am able to see it. I think this is to do with the lifecycle of testing or AG Grid rendering. How do I tell the test framework to wait untill the  component is rendered?</p>
<p>link renderer component</p>
<pre><code>@Component({
    template: '&lt;a [routerLink]=&quot;[params.inRouterLink,params.value]&quot;  (click)=&quot;navigate(params.inRouterLink)&quot;&gt;{{params.value}}&lt;/a&gt;'
})
export class RouterLinkRendererComponent implements AgRendererComponent {
    params: any;

    constructor(
        private ngZone: NgZone,
        private router: Router) { }

    agInit(params: any): void {
        this.params = params;
    }

    refresh(params: any): boolean {
        return false;
    }
}
</code></pre>
<p>Test Component:</p>
<pre><code>@Component({
  template: `
    &lt;ag-grid-angular
      style=&quot;width: 500px; height: 500px;&quot;
      class=&quot;custom-theme&quot;
      [rowData]=&quot;rowData&quot;
      [columnDefs]=&quot;columnDefs&quot;
      (gridReady)=&quot;onGridReady($event)&quot;
    &gt;
    &lt;/ag-grid-angular&gt;
  `
})
export class TestCustomComponent {
  columnDefs = [
    {
      headerName: 'Make',
      field: 'make',
      cellRendererFramework: RouterLinkRendererComponent,
      cellRendererParams: {
        inRouterLink: '/#'
      }
    },
    { headerName: 'Model', field: 'model' },
    { headerName: 'Price', field: 'price' }
  ];

  rowData = [
    { make: 'Toyota', model: 'Celica', price: 35000 },
    { make: 'Ford', model: 'Mondeo', price: 32000 },
    { make: 'Porsche', model: 'Boxter', price: 72000 }
  ];
}
</code></pre>
<p>Unit Testing</p>
<pre><code>fdescribe('AgnavigatorComponent', () =&gt; {
  let component: TestCustomComponent;
  let fixture: ComponentFixture&lt;TestCustomComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [RouterLinkRendererComponent, TestCustomComponent],
      imports: [
        RouterTestingModule,
        AgGridModule.withComponents([RouterLinkRendererComponent])
      ]
    }).compileComponents();
  }));

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

  it('should create', () =&gt; {
    const appElement = fixture.nativeElement;
    // here the values are empty only for the first column which uses custom renderer.
    const cellElements = appElement.querySelectorAll('.ag-cell-value');
  });
});
</code></pre>
<p>once the test execution completes I can see the column with proper value with href in it.</p>
",https://stackoverflow.com/questions/63231639/how-to-test-agrenderercomponent-component-in-angular-ag-grid,"['angular', 'unit-testing', 'testing', 'ag-grid-angular']",2990,True,1,1
Upgrading AutoMapper from v6 to v9 and unit testing with Resolution Context,"<p>I'm hoping that somebody can help me. We are currently upgrading AutoMapper from v6 to v9 - we would go to v10 but the inability to create new <code>ResolutionContext</code> impacts our unit testing. That said with v9 we are still having the following issue with unit testing AutoMapper Converters...</p>
<p>A ConverterClass:</p>

<pre class=""lang-cs prettyprint-override""><code>public class FooBarConverter :
    ITypeConverter&lt;FooSourceObject, BarDestinationObject&gt;
{
    /// &lt;inheritdoc/&gt;
    public virtual BarDestinationObjectConvert(FooSourceObjectsource, BarDestinationObjectdestination, ResolutionContext context)
    {
        EnsureArg.IsNotNull(source, nameof(source));

        switch (source.Type)
        {
            case SomeType.None:
                return context.Mapper.Map&lt;NoneBarDestinationObject&gt;(source);
            case SomeType.FixedAmount:
                return context.Mapper.Map&lt;FixedBarDestinationObject&gt;(source);
            case SomeType.Percentage:
                return context.Mapper.Map&lt;PercentageBarDestinationObject&gt;(source);
            default:
                throw new ArgumentOutOfRangeException(nameof(source));
        }
    }
</code></pre>
<p>Before in AutoMapper 6 we had the following Unit Test (using Xunit):</p>
<pre class=""lang-cs prettyprint-override""><code>public class FooBarConverterTests
{
    private readonly FooBarConverter target;

    private readonly Mock&lt;IRuntimeMapper&gt; mockMapper;
    private readonly ResolutionContext resolutionContext;

    public FooBarConverterTests()
    {
        this.mockMapper = new Mock&lt;IRuntimeMapper&gt;();
        this.resolutionContext = new ResolutionContext(null, this.mockMapper.Object);
        this.target = new FooBarConverter();
    }

    [Fact]
    public void FixedAmountFooModel_ConvertsTo_FixedBarDomainModel()
    {
        // Arrange
        var input = new Foo
        {
            Type = SomeType.FixedAmount
        };

        var expected = new DomainModels.FixedBarDestinationObject();

        this.mockMapper.Setup(x =&gt; x.Map&lt;FixedBarDestinationObject&gt;(It.IsAny&lt;FooSourceObjectsource&gt;()))
            .Returns(expected);

        // Act
        var actual = this.target.Convert(input, It.IsAny&lt;BarDestinationObjectdestination&gt;(), this.resolutionContext);

        // Assert
        actual.ShouldSatisfyAllConditions(
            () =&gt; actual.ShouldNotBeNull(),
            () =&gt; actual.ShouldBeAssignableTo&lt;DomainModels.FixedBarDestinationObject&gt;());

        this.mockMapper.Verify(x =&gt; x.Map&lt;DomainModels.FixedBarDestinationObject&gt;(input));
    }
}
</code></pre>
<p>Essentially, this was working fine, however since upgrading to v9, the mapping setup goes missing as it's passed through the resolution context. Meaning that the resulting call of <code>Mapper.Map&lt;FixedBarDestinationObject&gt;()</code> always returns <code>null</code>.</p>
<p>I understand that the <code>ResolutionContext</code> may have changed slightly, but I don't understand how to resolve this issue and ensure that the mock mapping is passed through to the underlying converter.</p>
<p>Thank you for any help or advice.</p>
",https://stackoverflow.com/questions/63471556/upgrading-automapper-from-v6-to-v9-and-unit-testing-with-resolution-context,['automapper-9'],1833,True,4,1
React and laravel mix : Cannot find module &#39;@babel/preset-react &#39;,"<p>I am learning unit testing using jest testing library in react js with laravel, here is what I have so far.</p>
<p>.babelrc file</p>
<pre><code>{
    &quot;plugins&quot;: [
      [
          &quot;module-resolver&quot;,
          {
              &quot;root&quot;: [
                  &quot;./resources/js&quot;
              ],
              &quot;alias&quot;: {
                  &quot;test&quot;: &quot;./test&quot;
              }
          }
      ]
  ],
&quot;env&quot;: {
  &quot;test&quot;: {
    &quot;presets&quot;: [
      [&quot;@babel/preset-env&quot;, {
        &quot;targets&quot;: {
          &quot;node&quot;: &quot;current&quot;
        }
      }],
      [&quot;@babel/preset-react &quot;, {
        &quot;targets&quot;: {
          &quot;node&quot;: &quot;current&quot;
        }
      }]
    ]
  },
  &quot;development&quot;: {
    &quot;presets&quot;: [
      [&quot;env&quot;, {
        &quot;modules&quot;: false,
        &quot;targets&quot;: {
          &quot;browsers&quot;: &quot;&gt; 2%&quot;,
          &quot;uglify&quot;: true
        }
      }]
    ]
  },
  &quot;production&quot;: {
    &quot;presets&quot;: [
      [&quot;env&quot;, {
        &quot;modules&quot;: false,
        &quot;targets&quot;: {
          &quot;browsers&quot;: &quot;&gt; 2%&quot;,
          &quot;uglify&quot;: true
        }
      }]
    ]
  }
}
}
</code></pre>
<p>package.json</p>
<pre><code>{
  ............
  &quot;devDependencies&quot;: {
    &quot;@babel/plugin-proposal-class-properties&quot;: &quot;^7.5.0&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.12.1&quot;,
    &quot;@babel/preset-react&quot;: &quot;^7.12.1&quot;,
    &quot;babel-jest&quot;: &quot;^26.6.0&quot;,
    &quot;babel-plugin-module-resolver&quot;: &quot;^3.2.0&quot;,
    &quot;cross-env&quot;: &quot;^5.2.1&quot;,
    &quot;enzyme&quot;: &quot;^3.11.0&quot;,
    &quot;enzyme-adapter-react-16&quot;: &quot;^1.15.5&quot;,
    &quot;jest&quot;: &quot;^26.6.0&quot;,
    &quot;laravel-mix&quot;: &quot;^5.0.5&quot;,
    &quot;react-test-renderer&quot;: &quot;^17.0.0&quot;,
    &quot;resolve-url-loader&quot;: &quot;^2.3.1&quot;,
    &quot;sass&quot;: &quot;^1.26.3&quot;,
    &quot;sass-loader&quot;: &quot;^7.1.0&quot;
  }
}
</code></pre>
<p>Now when I run <code>npm test </code> I get the following error.</p>
<p><a href=""https://i.stack.imgur.com/mJY26.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/mJY26.png"" alt=""enter image description here"" /></a></p>
<p>What do I need to do to solve this error?</p>
",https://stackoverflow.com/questions/64501400/react-and-laravel-mix-cannot-find-module-babel-preset-react,"['javascript', 'reactjs', 'laravel', 'jestjs', 'laravel-mix']",713,False,1,0
Function doesn&#39;t return more than two values,"<p>I'm working with unit testing using testthat in R. I have to test a function say calculateProfit. My function to test looks like this,</p>
<pre><code>calculateProfit = function(subTotal, colName) {
  data  = getMappingList(subTotal, &quot;dclass&quot;, colName)

  costRate = 0
  if (colName == &quot;amount&quot;) {
    data_pt  = getMappingList(subTotal, &quot;dclass&quot;, profit)
    costRate = -1 * (data_pt[COST] + data[COST]) / (data_pt[S] + data[S]) - -1 * data_pt[COST] / data_pt[S]
  } 
</code></pre>
<p>The function getMappingList is as follows:</p>
<pre><code>getMappingList = function(data, nameCol, valueCol) {
  nameList  = pull(data, nameCol)
  valueList = pull(data, valueCol)
  names(valueList) = nameList
  valueList
}
</code></pre>
<p>Now, while doing unit testing we have to mock the function getMappingList using local_mock from testthat. If the function getMappingList is called once then it is easy to test it. But since this function is called again I have used it like the below manner.</p>
<pre><code>local_mock(getMappingList = function(data, nameCol, valueCol){
              data = read.csv(filePath = file.path(TARGET_PATH, &quot;getMappingList&quot;, &quot;Case1&quot;, &quot;data.csv&quot;))
              data = unlist(data)
              
              data_pt = read.csv(filePath = file.path(TARGET_PATH, &quot;getMappingList&quot;, &quot;Case1&quot;, &quot;data_pt.csv&quot;))
              data_pt = unlist(data_pt)
              
              return(data)
              return(data_pt)
              })
</code></pre>
<p>when I execute the actual script like below,</p>
<pre><code>Actual_Output = calculateProfit(subTotal, &quot;amount&quot;)
</code></pre>
<p>The if loop isn't executed. I'm getting the output for costRate as 0. But the output should be a whole number.</p>
<p>This is the input</p>
<pre><code>&gt; dput(subtotal)
structure(list(dclass = c(&quot;cost&quot;, &quot;s&quot;), amount = c(200, 300), 
    profit = c(301, 401)), class = &quot;data.frame&quot;, row.names = c(NA, 
-2L))
</code></pre>
<p>If anyone could help me to sort this out, it would be a great help.</p>
",https://stackoverflow.com/questions/65254397/function-doesnt-return-more-than-two-values,"['r', 'function', 'unit-testing', 'mocking', 'testthat']",31,False,0,0
How to write unit test for private static method in static class with nunit in c#,"<p>I'm using nunit for unit testing and i want to test a private method in a static class.
This is my class:</p>

<pre><code>public static class ServiceModuleExtentions
{
    public static void RegisterCoreServices(this IServiceCollection serviceCollection)
    {
        serviceCollection.AddScoped&lt;ICourseService, CourseService&gt;();
        var automapper = RegisterAutoMapperService();
        serviceCollection.AddSingleton(automapper);
    }

    private static IMapper RegisterAutoMapperService()
    {
        // Auto Mapper Configurations
        var mappingConfig = new MapperConfiguration(mc =&gt;
        {
            mc.AddProfile(new MapperProfile());
        });

        IMapper mapper = mappingConfig.CreateMapper();

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

<p>Now my question is how can i write unit test for RegisterAutoMapperService method?</p>

<p>And also this is my MapperProfile class:</p>

<pre><code>public class MapperProfile : Profile
{
    public MapperProfile()
    {
        CreateMap&lt;Course, CourseVM&gt;().ReverseMap();
    }
}
</code></pre>
",https://stackoverflow.com/questions/61350417/how-to-write-unit-test-for-private-static-method-in-static-class-with-nunit-in-c,"['c#', 'unit-testing', 'nunit', 'static-methods', 'static-classes']",315,False,1,0
What C++ design pattern is available for swapping behavior of a function template between production code and testing code?,"<p>I am refactoring a component to make it more unit testable. A first step is to enable unit testing for some core component code. Unfortunately, this core component code calls some in-component utility functions that directly interact with other components' concrete classes, which are hard to instantiate without the production environment. For the normal utility functions, I can leverage dependency injection to wrap them as virtual functions inside a utility interface and swap in overrides during unit testing. However, there are also utility function templates, which I couldn't apply the same technique, because we can't have virtual function template. Is there a known pattern to handle this?</p>
<p>To give a concrete example, consider the code that follows. Is there a way to switch behavior of the <code>utilIsNameValid</code> function template during unit testing? Some constraints apply:</p>
<ol>
<li>I need to directly isolate the logic in <code>utilIsNameValid</code> from testing its using code. This prevents me from just switching the behavior of <code>utilGetName</code>s with dependency injection, and hope that it would indirectly steer <code>utilIsNameValid</code> the way I want it.</li>
<li>I cannot change <code>MyClass</code>s interface because it is a legacy API with wide impact. @Jarod42's answer is near perfect but requires <code>MyClass</code> to become a template, which could lead to callsite adaptation changes.</li>
</ol>
<p><code>mycomponent/util/MyUtil.hpp (in-component utility code)</code></p>
<pre><code>#include &lt;string&gt;
class TheirClassA;
class TheirClassB;

std::string utilGetName(TheirClassA* a); // a normal utility function

std::string utilGetName(TheirClassB* b); // a normal utility function

template&lt;class T&gt;
bool utilIsNameValid(T obj) {            // a utility function template
    auto name = utilGetName(obj);
    // ... perform the generic name checking ...
}
</code></pre>
<p><code>mycomponent/util/MyUtil.cpp (in-component utility code)</code></p>
<pre><code>#include &quot;MyUtil.hpp&quot;
#include &quot;theircomponent/TheirClassA.hpp&quot;
#include &quot;theircomponent/TheirClassB.hpp&quot;

std::string utilGetName(TheirClassA* a) {
    return std::string{a-&gt;getNameInAsWayThatReturnsCharPtr()};
}
std::string utilGetName(TheirClassB* b) {
    return b-&gt;getNameInBsWayThatReturnsString();
}
</code></pre>
<p><code>mycomponent/core/MyClass.hpp (core component code)</code></p>
<pre><code>class TheirClassA;
class TheirClassB;
class MyClass {
    public:
    bool canProcess(TheirClassA* a) const;
    bool canProcess(TheirClassB* b) const;
};
</code></pre>
<p><code>mycomponent/core/MyClass.cpp (core component code)</code></p>
<pre><code>#include &quot;MyClass.hpp&quot;
#include &quot;mycomponent/util/MyUtil.hpp&quot;
bool MyClass::canProcess(TheirClassA* a) const {
    return utilIsNameValid(a) &amp;&amp; /* some other conditions for TheirClassA objects*/;
}
bool MyClass::canProcess(TheirClassB* b) const {
    return utilIsNameValid(b) &amp;&amp; /* some other conditions for TheirClassB objects*/;
}
</code></pre>
<p><code>production/main.cpp</code></p>
<pre><code>#include &quot;mycomponent/core/MyClass.hpp&quot;
#include &quot;theircomponent/TheirClassA.hpp&quot;
#include &quot;theircomponent/TheirClassB.hpp&quot;
int main (){
    // ... tedious steps to set up TheirClassA and TheirClassB objects ...
    MyClass processor;
    if (processor.canProcess(a)) {
        // ... process a ....
    }
    if (processor.canProcess(b)) {
        // ... process b ....
    }
}
</code></pre>
<p><code>mycomponent/unittest/Test.cpp</code></p>
<pre><code>#include &quot;mycomponent/core/MyClass.hpp&quot;
#include &quot;theircomponent/TheirClassA.hpp&quot;
#include &quot;theircomponent/TheirClassB.hpp&quot;
int main (){
    // ... cannot afford instantiating actual objects ...
    TheirClassA* a = nullptr;
    TheirClassB* b = nullptr;

    // ... need someway for utilIsNameValid to simply return 
    //     true or false to test out the rest of the code in
    //     MyClass::canProcess(...) ...
    MyClass processor;
    if (processor.canProcess(a)) {
        // ... process a ....
    }
    if (processor.canProcess(b)) {
        // ... process b ....
    }
}
</code></pre>
",https://stackoverflow.com/questions/64466214/what-c-design-pattern-is-available-for-swapping-behavior-of-a-function-templat,"['c++', 'unit-testing', 'function-templates']",91,True,1,1
Test result - className not updated,"<p>I'm unit testing in React (Jest, Enzyme). I expect #mail to have class 'solutions__mail-input', when input is changed, but it doesn't. Code:</p>
<pre><code>inputEmail.simulate(&quot;change&quot;, {
      target: { value: &quot;test@test.com&quot;, name: &quot;mail&quot; },
    }); 
</code></pre>
<p>then:</p>
<pre><code>expect(solutions.find(&quot;#mail&quot;).hasClass(&quot;solutions__mail-input&quot;)).toEqual(
      true
    );
</code></pre>
<p>And it is not greened, value of input is changed, logic of changing class is also good.</p>
<p>Test:</p>
<pre><code>

  it(&quot;test valid mail&quot;, () =&gt; {
    const solutions = shallow(&lt;Solutions /&gt;);
    const inputEmail = solutions.find(&quot;#mail&quot;);
    inputEmail.simulate(&quot;change&quot;, {
      target: { value: &quot;test@test.com&quot;, name: &quot;mail&quot; },
    });
    expect(solutions.find(&quot;#mail&quot;).props().value).toBe(&quot;test@test.com&quot;);
    expect(solutions.find(&quot;#mail&quot;).hasClass(&quot;solutions__mail-input&quot;)).toEqual(
      true
    );
  });

</code></pre>
<p>Component:</p>
<pre><code>      &lt;input
        type=&quot;text&quot;
        placeholder=&quot;Email&quot;
        value={mail}
        id=&quot;mail&quot;
        name=&quot;mail&quot;
        className={`solutions__mail-input${!readyToSend ? &quot;--invalid&quot; : &quot;&quot;}`}
        onChange={(e) =&gt; {
          changeMail(e.target.value);
          validateMail();
        }}
      /&gt;
    
</code></pre>
",https://stackoverflow.com/questions/65369268/test-result-classname-not-updated,"['reactjs', 'unit-testing', 'enzyme']",361,True,1,2
Unable to compile Typescript using mocha and visual Studio Code Debugger,"<p>I'm trying to debug unit testing with Visual Studio Code and mocha, but when mocha launchs, throws this error.</p>
<blockquote>
<p>TSError: ⨯ Unable to compile TypeScript: mfa/test/index.test.ts(4,20):
error TS2307: Cannot find module 'assert' or its corresponding type
declarations.</p>
</blockquote>
<p>My launch.json:</p>
<pre><code>{
  &quot;version&quot;: &quot;0.2.0&quot;,
  &quot;configurations&quot;: [
    {
      &quot;name&quot;: &quot;mocha tests&quot;,
      &quot;type&quot;: &quot;node&quot;,
      &quot;protocol&quot;: &quot;inspector&quot;,
      &quot;request&quot;: &quot;launch&quot;,
      &quot;program&quot;: &quot;${workspaceRoot}/node_modules/mocha/bin/_mocha&quot;,
      &quot;stopOnEntry&quot;: false,
      &quot;args&quot;: [ &quot;-r&quot;, &quot;ts-node/register&quot;, &quot;${workspaceRoot}/test/**/*.test.ts&quot;, &quot;--no-timeouts&quot;],
      &quot;sourceMaps&quot;: true,
      &quot;cwd&quot;: &quot;${workspaceRoot}&quot;
      }
  ]
}
</code></pre>
<p>My tsconfig.json</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;experimentalDecorators&quot;: true,
    &quot;target&quot;: &quot;ES2017&quot;, 
    &quot;module&quot;: &quot;commonJs&quot;,
    &quot;allowJs&quot;: false, 
    &quot;sourceMap&quot;: true, 

    /* Strict Type-Checking Options */
    &quot;strict&quot;: true,
    &quot;noImplicitAny&quot;: false,

    &quot;esModuleInterop&quot;: true, 



  
    /* Advanced Options */
    &quot;skipLibCheck&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true, 
   
  }
}
</code></pre>
",https://stackoverflow.com/questions/63715484/unable-to-compile-typescript-using-mocha-and-visual-studio-code-debugger,"['typescript', 'visual-studio-code', 'mocha.js']",1064,True,1,2
Testing NuxtJS Components that use Vuetify,"<p>I want to unit test components with jest in a NuxtJS Project that are using Vuetify. When I want to select a button (v-btn), jest outputs the following:</p>

<pre><code> [vue-test-utils]: find did not return .v-btn, cannot call text() on empty Wrapper
</code></pre>

<p>I followed the official docs of vuetify for unit testing.</p>

<pre><code>// myComponent.vue

&lt;template&gt;
  &lt;v-menu offset-y&gt;
    &lt;v-btn color=""primary""&gt;
      myLabel
    &lt;/v-btn&gt;
  &lt;/v-menu&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
}
&lt;/script&gt;

</code></pre>

<pre><code>// myComponent.spec.js
import { createLocalVue, mount } from '@vue/test-utils'
import Vuetify from 'vuetify'
import MyComponent from '~/components/MyComponent'

describe('Index Switch', () =&gt; {
  const localVue = createLocalVue()
  let wrapper
  let vuetify

  beforeEach(() =&gt; {
    vuetify = new Vuetify()
    wrapper = mount(MyComponent, { localVue, vuetify })
  })

  it('should have index switch button', () =&gt; {
    const myButton = wrapper.find('.v-btn')
    expect(myButton.text()).toBe('myLabel')
  })
})

</code></pre>

<p>Any ideas what is wrong here?</p>
",https://stackoverflow.com/questions/59965078/testing-nuxtjs-components-that-use-vuetify,"['vue.js', 'jestjs', 'vuetify.js', 'nuxt.js']",359,False,2,1
How to write test case for undefined window Object | Vue test utils | Jest Framework,"<p>I am using vue test utils - Jest framework for unit testing of my vue file. I'm not able to test the below line. </p>

<pre><code>const inBrowser = typeof window !== 'undefined';
</code></pre>

<p>My question is how to set <strong>JavaScript Window</strong>  as undefined. Is there any way to set window as undefined Browser Object Model (BOM)?</p>
",https://stackoverflow.com/questions/60321739/how-to-write-test-case-for-undefined-window-object-vue-test-utils-jest-frame,"['javascript', 'unit-testing', 'vue.js', 'jestjs', 'vue-test-utils']",1666,False,3,1
"Pytest not running as expected, module not found or collected 0 items","<p>Here is my directory structure. (I deleted <code>word_count_test.py</code> it was worth a try, the content was exactly the same as <code>test_word_count.py</code>).</p>

<p><a href=""https://i.stack.imgur.com/IY5Ar.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/IY5Ar.png"" alt=""directory structure""></a></p>

<p>The code for unit testing in <code>word_count.py</code></p>

<pre><code>from validators import url

def isValidUrl(uri):
    return url(uri)
</code></pre>

<p><code>test_word_count.py</code> contains</p>

<pre><code>import pytest
from src.word_count import isValidUrl

def isValidUrl_test():
    assertTrue(isValidUrl(""http://www.bbc.co.uk/news""))

assert 1 == 1
</code></pre>

<p>Depending on whether I run pytest from the terminal or from within the IDE I get </p>

<pre><code>__________________ ERROR collecting test/test_word_count.py ____________________________
ImportError while importing test module '/Users/path/to/the/project/word_counter_service/test/test_word_count.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test/test_word_count.py:2: in &lt;module&gt;
    from src.word_count import isValidUrl
E   ModuleNotFoundError: No module named 'src'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================= 1 error in 0.10s =============================================================================================

</code></pre>

<p>or </p>

<pre><code>word_counter_service) mc-n357353:word_counter_service leives01$ pytest
=========================================================== test session starts ===========================================================
platform darwin -- Python 3.8.0, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: /Users/path/to/the/project/word_counter_service
collected 0 items                                                                                                                         

========================================================== no tests ran in 0.10s ==========================================================

</code></pre>
",https://stackoverflow.com/questions/59600887/pytest-not-running-as-expected-module-not-found-or-collected-0-items,"['python', 'unit-testing', 'testing', 'pytest']",382,False,0,1
"Unit test on object, not class","<p>How can I run a unit test (with JUnit, TestNG, whatever does the job), on an object, not a class? (<em>object</em> meaning: a class instance)
The unit testing framework should provide the same annotation possibilities like with JUnit, TestNG, etc.. With <code>@Before</code>, <code>@Test</code>, etc..</p>

<p>Like:
</p>

<pre><code>class StartupBean {
    @EJB   // &lt;-- Initialized with Auto-Discovery by JavaEE
    TestIT object;

    void run() {
        // Exactly what I want
        // (""UnitTester"" as a placeholder for whatever behaves like JUnitCore().run(...) on objects):
        UnitTester.test(object);

        // *Not* this, using a class, instead of an object:
        new JUnitCore().run(TestIT.class);
    }
}

class TestIT {
     @Before
     public void setUp() { ... }

     @Test
     void run() { ... }
}
</code></pre>
",https://stackoverflow.com/questions/61773603/unit-test-on-object-not-class,"['java', 'junit', 'testng']",70,False,0,0
How do I configure .babelrc for react and jest testing framework?,"<p><strong>I created a react app from scratch(<a href=""https://createapp.dev/parcel"" rel=""nofollow noreferrer"">createapp.dev</a>)  and am  using  parcel bundler to bundle it.</strong> </p>

<p><strong>I tried do unit testing on it using <a href=""https://testing-library.com/"" rel=""nofollow noreferrer"">https://testing-library.com/</a> and jest but I keep getting this error.</strong></p>

<pre><code>src/components/App.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 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
</code></pre>

<p><strong>How can I fix it?
These are my files</strong> 
.babelrc</p>

<pre><code>{
    ""presets"": [
      [
        ""@babel/preset-env"",
        {
          ""modules"": false
        }
      ],
      [""@babel/preset-react""]
    ],
    ""plugins"": [""@babel/plugin-proposal-class-properties"" ]
  }
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>{

  ""main"": ""src/index.js"",

  ""scripts"": {
    ""test"": ""jest"",
    ""start"": ""parcel public/index.html --host 127.0.0.1 --port 8080"",
  },
  ""dependencies"": {
    ""react"": ""^16.12.0"",
    ""react-dom"": ""^16.12.0""
  },
  ""devDependencies"": {
    ""@babel/core"": ""^7.8.7"",
    ""@babel/plugin-proposal-class-properties"": ""^7.8.3"",
    ""@babel/preset-env"": ""^7.8.7"",
    ""@babel/preset-react"": ""^7.8.3"",
    ""@testing-library/react"": ""^10.0.1"",
    ""babel-jest"": ""^25.1.0"",
    ""jest"": ""^25.1.0"",
    ""parcel"": ""^1.12.4"",
    ""parcel-bundler"": ""^1.12.4"",
    ""prettier"": ""^1.19.1""
  }
}
</code></pre>
",https://stackoverflow.com/questions/60683064/how-do-i-configure-babelrc-for-react-and-jest-testing-framework,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library', 'parceljs']",3263,True,3,1
Getting &#39;Request processing failed&#39; while doing TestNG PUT request in gradle mockmvc,"<p>Getting below exception while running PUT request Test case using mockmvc.
The Mockmvc code for unit testing is this:</p>

<pre><code>mockMvc.perform(put(""/images/""+id)
                .contentType(MediaType.APPLICATION_JSON)
                .header(""X-Client-Type"", ""STOS"")
                .header(""Authorization"", ""Bearer "" + jwtTokenResponse.getAccessToken())
                .content(convertObjectToString(imageRequest)))
                .andExpect(status().isOk());
</code></pre>

<p>The exception is below for the same testcase:</p>

<pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:919)
00:41:31.144 [DEBUG] [TestEventLogger]         at javax.servlet.http.HttpServlet.service(HttpServlet.java:663)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
00:41:31.144 [DEBUG] [TestEventLogger]         at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
00:41:31.144 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
00:41:31.144 [DEBUG] [TestEventLogger]         at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:239)
00:41:31.144 [DEBUG] [TestEventLogger]         at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:215)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.test.web.servlet.setup.PatternMappingFilterProxy.doFilter(PatternMappingFilterProxy.java:101)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
00:41:31.145 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.146 [DEBUG] [TestEventLogger]         at com.ril.api.auth.filter.JwtTokenAuthenticationProcessingFilter.successfulAuthentication(JwtTokenAuthenticationProcessingFilter.java:122)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:240)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
00:41:31.146 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
00:41:31.147 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
00:41:31.148 [DEBUG] [TestEventLogger]         at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
00:41:31.148 [DEBUG] [TestEventLogger]         at controller.ImageControllerTests.testImagesPut(ImageControllerTests.java:336)
00:41:31.148 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
00:41:31.148 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
00:41:31.149 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
00:41:31.149 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:200)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:180)
00:41:31.149 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
00:41:31.149 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
00:41:31.149 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
00:41:31.149 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:212)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.Invoker.invokeMethod(Invoker.java:707)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
00:41:31.149 [DEBUG] [TestEventLogger]         at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.TestRunner.privateRun(TestRunner.java:767)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.TestRunner.run(TestRunner.java:617)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.SuiteRunner.run(SuiteRunner.java:254)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.testng.TestNG.run(TestNG.java:1057)
00:41:31.150 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.runTests(TestNGTestClassProcessor.java:141)
00:41:31.151 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.stop(TestNGTestClassProcessor.java:90)
00:41:31.151 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
00:41:31.151 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
00:41:31.151 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
00:41:31.151 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
00:41:31.151 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
00:41:31.151 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
00:41:31.151 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
00:41:31.151 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
00:41:31.151 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
00:41:31.151 [DEBUG] [TestEventLogger]         at com.sun.proxy.$Proxy2.stop(Unknown Source)
00:41:31.151 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
00:41:31.152 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
00:41:31.152 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
00:41:31.152 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
00:41:31.152 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
00:41:31.152 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
00:41:31.152 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
00:41:31.152 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
00:41:31.152 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
00:41:31.152 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
00:41:31.152 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
00:41:31.152 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
00:41:31.152 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
00:41:31.152 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
00:41:31.153 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
00:41:31.153 [DEBUG] [TestEventLogger]         at java.lang.Thread.run(Thread.java:748)
00:41:31.153 [DEBUG] [TestEventLogger] 
00:41:31.153 [DEBUG] [TestEventLogger]         Caused by:
00:41:31.153 [DEBUG] [TestEventLogger]         java.lang.NullPointerException
00:41:31.153 [DEBUG] [TestEventLogger]             at com.ril.service.cms.controller.ImageController.updateImageDetails(ImageController.java:136)
00:41:31.153 [DEBUG] [TestEventLogger]             at com.ril.service.cms.controller.ImageController$$FastClassBySpringCGLIB$$689e4489.invoke(&lt;generated&gt;)
00:41:31.153 [DEBUG] [TestEventLogger]             at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
00:41:31.153 [DEBUG] [TestEventLogger]             at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
00:41:31.153 [DEBUG] [TestEventLogger]             at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
00:41:31.153 [DEBUG] [TestEventLogger]             at net.bull.javamelody.MonitoringSpringInterceptor.invoke(MonitoringSpringInterceptor.java:76)
00:41:31.153 [DEBUG] [TestEventLogger]             at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
00:41:31.154 [DEBUG] [TestEventLogger]             at com.ril.service.cms.controller.ImageController$$EnhancerBySpringCGLIB$$b7ab9e1d.updateImageDetails(&lt;generated&gt;)
00:41:31.154 [DEBUG] [TestEventLogger]             at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
00:41:31.154 [DEBUG] [TestEventLogger]             at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
00:41:31.154 [DEBUG] [TestEventLogger]             at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
00:41:31.154 [DEBUG] [TestEventLogger]             at java.lang.reflect.Method.invoke(Method.java:498)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
00:41:31.154 [DEBUG] [TestEventLogger]             at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
00:41:31.155 [DEBUG] [TestEventLogger]             at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
00:41:31.155 [DEBUG] [TestEventLogger]             at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
00:41:31.155 [DEBUG] [TestEventLogger]             ... 119 more
00:41:31.156 [QUIET] [system.out] 
00:41:31.156 [QUIET] [system.out] &lt;/event&gt;&lt;/ijLog&gt;
00:41:31.156 [DEBUG] [TestEventLogger] 
00:41:31.156 [DEBUG] [TestEventLogger] Gradle suite &gt; Gradle test FAILED
</code></pre>

<p>What is needed to corrected here?</p>

<p>What is the root cause for this?</p>

<p>How to avoid this scenario?</p>
",https://stackoverflow.com/questions/60803915/getting-request-processing-failed-while-doing-testng-put-request-in-gradle-moc,"['unit-testing', 'testing', 'gradle', 'testng', 'mockmvc']",60,False,1,0
Mocked Async Method in xUnit-Test returns always null,"<p>I have a ASP.NET WebAPI 2 project and I am trying to add unit-testing with xunit and moq.</p>

<p>This is my Get-Method in my Controller:</p>

<pre><code>public class SiteController : ApiController
{
    private readonly ISite _siteSrv;

    public SiteController( ISite siteSrv )
    {
        _siteSrv = siteSrv;
    }

    public async Task&lt;IHttpActionResult&gt; Get( int id )
    {
        //reading current user login id and user roles [...]

        // getting data from SiteService, which I try to mock
        var site = await _siteSrv.Get( id, userLoginId.Value, roles );

        //converting it into a model [...]

        return Ok(model);
    }
}
</code></pre>

<p>And my SiteService Get method:</p>

<pre><code>public async Task&lt;Site&gt; Get( int id, long userLoginId, string[] roles )
{
    //...doing some stuff
    // and returning the data
    return await _context.Sites
        .AsNoTracking()
        .FirstOrDefaultAsync( s =&gt; s.SiteId == id );
}
</code></pre>

<p>This is my Test-Method:</p>

<pre><code>[Fact]
public async Task Verify_GetId_Method_Returns_OkResult_ForAdmin()
{
    int siteId = 1;
    long userLoginId = 1;
    string role = ""Admin"";

    // fake site
    var site = new Site()
    {
        SiteId = 1,
        SiteName = ""Site1""
    };

    // mocking the SiteService
    var mockSite = new Mock&lt;ISite&gt;();
    // setting up the Get-Method returning the fake site asynchronously
    mockSite.Setup( s =&gt; s.Get( siteId, userLoginId, new string[] { role } ) )
        .ReturnsAsync( site );

    // faking HttpContext
    using ( new FakeHttpContext.FakeHttpContext() )
    {
        // current logged in user
        HttpContext.Current.User = CurrentUserTestData.GetAccount( 
            userLoginId, role );

        // the SiteController with the mocked SiteService
        var controller = new SiteController( mockSite.Object );
        // setting Request
        controller.Request = new HttpRequestMessage();
        controller.Request.Properties.Add( 
            HttpPropertyKeys.HttpConfigurationKey,
            new HttpConfiguration() );

        // calling the async Get method of the controller
        var result = await controller.Get( siteId );
        // !! result is always NULL !!

        Assert.NotNull( result ); // FAIL
    }
}
</code></pre>

<p>Any idea what I am doing wrong?</p>
",https://stackoverflow.com/questions/61754899/mocked-async-method-in-xunit-test-returns-always-null,"['unit-testing', 'async-await', 'asp.net-web-api2', 'moq', 'xunit']",580,True,1,1
Writing to a file or String in Rust,"<p>TL;DR: I want to implement trait <code>std::io::Write</code> that outputs to a memory buffer, ideally String, for unit-testing purposes.</p>
<p>I must be missing something simple.</p>
<p>Similar to another question, <a href=""https://stackoverflow.com/questions/22355273/writing-to-a-file-or-stdout-in-rust"">Writing to a file or stdout in Rust</a>, I am working on a code that can work with any <code>std::io::Write</code> implementation.</p>
<p>It operates on structure defined like this:</p>
<pre class=""lang-rust prettyprint-override""><code>pub struct MyStructure {
    writer: Box&lt;dyn Write&gt;,
}
</code></pre>
<p>Now, it's easy to create instance writing to either a file or <code>stdout</code>:</p>
<pre><code>impl MyStructure {
    pub fn use_stdout() -&gt; Self {
        let writer = Box::new(std::io::stdout());
        MyStructure { writer }
    }

    pub fn use_file&lt;P: AsRef&lt;Path&gt;&gt;(path: P) -&gt; Result&lt;Self&gt; {
        let writer = Box::new(File::create(path)?);
        Ok(MyStructure { writer })
    }
    
    pub fn printit(&amp;mut self) -&gt; Result&lt;()&gt; {
        self.writer.write(b&quot;hello&quot;)?;
        Ok(())
    }
}
</code></pre>
<p>But for unit testing, I also need to have a way to run the business logic (here represented by method <code>printit()</code>) and <strong>trap its output</strong>, so that its content can be checked in the test.</p>
<p>I cannot figure out how to implement this. <a href=""https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=f66f3a7a43381248b6245c1e2ee11ad1"" rel=""noreferrer"">This playground code</a> shows how I would like to use it, but it does not compile because it breaks borrowing rules.</p>
<pre><code>// invalid code - does not compile!
fn main() {
    let mut buf = Vec::new(); // This buffer should receive output
    let mut x2 = MyStructure { writer: Box::new(buf) };
    x2.printit().unwrap();
    
    // now, get the collected output
    let output = std::str::from_utf8(buf.as_slice()).unwrap().to_string();
    
    // here I want to analyze the output, for instance in unit-test asserts
    println!(&quot;Output to string was {}&quot;, output);
}
</code></pre>
<p>Any idea how to write the code correctly? I.e., how to implement a writer on top of a memory structure (String, Vec, ...) that can be accessed afterwards?</p>
",https://stackoverflow.com/questions/63024483/writing-to-a-file-or-string-in-rust,['rust'],6015,True,12,1
Apache Flink: How to update Source Function in Unit Test?,"<p>I need my Flink job to read from a local instance of a Source Function and update every time the Source Function instance's data changes within the unit testing code itself rather than a stream.</p>
<p>Pseudocode:</p>
<pre><code>StreamExecutionEnvironment env = ...getExecutionEnvironment();
StockSource src = new StockSource(); // the Source Function instance
env.addSource(src);
results = Pipeline(env); // does some calculations and returns the calculated data
env.execute();


// Test 1
When: src.sendData(&quot;TWTR&quot;, 120.6);
Assert: results.eurRate == 98.87;

// Test 2
When: src.sendData(&quot;GOOG&quot;, 300);
Assert: results.eurRate == 245.95;
</code></pre>
<p>Is doing something like this even possible in Flink?</p>
",https://stackoverflow.com/questions/65331859/apache-flink-how-to-update-source-function-in-unit-test,"['java', 'stream', 'apache-flink', 'data-stream']",1211,True,1,2
H2Database gives error for SET IDENTITY_INSERT,"<p>I am struggling with this belo error
I use H2Database for unit testing.
I have <code>SET IDENTITY_INSERT &lt;SchemaName.table_name&gt; ON/OFF;</code> in our DML .sql file. This works perfectly fine in our production sql server. But this lines fails in h2database.
H2 properties::</p>
<pre><code>{
  &quot;driverClass&quot;: &quot;org.h2.Driver&quot;,
  &quot;user&quot;: &quot;test&quot;,
  &quot;password&quot;: &quot;test&quot;,
  &quot;url&quot;: &quot;jdbc:h2:mem:testdb;IGNORECASE=TRUE;DB_CLOSE_DELAY=-1;TRACE_LEVEL_FILE=3;TRACE_LEVEL_SYSTEM_OUT=3&quot;,
  &quot;properties&quot;: {
    &quot;charSet&quot;: &quot;UTF-8&quot;,
    &quot;mode&quot;: &quot;MSSQLServer&quot;
  }
}
</code></pre>
<p>Error :</p>
<pre><code>org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement &quot;SET IDENTITY_INSERT[*] mytable ON &quot;; expected &quot;@, AUTOCOMMIT, MVCC, EXCLUSIVE, IG
NORECASE, PASSWORD, SALT, MODE, COMPRESS_LOB, DATABASE, COLLATION, BINARY_COLLATION, UUID_COLLATION, CLUSTER, DATABASE_EVENT_LISTENER, ALLOW_LITERALS, DEFA
ULT_TABLE_TYPE, CREATE, HSQLDB.DEFAULT_TABLE_TYPE, PAGE_STORE, CACHE_TYPE, FILE_LOCK, DB_CLOSE_ON_EXIT, AUTO_SERVER, AUTO_SERVER_PORT, AUTO_RECONNECT, ASSE
RT, ACCESS_MODE_DATA, OPEN_NEW, JMX, PAGE_SIZE, RECOVER, NAMES, SCOPE_GENERATED_KEYS, SCHEMA, DATESTYLE, SEARCH_PATH, SCHEMA_SEARCH_PATH, JAVA_OBJECT_SERIA
LIZER, LOGSIZE, FOREIGN_KEY_CHECKS&quot;; SQL statement:
SET IDENTITY_INSERT mytable ON [42001-199]
</code></pre>
<p>pom.xml::</p>
<pre><code> &lt;dependency&gt;
        &lt;groupId&gt;com.h2database&lt;/groupId&gt;
        &lt;artifactId&gt;h2&lt;/artifactId&gt;
         &lt;version&gt;1.4.199&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
</code></pre>
<p>Any help around this is appeciated.</p>
",https://stackoverflow.com/questions/64918861/h2database-gives-error-for-set-identity-insert,"['sql-server', 'database', 'h2']",472,False,1,0
&#39;globalThis&#39; underfined for Jest test cases,"<p>I am using globalThis property specifically globalThis.scrollTo(0,0) in my React WebApp.</p>

<p>I am using Jest for unit testing alongwith Enzyme.</p>

<p>As of test cases fail as it is unable to identify globalThis and says that 'globalThis' is undefined.</p>

<p>Is there a way to introduce globalThis into the tests just like jsdom does for window etc ?</p>

<p>For Example</p>

<p>-- abc.tsx --</p>

<pre><code>const abc: React.FC&lt;CustomProps&gt; = props =&gt; {
useEffect(() =&gt; {
globalThis?.scrollTo(0,0);
}
}
</code></pre>

<p>-- abcTest.tsx --</p>

<pre><code>wrapper = mount(&lt;abc/&gt;);
</code></pre>

<p><strong>mount</strong> produces error that ""globalThis"" is undefined</p>
",https://stackoverflow.com/questions/60976511/globalthis-underfined-for-jest-test-cases,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'jsdom']",18849,True,17,2
How to Unit Test Static Method using MOQ?,"<p>Below is the Scenario.<br/>
I have a public class which contains 2 static methods.</p>

<pre><code>public class Helper{    
public static string (string args1, Datetime dt)
{
string computedValue = GetSomeValue(args1);
return dt.ToString(computedValue);
}        
public static GetSomeValue(string args2){
//Perform Computation and return a string
}
}
</code></pre>

<p>Now I want to unit test the <code>GetSomeValue</code> method. I am not sure if we can mock the static method or if we should be unit testing this method.<br/>
Please help.</p>
",https://stackoverflow.com/questions/61908664/how-to-unit-test-static-method-using-moq,"['c#', '.net', 'unit-testing', 'moq']",658,False,0,1
Dependency Injecting IConfiguration within unit test class,"<p>I am using ASP.NET Core 3, I have a helpers class that contains 2 dependencies, IConfiguration and ILogger, when unit testing the concrete implementation seen here:</p>

<pre><code>public class Helper : IHelpers
{
    private IConfiguration configuration;
    private readonly ILogger&lt;Helper&gt; logger;
    public Helper(IConfiguration _config, ILogger&lt;Helper&gt; _logger)
    {
        configuration = _config;
        logger = _logger;
    }
    public Tuple&lt;string, string&gt; SpotifyClientInformation()
    {
        Tuple&lt;string, string&gt; tuple = null;
        try
        {
            if (configuration != null)
            {
                string clientID = configuration[""SpotifySecrets:clientID""];
                //Todo move secretID to more secure location
                string secretID = configuration[""SpotifySecrets:secretID""];
                tuple = new Tuple&lt;string, string&gt;(clientID, secretID);
            }
        }
        catch (Exception ex)
        {
            logger.LogCritical(""Configuration DI not set up correctly"",ex);
        }

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

<p>In my tests, I try to DI  helpers via this code:</p>

<pre><code>public class HelperTests
{
    private ServiceCollection serviceCollection;
    private IHelpers helper;
    [SetUp]
    public void Setup()
    {
        serviceCollection = new ServiceCollection();
        serviceCollection.AddTransient&lt;IHelpers, Helper&gt;();


        ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

        helper = serviceProvider.GetService&lt;IHelpers&gt;();
    }

    [Test]
    public void GetSpotifyConfiguration()
    {
        Tuple&lt;string, string&gt; devData = helper.SpotifyClientInformation();
        Assert.NotNull(devData.Item1);
        Assert.NotNull(devData.Item2);
    }
}
</code></pre>

<p>but I get the error that reads:</p>

<pre><code>System.InvalidOperationException : Unable to resolve service for type 
'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'Spotify_Angular.Helper'.
</code></pre>
",https://stackoverflow.com/questions/59741796/dependency-injecting-iconfiguration-within-unit-test-class,"['c#', 'asp.net-core']",973,True,0,1
Jasmine-ts throwing an error about package subpath,"<p>I'm starting on a jasmine unit testing path and I'm having issues trying to execute jasmine and finding my ts written specs.</p>
<p>I have jasmine-ts and I just run the usual</p>
<pre><code>jasmine-ts --config=spec/support/jasmine.json
</code></pre>
<p>the above line is executed after I run <code>jasmine init</code> on the root folder</p>
<p>EDIT:</p>
<p>Sorry I forgot to put in the error</p>
<pre><code>internal/modules/cjs/loader.js:438
      throw e;
      ^

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './dist' is not defined by &quot;exports&quot; i
</code></pre>
",https://stackoverflow.com/questions/65335931/jasmine-ts-throwing-an-error-about-package-subpath,"['typescript', 'unit-testing', 'jasmine', 'jasmine-ts']",2935,True,7,3
Angular Unit Testing with Dynamic Component Failed with error TypeError: Cannot read property &#39;ɵcmp&#39; of undefined,"<p>list of Angular dependency </p>

<pre><code>    ""@angular/common"": ""~9.1.1"",
    ""@angular/compiler"": ""~9.1.1"",
    ""@angular/core"": ""~9.1.1"",
    ""@angular/forms"": ""~9.1.1"",
    ""@angular/platform-browser"": ""~9.1.1"",
    ""@angular/platform-browser-dynamic"": ""~9.1.1"",
    ""@angular/router"": ""~9.1.1"",
    ""@fortawesome/fontawesome-free"": ""^5.13.0""
</code></pre>

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

<pre><code>import { Component, ViewChild, OnDestroy, AfterViewInit  } from '@angular/core';
import { ComponentFactoryResolver, Type, ComponentRef, ChangeDetectorRef } from '@angular/core';
import { Subject } from 'rxjs';

import { DynamicCompDirective } from '../../directive/dynamic-comp.directive';
import { DialogRef } from '../../model/dialog.ref';

@Component({
  selector: 'app-dialog-layout',
  templateUrl: './dialogLayout.component.html',
  styleUrls: ['./dialogLayout.component.css']
})
export class DialogLayoutComponent implements AfterViewInit, OnDestroy {

  @ViewChild(DynamicCompDirective, {static: true})insertionPoint: DynamicCompDirective;

  dialogHeight: number;
  dialogWidth: number;
  backDrop: boolean = false;

  public componentRef: ComponentRef&lt;any&gt;;
  public childComponentType: Type&lt;any&gt;;

  private readonly _onClose = new Subject&lt;any&gt;();
  public onClose = this._onClose.asObservable();


  constructor(private resolver: ComponentFactoryResolver,
              private cd: ChangeDetectorRef,
              private dialogRef: DialogRef) { }

  ngAfterViewInit() {
    this.loadChildComponent(this.childComponentType);
    this.cd.detectChanges();
  }

  ngOnDestroy() {
    if (this.componentRef) {
        this.componentRef.destroy();
    }
  }

  onOverlayClicked(evt: MouseEvent) {
    if (this.backDrop) {
      this.dialogRef.close();
    }
  }

  onDialogClicked(evt: MouseEvent) {
    evt.stopPropagation()
  }

  loadChildComponent(componentType: Type&lt;any&gt;) {
    const componentFactory = this.resolver.resolveComponentFactory(componentType);
    const viewContainerRef = this.insertionPoint.container;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
  }

  close() {
    this._onClose.next();
  }

}
</code></pre>

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

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ChangeDetectorRef } from '@angular/core';
import { DialogLayoutComponent } from './dialogLayout.component';
import { DialogRef } from '../../model/dialog.ref';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ DialogLayoutComponent ],
      providers: [ { provide: DialogRef, useClass: DialogRef } ]
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p><strong>dialog.ref.ts</strong></p>

<pre><code>import { Observable, Subject } from 'rxjs';

export class DialogRef {

  constructor() {}

  private readonly _afterClosed = new Subject&lt;any&gt;();

  afterClosed: Observable&lt;any&gt; = this._afterClosed.asObservable();

  public close(result?: any): void {
    this._afterClosed.next(result);
  }

}
</code></pre>

<p>My unit testing failed with error <strong>TypeError: Cannot read property 'ɵcmp' of undefined</strong></p>

<p>No clue where this error is coming from. Already spend 2 days googling this error, but no luck. Kindly help to resolve the issue.</p>

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

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/61295161/angular-unit-testing-with-dynamic-component-failed-with-error-typeerror-cannot,"['angular-unit-test', 'angular-dynamic-components', 'angular-dependency-injection']",7856,False,2,1
Unit testing lazy loaded modules routing,"<p>I'm facing some problems with unit testing for routing. I've tried <a href=""https://stackoverflow.com/questions/51635273/angular-unit-testing-lazy-loaded-modules-with-routing"">this</a> solution, but this lazy loading notation is now <a href=""https://stackoverflow.com/questions/59943328/what-is-difference-between-loadchildren-import-hoge-module-ts-thenm"">deprecated</a>, so my tests are failed for some reason.
Could someone give me advice what might be wrong with my code?</p>

<p><strong><em>app-routing.module.ts</em></strong>:</p>

<pre><code>export const routes: Routes = [
{path: 'about', component: AboutComponent},
{path: 'files', loadChildren: () =&gt; import('./files/files.module').then(m =&gt; m.FilesModule)}, 
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }
</code></pre>

<p><strong><em>app-routing.module.spec.ts</em></strong>:</p>

<pre><code>describe('AppRoutingModule', () =&gt; {
   let location: Location;
   let router: Router;
   let fixture;

   beforeEach(() =&gt; {
   TestBed.configureTestingModule({
       imports:[
           RouterTestingModule.withRoutes(routes),
           HttpClientModule,
           AboutComponent,
       ],
       declarations: [
           AppComponent,
           FilesComponent,
       ],
       providers: [{provide: APP_BASE_HREF, useValue: '/'}]
   })

   router = TestBed.get(Router);
   location = TestBed.get(Location);

   fixture = TestBed.createComponent(AppComponent);
   router.initialNavigation();
   });

   it('should navigate to files', fakeAsync(() =&gt; {
       const loader = TestBed.get(NgModuleFactoryLoader);
       loader.stubbedModules = {lazyModule : FilesModule }

       router.resetConfig([
           {path: 'files', loadChildren: 'lazyModule'},
       ]);

       router.navigate(['files']);
       tick(50);
       fixture.detectChanges();

       expect(location.path()).toBe('/files');
   }));
});

</code></pre>

<p>Thank you!</p>
",https://stackoverflow.com/questions/60262547/unit-testing-lazy-loaded-modules-routing,"['angular', 'typescript', 'unit-testing', 'jasmine', 'lazy-loading']",4898,True,2,2
How to trigger transitionend with Jest unit testing,"<p>I am using angular 8 and Jest for unit testing. I have added a listener for 'transitionend' on the element, but I haven't been able to figure out how to trigger/mock the transitionend event with Jest</p>
<pre><code>this.animatedElement.nativeElement.addEventListener('transitionend', () =&gt; {
      this.transitionEnded = true;
});
</code></pre>
<p>I am trying to create a unit test that tests <code>this.transitionEnded</code> is true</p>
",https://stackoverflow.com/questions/63180216/how-to-trigger-transitionend-with-jest-unit-testing,"['javascript', 'css', 'angular', 'unit-testing', 'jestjs']",1788,True,3,2
How to mock an instance variable using Mockito in java?,"<p>I'm a noob to unit testing and use of mockito</p>
<p>I have a class</p>
<pre><code>public class SystemTenancyConfig {
    private String systemTenancy;
}
</code></pre>
<p>I have used this in another class where I'm getting the value:</p>
<pre><code>
@Inject
SystemTenancyConfig systemTenancyConfig;
String val = systemTenancyConfig.getsystemTenancy();
</code></pre>
<p>How do I mock systemTenancyConfig.getsystemTenancy() to be set to a string say &quot;Test&quot;?
UpdatE:</p>
<pre><code>    @Mock
    private SystemTenancyConfig systemTenancyConfig;
       when(systemTenancyConfig.getSystemTenancy()).thenReturn(&quot;test&quot;);
</code></pre>
<p>is giving me a NPE</p>
",https://stackoverflow.com/questions/62865930/how-to-mock-an-instance-variable-using-mockito-in-java,"['java', 'mockito']",2303,True,0,1
Embedded Mongo : Session not supported by Mongo Cluster Issue,"<p>I am working on unit testing using embedded mongo. It is able to connect to mongo at the random port but on running the test I am getting error of - com.mongodb.MongoClientException: Sessions are not supported by the MongoDB cluster to which this client is connected</p>
",https://stackoverflow.com/questions/63517424/embedded-mongo-session-not-supported-by-mongo-cluster-issue,"['mongodb', 'spring-boot', 'spring-mongodb', 'spring-mongo']",496,False,0,1
How to use e2e or unit testing with nativescript-vue?,"<p>How to use e2e or unit testing with nativescript-vue?</p>
<p>Would you please describe a <a href=""https://github.com/wix/Detox/blob/master/docs/Introduction.GettingStarted.md"" rel=""nofollow noreferrer"">Getting Started</a> kind of guide?</p>
<p>Is there any tested <strong>testing method</strong> with nativescript 7 ?</p>
<p>Does <a href=""https://appium.io/"" rel=""nofollow noreferrer"">appium</a> or <a href=""https://github.com/wix/Detox"" rel=""nofollow noreferrer"">detox</a> really work?</p>
<p>Is it possible to update <a href=""https://github.com/rigor789/ui-tested-nsvue-app"" rel=""nofollow noreferrer"">ui-tested-nsvue-ap</a>p somehow?</p>
",https://stackoverflow.com/questions/64097583/how-to-use-e2e-or-unit-testing-with-nativescript-vue,"['nativescript', 'appium', 'nativescript-vue', 'detox']",144,True,0,1
UI alignment Testing in iOS,"<p>I am unit testing UI elements on iOS using the native XCTest framework. The limitation which I found is that we <strong>cannot test the alignment of UI objects on screen</strong>. Is there any third party framework which can help achieving this functionality. Please share. Thanks!</p>
",https://stackoverflow.com/questions/61506710/ui-alignment-testing-in-ios,"['swift', 'xcode-ui-testing']",109,False,0,1
SharePoint visual webpart unit testing in visual studio,"<p>I need to know whether we can create test cases for custom webparts that are build for SharePoint web applications. I have created custom webpart for my SharePoint list with asp.net controls (asp:textbox, asp:dropdown etc..) and added functions like populating dropdown in page_load, used spquery for querying items and displayed in asp gridview </p>

<pre><code> protected void Page_Load(object sender, EventArgs e)
{
  if(!IsPostBack)
   {
     // Check new or edit item and populate saved values in controls on edit item
    }
}

Protected void btnSave_Click(object sender, EventArgs e)
{
  // Action done on save click
}

</code></pre>

<p>I have used Nunit for creating unit test cases for console applications in development phase. It is very useful for me to cover all test cases also reduces testing phase time and bugs.</p>

<p>But I don't know how to implement unit testing in webparts page load function, button click actions etc..</p>

<p>I am new to SharePoint as well as Unit testing. It will be very greatful, if someone help me to handle this by providing some examples for the above cases.</p>
",https://stackoverflow.com/questions/62103951/sharepoint-visual-webpart-unit-testing-in-visual-studio,"['c#', 'asp.net', 'visual-studio', 'unit-testing', 'sharepoint-2013']",57,False,1,0
Unit testing a PHP API client,"<p>I am writing an API client in php that sends request to an API server to get the details of a person based on his ID on the API server. The API server has a token based authentication and when queried with the correct ID and the token, the details of that person are returned as a JSON response. I am comfortable with the implementation of the class. However, when it comes to unit testing, I have not much idea about what all should be the best test cases that I should write. Unfortunately, I couldn't find any resources on the same. I have written a few test cases that validates the request parameters and the end point to query. Can anyone shed some more light on unit testing API clients?</p>
",https://stackoverflow.com/questions/63884833/unit-testing-a-php-api-client,"['php', 'api', 'unit-testing', 'phpunit', 'apiclient']",713,True,1,1
Junit test - how to mock class private member of type of private interface?,"<p>I wrote few junits, using some mocking techniques.
But stucked here:</p>
<pre><code>public class Lookup {
    private LookupMethod lookupMethod;

    private interface LookupMethod {
        String lookup(String input);
    }

   public String treatString(@Nullable String input) {
       ...
       String lookupResult = lookupMethod.lookup(lookupInput);
       ...
   }
}
</code></pre>
<p>I'm unit testing the <strong>treatString()</strong> method and looking how to mock the <strong>lookupMethod.lookup()</strong> call in the <strong>treatString()</strong> method above.
I can't change <strong>Lookup</strong> class.</p>
<p>I'll appreciate a tip (example would be even better).</p>
",https://stackoverflow.com/questions/63707548/junit-test-how-to-mock-class-private-member-of-type-of-private-interface,"['java', 'junit', 'mocking']",102,False,0,1
Unit Testing Input Event in Angular6,"<p>I have an Input field in the UI</p>

<p><code>&lt;input matInput placeholder=""BLC"" id='blc' formControlName=""blc"" (change)=""onBLCChanged($event)"" /&gt;</code></p>

<p>I want to do unit testing for this, but this field send $event not any value to the function, how can I mock this.</p>

<pre><code>  it('some text', async(async() =&gt; {
    spyOn(component, 'onBLCChanged');
    // first round of change detection
    fixture.detectChanges();
    // get ahold of the input
    let input = debugElement.query(By.css('#blc'));
    let inputElement = input.nativeElement;

    //set input value
    inputElement.value = 'test';
    inputElement.dispatchEvent(new Event('change'));

    expect(component.onBLCChanged).toHaveBeenCalledWith({});
  }));
</code></pre>

<p>This is not working, <code>Expected spy onBLCChanged to have been called with [ Object({  }) ] but actual calls were [ [object Event] ].
</code></p>

<p>Please help, <code>onBLCChanged</code> is the method in the .ts file.</p>
",https://stackoverflow.com/questions/59824622/unit-testing-input-event-in-angular6,['angular'],45,True,0,2
Is there possibillity to call constructor inside Container.get() in typedi?,"<p>I am using typedi with node.js</p>

<p>I wonder if I could do something like that</p>

<pre><code>const obj = Container.get(MyObj(creds));
</code></pre>

<p>istead of</p>

<pre><code>const obj = new MyObj(creds);
</code></pre>

<p>I need that to use because of jasmine unit testing. I need the same object.</p>

<p>How should I do it to get the same object inside my unit test?</p>
",https://stackoverflow.com/questions/60165548/is-there-possibillity-to-call-constructor-inside-container-get-in-typedi,"['node.js', 'unit-testing', 'dependency-injection', 'jasmine']",713,False,1,1
how to write functional unit test cases in react native?,"<p>I am new to react native. I have implemented functionality and snapshot unit testing but not sure how to write functional and API level unit test cases. I am using enzyme and jest. also I have used redux for state management. </p>

<p>following is my few files .</p>

<p>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>/* eslint-disable no-unused-vars */
/* eslint-disable no-use-before-define */
/* eslint-disable class-methods-use-this */

import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import * as myConstant from './src/common/constants';

import reducer from './src/reducer/reducer';
import Navigation from './src/common/navigator';


const client = axios.create({
  baseURL: myConstant.API,
  responseType: 'json',
  timeout: 25000,
});

const store = createStore(reducer, applyMiddleware(axiosMiddleware(client)));


export default class App extends Component {
  render() {
    return (
      &lt;Provider store={store}&gt;
        &lt;View style={styles.container}&gt;
          &lt;Navigation /&gt;
        &lt;/View&gt;
      &lt;/Provider&gt;
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    marginTop: 50,
  },
});</code></pre>
</div>
</div>
</p>

<p>home.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>/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-unused-vars */
import React, { Component } from 'react';
import { ActivityIndicator } from 'react-native-paper';
import {
  View, Text, FlatList, TouchableOpacity,
} from 'react-native';
import { connect } from 'react-redux';
import { Ionicons } from '@expo/vector-icons';
import styles from './style';
import { listRepos } from '../../reducer/reducer';
import ErrorAlert from '../../common/errorAlertComponent/errorAlert';


class Home extends Component {
  componentDidMount() {
    this.props.listRepos();
  }

  FlatListItemSeparator = () =&gt; (
    &lt;View style={styles.flatListItemSeparator} /&gt;
  )

  renderItem = ({ item }) =&gt; (

    &lt;View style={styles.listRowContainer}&gt;

      &lt;TouchableOpacity onPress={() =&gt; this.props.navigation.navigate('ThumbnailViewScreen', {
        albumID: item.id,
      })} style={styles.listRow}&gt;
        &lt;View style={styles.listTextNavVIew}&gt;
          &lt;Text style={styles.albumTitle}&gt; {item.title} &lt;/Text&gt;
          &lt;Ionicons name='md-arrow-dropright' style={styles.detailArrow} /&gt;
        &lt;/View&gt;
      &lt;/TouchableOpacity&gt;

    &lt;/View&gt;
  );

  render() {
    const { error, loading, albums } = this.props;

    if (error) {
      return &lt;ErrorAlert /&gt;;
    }

    if (loading) {
      return (
        &lt;View style={{ flex: 1, paddingTop: 30 }}&gt;
            &lt;ActivityIndicator animating={true} size='large' /&gt;
        &lt;/View&gt;
      );
    }
    return (
      &lt;View style={styles.MainContainer} &gt;
        &lt;FlatList
          styles={styles.container}
          data={albums}
          renderItem={this.renderItem}
          ItemSeparatorComponent={this.FlatListItemSeparator}

        /&gt;
      &lt;/View&gt;
    );
  }
}

const mapStateToProps = (state) =&gt; {
  const storedRepositories = state.albums.map((repo) =&gt; ({ key: repo.id.toString(), ...repo }));
  return {
    albums: storedRepositories,
    loading: state.loading,
    error: state.error,
  };
};

const mapDispatchToProps = {
  listRepos,
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);</code></pre>
</div>
</div>
</p>

<p>reducer.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>export const GET_ALBUM = 'album/LOAD';
export const GET_ALBUM_SUCCESS = 'album/LOAD_SUCCESS';
export const GET_ALBUM_FAIL = 'album/LOAD_FAIL';


const initialState = {
  albums: [],
  loading: false,
  error: null,
};


export default function reducer(state = initialState, action) {
  switch (action.type) {
    case GET_ALBUM:
      return { ...state, loading: true };
    case GET_ALBUM_SUCCESS:
      return { ...state, loading: false, albums: action.payload.data };
    case GET_ALBUM_FAIL:
      return {
        ...state,
        loading: false,
        error: 'Error while fetching albums',
      };
    default:
      return state;
  }
}

export function listRepos() {
  return {
    type: GET_ALBUM,
    payload: {
      request: {
        url: 'photos/',
      },
    },
  };
}

export function listThumb(albumId) {
  return {
    type: GET_ALBUM,
    payload: {
      request: {
        url: `photos?albumId=${albumId}`,
      },
    },
  };
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/60483628/how-to-write-functional-unit-test-cases-in-react-native,"['react-native', 'unit-testing', 'jestjs', 'enzyme', 'testcase']",1557,True,3,1
Should I mock every single dependencies in unit testing?,"<p>After a lot reading, I found that people advice to mock every dependencies in a method under unit test.</p>

<p><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><a href=""https://stackoverflow.com/questions/38181/when-should-i-mock"">When should I mock?</a></p>

<p>However, I have a method that creates a list of objects (the dependencies) and uses the method these objects to alter the list. In the real-life scenario, the method is transforming data payload sent by the client into these objects.
Below is the code implementation in Typescript but it just gives you an idea.</p>

<pre><code>import {expect} from 'chai';

import 'mocha';

class Bar {
    private val: number;

    constructor(val: number) {
        this.val = val;
    }

    isValid(): boolean {
        return this.val !== 2;
    }

    canMergeWith(bar: Bar): boolean {
        return this.val === bar.val;
    }
}

class BarBuilder {
    constructor() {
    }

    createBars(payload: number[]): Bar[] {
        const bars: Bar[] = [];
        payload.forEach(p =&gt; {
            bars.push(new Bar(p));
        });

        const filtered = this.filterBars(bars);
        const merged = this.mergeBars(filtered);
        return merged;
    }

    private filterBars(bars: Bar[]): Bar[] {
        return bars.filter(b =&gt; b.isValid());
    }

    private mergeBars(bars: Bar[]): Bar[] {
        const merged: Bar[] = [];
        bars.forEach((bar, i) =&gt; {
            if (i &gt; 0) {
                const before = bars[i - 1];
                if (!bar.canMergeWith(before)) {
                    merged.push(bar);
                }
            } else {
                merged.push(bar);
            }
        });
        return merged;
    }
}

describe('BarBuilder', () =&gt; {
    it('Should convert payload into valid bars', () =&gt; {
        const payload = [1, 2, 3, 4, 4, 5, 5];
        const barBuilder = new BarBuilder();
        const bars = barBuilder.createBars(payload);
        expect(bars).to.deep.equal([{val: 1}, {val: 3}, {val: 4}, {val: 5}]);
    });
});
</code></pre>

<p>Currently, the test is passing. But it is violating the rule that <strong>I should mock every dependency in the class</strong>.</p>

<p>My question which one of the following should I do: </p>

<ol>
<li>Should I really mock the class Bar in order to comply to that rule?</li>
</ol>

<p>If so, I find another difficulty doing that. If I mock the class Bar, how do I make the mock methods <code>canMergeWith</code> and <code>isValid</code>  return true or false based on their input? Isn't the equivalent as re-writting the class itself?</p>

<ol start=""2"">
<li>Should I refactor my code instead?</li>
</ol>

<p>I was also thinking probably the problem is with my code being not testable. Before, the methods <code>canMergeWith</code> and <code>isValid</code> belonged to <code>BarBuilder</code>. For the sake of readability, I moved them inside Bar. But now, the unit testing <code>BarBuilder</code> is not trival anymore .</p>

<ol start=""3"">
<li>Leave the test as it is despite the fact that it is violating unit testing rule.</li>
</ol>
",https://stackoverflow.com/questions/61793083/should-i-mock-every-single-dependencies-in-unit-testing,"['unit-testing', 'oop', 'language-agnostic']",1409,True,2,1
How i can verify the signal in a unit test of Camunda process?,"<p>We use <a href=""https://github.com/camunda/camunda-bpm-assert"" rel=""nofollow noreferrer"">camunda-bpm-assert</a> and <a href=""https://github.com/camunda/camunda-bpm-assert-scenario/"" rel=""nofollow noreferrer"">camunda-bpm-assert-scenario</a> libs for Camunda  <strong>processes unit testing</strong> (testing of <code>.bpmn</code>).</p>

<p>But i couldn't find any approach for <strong>signal</strong> testing - how can we <em>verify, that signal with the right name and variables was thrown</em> during test execution?</p>

<p>Appreciate any ideas.</p>
",https://stackoverflow.com/questions/59789594/how-i-can-verify-the-signal-in-a-unit-test-of-camunda-process,"['unit-testing', 'bpmn', 'camunda', 'camunda-modeler']",352,True,1,1
Can one save raw data corresponding to a Pybind11 class,"<p>I'd like to be able to save raw byte array containing the data matching a (packed) C++ class exposed by Pybind11. Is this possible? It will really help with unit testing some C++ code. It would also be nice to do the reverse, but it isn't crucial.</p>
",https://stackoverflow.com/questions/63200831/can-one-save-raw-data-corresponding-to-a-pybind11-class,['pybind11'],425,True,1,1
Unit Testing UI-related functions,"<p>I'm trying to get unit-testing concept and get lost with testing UI-related functions, like this:</p>

<pre><code>const hideElem = elem =&gt; {
  elem.classList.add('js-hidden')
}
</code></pre>

<p>or this:</p>

<pre><code>const getInputValue = (inputElem) =&gt; {
  let inputEl = document.querySelector(inputElem)

  return inputEl.value
}
</code></pre>

<p>or this:</p>

<pre><code>const cleanInput = input =&gt; {
  const inputEl = document.querySelector(input)
  inputEl.value = ''
}
</code></pre>

<p>Do I need to cover such functions with unit tests in Jest? If yes - could you please explain how to combine here Jest and DOM-related things? </p>
",https://stackoverflow.com/questions/62455692/unit-testing-ui-related-functions,"['javascript', 'unit-testing', 'testing', 'jestjs']",90,True,2,1
How to check equality of items of two list using Assert in Nunit,"<p>I'm fairly new to unit testing. The following code is just for reference.
I want to check empId of list one is same as the emp id of list 2 or not.</p>

<pre class=""lang-cs prettyprint-override""><code>public class EmpInfo
{    
    public EmpInfo( string lastName,string firstName, string empId)
    {
        EAlphabeticLastName = lastName;
        EFirstName = firstName;
        EmpId = empId;
    }
}

[Test]
[Category(""Explicit"")]
public void testEmp() 
{
    public List&lt;EmpInfo&gt; List1e = new List&lt;EmpInfo&gt;(){        
            new EmpInfo(""dx"",""Tex"",""25"")  
    };

    public List&lt;EmpInfo&gt; List2e = new List&lt;EmpInfo&gt;(){          
            new EmpInfo(""dx"",""Tex"",""25"")  
    };
    Assert.AreEqual(List1e.empId,List2e.empId);
}
</code></pre>

<p>What is the correct way to check equality of list items in Nunit (C#) ? </p>
",https://stackoverflow.com/questions/59732297/how-to-check-equality-of-items-of-two-list-using-assert-in-nunit,"['c#', '.net-core', 'nunit', 'assert']",1633,True,1,4
Using package level variables in go test files,"<p>I am trying to write a unit test for a file that is like this</p>
<pre><code>//file1.go
var (
    fileName = &quot;/path/to/original/file.json&quot;
)

func DoSomething(){
    // Read &lt;fileName&gt; and do some stuff
}
</code></pre>
<p>But for unit testing, I would like to use /path/to/dummy/file.json to be used by DoSomething()
file1_test.go will be under the same package as file.go
What would be the correct approach for writing test cases for this function?</p>
<p>Will it be a good idea to modify fileName variable to /path/to/dummy/file.json ? or
Should we modify the file1.go to make it suitable for testing?</p>
<p>Is this the standard to make these kind of values configurable so that they can modified during unit testing e.g. file name in this case or we should modify our function so that it can work with byte stream data directly so during testing testing we can feed dummy data directly?</p>
",https://stackoverflow.com/questions/63773379/using-package-level-variables-in-go-test-files,"['unit-testing', 'go', 'go-testing']",1057,True,0,1
UmiJs Unit test error - _umi.connect) is not a function,"<p>I am new in unit testing in reactjs.
I tried to test my login component rendering
For testing, i am using JEST and enzyme.</p>
<p>[This is the error, i am getting]</p>
<p><a href=""https://i.stack.imgur.com/vyEdd.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/vyEdd.png"" alt="""" /></a></p>
<p>Test case code:</p>
<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import Login from './index'; // Introduce the corresponding React component

it('renders Login page', () =&gt; {
    const wrapper = shallow(&lt;Login.WrappedComponent login={{ name: '' }} /&gt;);
})
</code></pre>
<blockquote>
<p>i am using Real project with umi - <code>https://ant.design/docs/react/practical-projects</code></p>
</blockquote>
<p>can any one help me on this.</p>
",https://stackoverflow.com/questions/62935492/umijs-unit-test-error-umi-connect-is-not-a-function,"['reactjs', 'redux', 'antd', 'redux-saga', 'umijs']",603,True,2,1
java.lang.NoSuchMethodError: okhttp3.internal.Internal.initializeInstanceForTests() When creating a Mock Server on Android,"<p><code>java.lang.NoSuchMethodError: okhttp3.internal.Internal.initializeInstanceForTests() When creating a Mock Server on Android</code></p>
<p>I tried to update the dependency but it did not work.</p>
<p>I am new to Android Unit testing and I want to test if the API call is successful or not. I am working on the Open Source Project on <a href=""https://github.com/commons-app/apps-android-commons"" rel=""nofollow noreferrer"">https://github.com/commons-app/apps-android-commons</a> (leaderboard branch)</p>
<pre><code>java.lang.NoSuchMethodError: okhttp3.internal.Internal.initializeInstanceForTests()V

    at okhttp3.mockwebserver.MockWebServer.&lt;clinit&gt;(MockWebServer.java:103)
    at fr.free.nrw.commons.leaderboard.LeaderboardApiTest.initTest(LeaderboardApiTest.java:35)
</code></pre>
<pre><code>public class LeaderboardApiTest {

    MockWebServer server;

    @Before
    public void initTest() {
        server = new MockWebServer();
    }

    @Before
    public void setUp() throws IOException {
        server.enqueue(new MockResponse().setBody(&quot;{\n&quot;
            + &quot;    \&quot;status\&quot;: 200,\n&quot;
            + &quot;    \&quot;username\&quot;: \&quot;user\&quot;,\n&quot;
            + &quot;    \&quot;category_count\&quot;: 0,\n&quot;
            + &quot;    \&quot;limit\&quot;: null,\n&quot;
            + &quot;    \&quot;avatar\&quot;: \&quot;avatar\&quot;,\n&quot;
            + &quot;    \&quot;offset\&quot;: null,\n&quot;
            + &quot;    \&quot;duration\&quot;: \&quot;all_time\&quot;,\n&quot;
            + &quot;    \&quot;leaderboard_list\&quot;: [\n&quot;
            + &quot;        {\n&quot;
            + &quot;            \&quot;username\&quot;: \&quot;user\&quot;,\n&quot;
            + &quot;            \&quot;category_count\&quot;: 0,\n&quot;
            + &quot;            \&quot;avatar\&quot;: \&quot;avatar\&quot;,\n&quot;
            + &quot;            \&quot;rank\&quot;: 1\n&quot;
            + &quot;        }\n&quot;
            + &quot;    ],\n&quot;
            + &quot;    \&quot;category\&quot;: \&quot;used\&quot;,\n&quot;
            + &quot;    \&quot;rank\&quot;: 1\n&quot;
            + &quot;}&quot;));
        server.start();
    }

    @Test
    public void apiTest() throws IOException, JSONException {
        HttpUrl httpUrl = HttpUrl.parse(NetworkingModule.TEST_TOOLS_FORGE_URL);
        LeaderboardResponse response = sendRequest(new OkHttpClient(), httpUrl);
        Assert.assertEquals(&quot;avatar&quot;, response.getAvatar());
        Assert.assertEquals(&quot;username&quot;, response.getUsername());
        Assert.assertEquals(Integer.valueOf(0), response.getRank());
        Assert.assertEquals(Integer.valueOf(0), response.getCategoryCount());
    }

    private LeaderboardResponse sendRequest(OkHttpClient okHttpClient, HttpUrl httpUrl)
        throws IOException, JSONException {
        Request request = new Builder().url(httpUrl).build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Gson gson = new Gson();
            return gson.fromJson(response.body().toString(), LeaderboardResponse.class);
        }
        return null;
    }

    @After
    public void shutdown() throws IOException {
        server.shutdown();
    }
}
</code></pre>
",https://stackoverflow.com/questions/62865787/java-lang-nosuchmethoderror-okhttp3-internal-internal-initializeinstancefortest,"['java', 'android', 'mocking', 'okhttp']",1582,True,2,1
Sorting char** array with generic quicksort in c,"<p>I am currently unit testing the generic quicksort I made for which i will post the code right here below, along with the compare method I'm using and the code I'm running to test it. <br />
The problem I find is that the array is not actually being sorted. The assertion fails and if I try to print the array after sorting it just prints the values in the predetermined order. <br />
I tried unit testing the algorithm for int and float values and it did sort just fine. <br />
I believe the problem may lie in the fact that I probably did not cast correctly the void pointer, resulting in undefined behaviour</p>
<pre><code>void quicksort(void* pointer, int size, int start, int end, int (*compare)(void*,void*)){
    if(end &gt; start){
        int index = partition(pointer, size, start, end,compare);
        quicksort(pointer,size,start,index-1,compare);
        quicksort(pointer,size,index+1,end,compare);
    }
}

int partition(void * pointer, int size, int start, int end, int (*compare)(void*,void*)){
    int beginning = start + 1;
    int ending = end;
    while(beginning &lt;= ending){
        if(compare(&amp;pointer[beginning*size],&amp;pointer[start*size]) &gt;= 0){
            beginning++;
        }
        else{
            if(compare(&amp;pointer[ending*size],&amp;pointer[start*size]) == -1){
                ending--;
            }
            else{
                swap(&amp;pointer[beginning*size],&amp;pointer[ending*size],size);
                beginning++;
                ending--;
            } 
        }
    }
    swap(&amp;pointer[start*size],&amp;pointer[ending*size],size);
    return ending;
}

void swap(void* datablocka, void* datablockb, size_t elem_size){
    char temp;
    char *chara = datablocka;
    char *charb = datablockb;
    while(elem_size--){
        temp = chara[elem_size];
        chara[elem_size] = charb[elem_size];
        charb[elem_size] = temp;
    }
}

int compare_string(void* first, void* second){
    char * a = first;
    char * b = second;
    int compare = strcmp(a,b);
    if (compare &lt; 0) return 1;
    else if(compare == 0) return 0;
    else return -1;
}

void quicksort_string_utest() {
  char* a[] = {&quot;a&quot;,&quot;aaa&quot;,&quot;abba&quot;,&quot;mime&quot;,&quot;pippo&quot;,&quot;cacciatorpediniere&quot;};
  char* b[] = {&quot;a&quot;,&quot;aaa&quot;,&quot;abba&quot;,&quot;cacciatorpediniere&quot;,&quot;mime&quot;,&quot;pippo&quot;};
  int end = (sizeof(a)/sizeof(a[0]))-1;
  quicksort(a, sizeof(a[0]), 0, end, compare_string );
  for(int i = 0; i &lt; 6; i++){
    assert(strcmp(a[i],b[i]) == 0);
  }
}
</code></pre>
<p>I would really appreciate your help with this, since as you can see I can't sort this out</p>
",https://stackoverflow.com/questions/63305471/sorting-char-array-with-generic-quicksort-in-c,"['arrays', 'c', 'casting', 'quicksort', 'generic-programming']",109,True,0,1
Is this sort of structure/scenario in a unit test project possible?,"<p>I'm new to the concept of unit testing and have started using xUnit framework to write my tests. I have a question that I would like to ask about unit testing.</p>
<p>In my test project, I'm going to have an interface which contains all the common test scenarios which will then be implemented by a base class. I didn't want to repeat writing the same code for the same test over and over in each test class files so in the base class I will have the implementation for each of the methods outlined in the interface but marked as virtual as it can be overwritten by the concrete test class when it needs to be.</p>
<p>For example:</p>
<pre><code>public interface IPersonTests
{
    void ValidateAge();
    void ValidateExperience();
    void ValidateAddress();
}
</code></pre>
<pre><code>public abstract class BasePersonTests : IPersonTests
{
    public virtual void ValidateAge()
    {
        // method implementation
    }

    public virtual void ValidateExperience()
    {
        // method implementation
    }

    public void ValidateAddress()
    {
        // method implementation
    }
}
</code></pre>
<pre><code>public class PersonA : BasePersonTests
{
    [Fact]
    public override void ValidateAge()
    {
        // different method implementation to the one specified in the base class
    }
}
</code></pre>
<p>Is it okay to have a code structure like the above for a unit test project?</p>
",https://stackoverflow.com/questions/63986308/is-this-sort-of-structure-scenario-in-a-unit-test-project-possible,"['c#', 'unit-testing', 'structure', 'xunit']",49,False,0,0
Unable to ignore import in jest,"<p>I want to ignore below code when I'm doing unit testing using jest.</p>
<pre><code>import Context from 'folder/Context'; 
</code></pre>
<p>this is having ts extension.</p>
<p>Context.ts contains ---- &gt;</p>
<pre><code>import {createContext} from 'react'
const Context = createContext({})
export const Provider = context.Provider
export default Context;
</code></pre>
<p>Now how to ignore this import in jest config.</p>
<p>Tried below options but it's not working.</p>
<pre><code> &quot;modulePathIgnorePatterns&quot;: [
        &quot;&lt;rootDir&gt;/src/folder/Context.ts&quot;
      ],
      &quot;testPathIgnorePatterns&quot;:[ &quot;&lt;rootDir&gt;/src/folder/Context.ts&quot;]
</code></pre>
<p>but it's not working. Please guide me here to proceed further.</p>
",https://stackoverflow.com/questions/63282629/unable-to-ignore-import-in-jest,"['jestjs', 'react-testing-library', 'ts-jest']",223,False,0,0
How to cover the missing branch from time delay condition in JUnit,"<p>would like to ask for help regarding unit testing my method which sets a time delay.  I was only able to cover the half of this method.  Here is the method</p>
<pre><code>public void setDelay() {
    XMLHandler objXMLHdl = new XMLHandler();
    
    String delay = objXMLHdl.GetXMLValue(&quot;myConfig.xml&quot;, &quot;/config/WS/delay&quot;);
    String intDelay = objXMLHdl.GetXMLValue(&quot;myConfig.xml&quot;, &quot;/config/WS/delay_minutes&quot;);
    
    if (delay.equals(&quot;1&quot;)) {
        try {
            TimeUnit.MINUTES.sleep(Integer.parseInt(intDelay));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code></pre>
<p>Here is the test</p>
<pre><code>public class WSGlobalFunctionsTest {

WSGlobalsFunctions globalFunction = new WSGlobalsFunctions();
XMLHandler objXMLHdl = new XMLHandler();



@Test
public void testSetDelay() { 
    globalFunction.setDelay();
}

@Test
public void testSetDelayFailed() throws NumberFormatException, InterruptedException, JAXBException {
    
    String delay = objXMLHdl.GetXMLValue(&quot;myConfig.xml&quot;, &quot;/config/WS/delay&quot;);
    String intDelay = objXMLHdl.GetXMLValue(&quot;myConfig.xml&quot;, &quot;/config/WS/delay_minutes&quot;);
    TimeUnit.MINUTES.sleep(Integer.parseInt(intDelay));
    globalFunction.setDelay();
    
}
</code></pre>
<p>Here is the XML file</p>
<pre><code>&lt;config&gt;
&lt;WS&gt;
    &lt;delay&gt;0&lt;/delay&gt;
    &lt;delay_minutes&gt;2&lt;/delay_minutes&gt;        
&lt;/WS&gt;
</code></pre>

<p>Any help would be greatly appreciated. T</p>
",https://stackoverflow.com/questions/62992217/how-to-cover-the-missing-branch-from-time-delay-condition-in-junit,"['java', 'xml', 'junit']",34,False,0,1
How to mock showDialog method,"<p>I'm unit testing a method calling in the second line this method of the material/dialog class:</p>
<pre><code>showDialog&lt;void&gt;(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
    ....
   )
</code></pre>
<p>I get this error in the unit test -&gt;
<code>'context != null': is not true</code>
because context is null.
How I can mock the context and inject into it ? or mock directly the method?</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/64007330/how-to-mock-showdialog-method,"['flutter', 'dart', 'mocking', 'dialog', 'mockito']",587,False,0,1
How to mock these types of query?,"<p>I'm new in unit testing . I've to test a public method which uses the following private method .</p>

<pre><code>     public void f1({some parameters}){
             List&lt;Vertex&gt; rVertex = fn(vertexId, graphTraversalSource,2);
            for (Vertex vertex : resultVertex) {
                if (checkingForAProperty(vertex.id().toString())) {
                     // some operations
                }
            }
         }


    private List&lt;Vertex&gt; fn(String v, GraphTraversalSource g, int i) {
        return g.V(v).repeat(in().dedup().simplePath()).until(loops().is(i)).toList();
      }
</code></pre>

<p>I thought of the following (terrible) approach (Assume g is mocked here ) :</p>

<pre><code>when (g.V(v)).then(X);
when (X.repeat(any)).then(Y);
when (Y.until(any)).then(Z);
</code></pre>

<p>But I could'nt decide how to do that . Any suggestions to do this will be really helpful.</p>
",https://stackoverflow.com/questions/61173638/how-to-mock-these-types-of-query,"['unit-testing', 'junit', 'mockito', 'gremlin']",356,True,0,1
Angular 11: Wrong Typecheck for UnitTest Spy on HttpClient.get(),"<p>When unit testing Angular's HttpClient.get(...) function, it seems that TypeScript cannot check types correctly when spying on HttpClient.get(...) with given responseType.</p>
<p>This error appeared after upgrading to Angular 11.</p>
<pre class=""lang-js prettyprint-override""><code>beforeEach(async () =&gt; {
  await TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    declarations: [AppComponent],
  }).compileComponents();
});

it('should check HttpClient.get()', () =&gt; {
  const http = TestBed.inject(HttpClient);
  const httpGetSpy = spyOn(http, 'get').and.returnValue(of('Test result.'));
  http.get('/test/url', { responseType: 'text' });
  
  expect(httpGetSpy).toHaveBeenCalledWith(
    '/test/url',
    { responseType: 'text'}
    // ^^^ Error:
    // &quot;Type '&quot;text&quot;' is not assignable to type '&quot;json&quot; | undefined'.
  );
});
</code></pre>
<p>Besides the simple reproducer above here is a more reasonable example as it appears in my production code:</p>
<pre class=""lang-js prettyprint-override""><code>// example.service.ts
@Injectable({ providedIn: 'root' })
export class ExampleService {
  constructor(private http: HttpClient) { }

  doSomething(): Observable&lt;any&gt; {
    return this.http.get('/some/url', { responseType: 'text' });
  }
}

// example.service.spec.ts
describe('ExampleService', () =&gt; {
  let service: ExampleService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule]
    });
    service = TestBed.inject(ExampleService);
  });

  it('should be created', () =&gt; {
    const http = TestBed.inject(HttpClient);
    const httpGetSpy = spyOn(http, 'get').and.returnValue(of('Test result.'));
    service.doSomething().subscribe();
    expect(httpGetSpy).toHaveBeenCalledWith('/some/url', { responseType: 'text' });
  });
});

</code></pre>
",https://stackoverflow.com/questions/65032969/angular-11-wrong-typecheck-for-unittest-spy-on-httpclient-get,"['angular', 'unit-testing', 'jasmine', 'angular-httpclient', 'angular11']",2943,True,0,1
Unit Testing IO Scala,"<p>I'm starting unit testing in scala using scalatest.
the method I'm testing is as follows :</p>

<pre><code> def readAlpha: IO[Float] = IO {
    val alpha = scala.io.StdIn.readFloat()
    alpha
  }
</code></pre>

<p>The test consists of limiting the float that the user inserts to two decimals
Here is what I've tried but that doesn't seem to work.
How could I be fixing it </p>

<pre><code>  ""alpha"" should "" have two decimal numbers after comma"" in {
    val alpha = readAlpha
    //assert(alpha == (f""$alpha%.2f""))
  }
</code></pre>
",https://stackoverflow.com/questions/61253471/unit-testing-io-scala,"['scala', 'unit-testing', 'scalatest']",1017,True,0,1
Microsoft C++ Native Test Fails Assert::AreSame even when values are the same,"<p>I'm running a test with microsoft native unit testing framework (that comes with vs2019) and it fails with this message: <code>Assert failed. Expected:&lt;1&gt; Actual:&lt;1&gt;</code></p>

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

<pre class=""lang-cpp prettyprint-override""><code>TEST_METHOD(memory_copy)
{
    int ref[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int src[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int dest[10];

    test::memory_copy&lt;int&gt;(src, dest, 10);

    for (unsigned int i = 0; i &lt; 10; i++)
    {
        Assert::AreSame(src[i], ref[i]);
        Assert::AreSame(dest[i], ref[i]);
    }
};
</code></pre>

<blockquote>
  <p>Note: <code>memory_copy&lt;&gt;()</code> copies memory from one pointer to another, just like <code>std::memcpy()</code></p>
</blockquote>

<p>Does anyone have an idea what may be the issue here?</p>
",https://stackoverflow.com/questions/60550339/microsoft-c-native-test-fails-assertaresame-even-when-values-are-the-same,"['c++', 'unit-testing']",208,True,0,2
Some featurePHP Fatal error: Cannot redeclare GuzzleHttp\uri_template(),"<p>I was trying to write unit testing using codeception in existing zend framework project. We are using s3 clients also for upload and download files. aws.phar file and codeception guzzlehttp getting conflicted, how could I avoid it?</p>

<p>When I run tests I got the following output
<a href=""https://i.stack.imgur.com/9Ca5q.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9Ca5q.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/59931579/some-featurephp-fatal-error-cannot-redeclare-guzzlehttp-uri-template,"['php', 'zend-framework2', 'codeception']",737,False,0,0
Mockito chain of method calls,"<pre><code>  @PostMapping(""/node{id}/delete"")
  public ResponseEntity&lt;CallbackResponse&gt; delete(@RequestParam(""eventId"") String eventId, @RequestParam(""id"") String nodeId) throws ResourceNotFoundException {

      serviceA.remove(eventId);
      client.getServiceB().deleteById(nodeId);
      return new ResponseEntity&lt;&gt;(new CallbackResponse(true), HttpStatus.OK);
  }
</code></pre>

<p>I am new to unit testing.
please help me in writing test cases for above rest controller method</p>

<p>I tried below test but it's not working</p>

<pre><code>    @Test
    public void testDeleteAgent() throws Exception{
        ServiceA serviceA = Mockito.mock(ServiceA.class);
        NodeClient client = Mockito.mock(NodeClient.class);

        Mockito.doNothing.when(serviceA).remove(Mockito.any());
        Mockito.doNothing.when(client.getServiceB()).deleteById(Mockito.any());
        ResponseEntity&lt;CallbackResponse&gt; result = agentController.delete(""123"", ""456"");
        Assert.assertEquals(HttpStatus.OK.value(), result.getStatusCode());
    }
</code></pre>

<p>when i run above test i am getting unfinished stubbing detected here error</p>

<p>I am created mock controller like this</p>

<pre><code>    private ServiceA serviceA = Mockit.mock(ServiceA.class);
    private NodeClient client = Mockit.mock(NodeClient.class);
    private AgentController agentController = new Controller(serviceA, client);
</code></pre>
",https://stackoverflow.com/questions/60110208/mockito-chain-of-method-calls,"['java', 'junit', 'mocking', 'mockito']",366,True,0,1
How do you make a thread-safe static property?,"<p>I have a CLR stored procedure defined in the below class. I am using property injection for MyObject but I'm not sure if it's thread-safe? Note: the CLR stored procedure needs to be static.</p>
<pre><code>public class MyClass
{
    private static IMyObject _myObj;
    public static IMyObject MyObject
    {
        get { return _myObj ?? new MyObject(); }
        set {_myObj = value; }
    }

    static MyClass()
    {
        _myObj = MyObject;
    }

    public static void My_Stored_Procedure()
    {
        _myObj.DoStuff();
    }
}
</code></pre>
<p>Mainly the reason for adding the static property is for unit testing.</p>
",https://stackoverflow.com/questions/62796267/how-do-you-make-a-thread-safe-static-property,"['c#', 'tsql', 'static', 'thread-safety', 'clr']",25,False,0,0
How to remove external dependencies from class,"<p>I have used many times some external dependency functions in my main cpp, I try to prepare my code for unit testing, so I would like to replace external dependencies with mock implementations, how will I convert those to mock implementations in my main cpp file?</p>
<pre><code>//ExternalDependencies.hpp
#include &lt;cstdint&gt;
#include &lt;set&gt;
#include &lt;unordered_set&gt;

namespace lab04{
namespace task_common{
namespace project{

uint32_t lab04::task_common::project::CalculateID(const uint32_t id)
{
    constexpr uint32_t temp= 0xFFF0;
    return id&amp; temp;
}

inline StreamType lab04::task_common::project::GetType(const uint32_t width) 
{
    switch (width)
    {
        case 1:
            Type = Type::Short;
            break;
        case 0:
            Type = Type::Long;
            break;
        default:
            THROW(ConfigErr, &quot;Eror!&quot;);
    }
    return Type;
}

uint32_t lab04::task_common::project::CalculateBS(const uint32_t Count, const uint32_t Size)
{
    return ((Count + 146) *(Size * 1676));
}

} 
}
} 
</code></pre>
",https://stackoverflow.com/questions/65075993/how-to-remove-external-dependencies-from-class,['c++'],138,False,0,1
How to set up &#39;supertest&#39; to test imported functions?,"<p>Unlike most of the tutorials on the Internet that use</p>

<pre class=""lang-js prettyprint-override""><code>app.post(""/login"", (req, res) =&gt; { ... });
</code></pre>

<p>I have set up routes like this</p>

<pre class=""lang-js prettyprint-override""><code>import * as LoginController from './controllers/login/login';

app.post(""/login"", LoginController.postLogin);
</code></pre>

<p>And in the <code>LoginController</code>, it's</p>

<pre class=""lang-js prettyprint-override""><code>export function postLogin(req, res) {
  ...
}
</code></pre>

<p>So, I wonder how I can do the unit testing for <code>postLogin(req, res)</code> using supertest without grabbing the <code>module.exports = app</code> from the <code>app.js</code>?</p>

<p>Is it possible to do something like</p>

<pre class=""lang-js prettyprint-override""><code>import request from ""supertest"";
import { postLogin } from ""./login""; // we're in src/controllers/login/login.test.js

describe(""POST Login"", () =&gt; {
    it(""should return 200 OK"", (done) =&gt; {
        request(postLogin)
            // some post data
            .expect(200, done);
    });
});

</code></pre>
",https://stackoverflow.com/questions/62371403/how-to-set-up-supertest-to-test-imported-functions,"['javascript', 'node.js', 'express', 'supertest']",390,False,0,1
can&#39;t able to mock a variable while testing,"<p>I am trying testing on node js I want to mock a variable outside of a function that is going to be unit tested.
for example</p>

<pre><code>const sample = [];
function uploadDoc {
sample.push('fileLocation')
}
function toSave(){
for (i=0;i&lt;sample.length;i++)
**some process read and access doc
}
</code></pre>

<p>I am facing issue while unit testing the second function
I have tried rewire npm that is also not working</p>
",https://stackoverflow.com/questions/62085317/cant-able-to-mock-a-variable-while-testing,"['node.js', 'testing', 'mocha.js', 'chai', 'sinon']",350,False,0,2
Why unit test fail with Optional return type?,"<p>Consider the following codes using Mockito (version 2.23.4) for unit testing. I have no idea why the test fail. If I change a.get(null) to a.get(2L) or any Long value, the test will pass. So why is null failing when anyLong() should work for null values?</p>
<pre><code>public class A {

    public Optional&lt;Long&gt; get(Long l) {
        return Optional.empty();
    }

    @Test
    public void test() {
        A a = Mockito.mock(A.class);
        Mockito.when(a.get(anyLong())).thenReturn(Optional.of(1L));
        Assert.assertTrue(a.get(null).isPresent());
    }

}
</code></pre>
",https://stackoverflow.com/questions/64478485/why-unit-test-fail-with-optional-return-type,"['java', 'mockito']",525,True,0,1
Errors such as: &#39;Solving environment: failed with initial frozen solve. Retrying with flexible solve&#39; &amp; &#39;unittest&#39; tab,"<p>I am working with spyder - python. I want to test my codes. I have followed the <code>pip install spyder-unittest</code> and <code>pip install pytest</code>. I have restarted the kernel and restarted my MAC as well. Yet, Unit Testing tab does not appear. Even when I drop down Run cannot find the Run Unit test. Does someone know how to do this? </p>
",https://stackoverflow.com/questions/60300787/errors-such-as-solving-environment-failed-with-initial-frozen-solve-retrying,"['tabs', 'spyder', 'python-unittest']",33884,True,6,2
Jenkins Pipeline - Laravel Unit Testing,"<p>I have started my laravel project, i'm trying to unit test my code and test db connectivity with jankins, this is my <strong>Jenkinsfile</strong> and how i configured it:</p>

<pre><code>pipeline {
    agent {
        dockerfile true
    }
    stages {
        stage(""Build"") {
            steps {
                sh 'php --version'
                sh 'composer install'
                sh 'composer --version'
                sh 'cp .env.example .env'
                sh 'php artisan key:generate'
            }
        }
        stage(""Unit test"") {
            steps {
                script {
                    docker.image('mysql:5.7').withRun('-e ""MYSQL_DATABASE=testing"" -e ""MYSQL_ROOT_PASSWORD=root""') { c -&gt;
                        docker.image('mysql:5').inside(""--link ${c.id}:db"") {
                            /* Wait until mysql service is up */
                            sh 'while ! mysqladmin ping -hdb --silent; do sleep 1; done'
                        }
                        sh ""./vendor/bin/phpunit""
                    }
                }
            }
        }
    }
}
</code></pre>

<p>The unit testing stage get error all the time and does not complete, why please ??</p>

<p><strong>All project configured by Docker.</strong></p>
",https://stackoverflow.com/questions/61467365/jenkins-pipeline-laravel-unit-testing,"['laravel', 'docker', 'jenkins', 'jenkins-pipeline', 'dockerfile']",2314,False,1,1
Importing Axe DevTools into iOS Unit Tests and UITests,"<p>When I import DevTools the app builds fine, but the unit tests give an error when building:</p>
<pre><code>Module compiled with Swift 5.1.2 cannot be imported by the Swift 5.2.4 compiler: 
....../Carthage/Build/iOS/Attest.framework/Modules/Attest.swiftmodule/x86_64-apple-ios-simulator.swiftmodule
</code></pre>
<p>If I only import it in our unit tests, then the unit tests build fine, but the app gives an error:</p>
<pre><code>Module compiled with Swift 5.1.2 cannot be imported by the Swift 5.2.4 compiler: 
......./Carthage/Build/iOS/Attest.framework/Modules/Attest.swiftmodule/x86_64-apple-ios-simulator.swiftmodule
</code></pre>
<p>Is manual testing and unit testing in the same build possible?</p>
",https://stackoverflow.com/questions/63379005/importing-axe-devtools-into-ios-unit-tests-and-uitests,"['ios', 'swift', 'axe', 'axedevtools']",88,True,1,1
How to unit test a component that has a ref prop,"<p>How do you unit test a component that has a ref prop ? i'm getting this error</p>

<blockquote>
  <p>● Should render  › should render </p>

<pre><code>TypeError: Cannot add property current, object is not extensible
</code></pre>
</blockquote>

<p>I looked at another question <a href=""https://stackoverflow.com/questions/39879176/unit-testing-react-component-ref"">Unit testing React component ref</a>, but there is no solution for that question.</p>

<p>this is the test </p>

<p><strong>CommentList.test.tsx</strong></p>

<pre><code>import ""@testing-library/jest-dom"";
import React from ""react"";
import { CommentListComponent as CommentList } from ""./CommentList"";
import { render, getByText, queryByText, getAllByTestId } from ""@testing-library/react"";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {},
    comments: [
        {
            author: { username: ""barnowl"", gravatar: ""https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png"", bio: null },
            comment_body: ""fsfsfsfsfs"",
            createdAt: ""2020-05-27T14:32:01.682Z"",
            gifUrl: """",
            id: 520,
            postId: 28,
            updatedAt: ""2020-05-27T14:32:01.682Z"",
            userId: 9,
        },
        {
            author: { username: ""barnowl"", gravatar: ""https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png"", bio: null },
            comment_body: ""fsfsfsfsfs"",
            createdAt: ""2020-05-27T14:32:01.682Z"",
            gifUrl: """",
            id: 519,
            postId: 27,
            updatedAt: ""2020-05-27T14:32:01.682Z"",
            userId: 10,
        },
    ],
    deleteComment: jest.fn(),
};
describe(""Should render &lt;CommentList/&gt;"", () =&gt; {
    it(""should render &lt;CommentList/&gt;"", () =&gt; {
        const commentList = render(&lt;CommentList {...props} /&gt;);
        expect(commentList).toBeTruthy();
    });
});
</code></pre>

<p>This is the component. </p>

<p><strong>CommentList.tsx</strong></p>

<pre><code>import React, { Fragment, useState, Ref } from ""react"";
import Grid from ""@material-ui/core/Grid"";
import OurSecondaryButton from ""../../../common/OurSecondaryButton"";
import CommentListContainer from ""../commentListContainer/commentListContainer"";

function CommentList(props: any, ref: Ref&lt;HTMLDivElement&gt;) {
    const [showMore, setShowMore] = useState&lt;Number&gt;(2);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState&lt;Boolean&gt;(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const min = Math.min(2, the_comments - inc);
    const showComments = (e) =&gt; {
        e.preventDefault();
        if (inc + 2 &amp;&amp; inc &lt;= the_comments) {
            setShowMore(inc + 2);
            setShowLessFlag(true);
        } else {
            setShowMore(the_comments);
        }
    };
    const handleClickOpen = () =&gt; {
        setOpenModal(true);
    };
    const handleCloseModal = () =&gt; {
        setOpenModal(false);
    };

    const showLessComments = (e) =&gt; {
        e.preventDefault();
        setShowMore(2);
        setShowLessFlag(false);
    };
    const isBold = (comment) =&gt; {
        return comment.userId === props.userId ? 800 : 400;
    };
    // show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
    const filterComments = props.comments
        .slice(0)
        .sort((a, b) =&gt; {
            const date1 = new Date(a.createdAt) as any;
            const date2 = new Date(b.createdAt) as any;
            return date2 - date1;
        })
        .slice(0, inc)
        .reverse();

    const showMoreComments = () =&gt; {
        return filterComments.map((comment, i) =&gt; (
            &lt;div key={i}&gt;
                &lt;CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} /&gt;
            &lt;/div&gt;
        ));
    };
    console.log(ref);
    return (
        &lt;Grid&gt;
            &lt;Fragment&gt;
                &lt;div data-testid=""comment-list-div"" style={{ margin: ""30px 0px"" }}&gt;
                    {props.comments.length &gt; 2 ? (
                        &lt;Fragment&gt;
                            {min !== -1 &amp;&amp; min !== -2 ? (
                                &lt;Fragment&gt;
                                    {min !== 0 ? (
                                        &lt;OurSecondaryButton onClick={(e) =&gt; showComments(e)} component=""span"" color=""secondary""&gt;
                                            View {min !== -1 &amp;&amp; min !== -2 ? min : 0} More Comments
                                        &lt;/OurSecondaryButton&gt;
                                    ) : (
                                        &lt;OurSecondaryButton onClick={(e) =&gt; showLessComments(e)} component=""span"" color=""secondary""&gt;
                                            Show Less Comments
                                        &lt;/OurSecondaryButton&gt;
                                    )}
                                &lt;/Fragment&gt;
                            ) : (
                                &lt;OurSecondaryButton onClick={(e) =&gt; showLessComments(e)} component=""span"" color=""secondary""&gt;
                                    Show Less Comments
                                &lt;/OurSecondaryButton&gt;
                            )}
                        &lt;/Fragment&gt;
                    ) : null}
                &lt;/div&gt;
            &lt;/Fragment&gt;
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                &lt;Fragment&gt;
                    {/* filter based on first comment  */}
                    {filterComments.map((comment, i) =&gt; (
                        &lt;div key={i}&gt;
                            &lt;CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} /&gt;
                        &lt;/div&gt;
                    ))}
                &lt;/Fragment&gt;
            )}
        &lt;/Grid&gt;
    );
}

export default React.forwardRef(CommentList) as React.RefForwardingComponent&lt;HTMLDivElement, any&gt;;
</code></pre>
",https://stackoverflow.com/questions/62069322/how-to-unit-test-a-component-that-has-a-ref-prop,"['reactjs', 'react-testing-library']",1796,False,1,1
How can I setup StaticResourceExtension when unit testing a markup extension that relies on it?,"<p>I have written a custom markup extension : <code>CoalesceResourceExtension</code></p>

<pre><code>[MarkupExtensionReturnType(typeof(object))]
public class CoalesceResourceExtension : MarkupExtension
{
    public CoalesceResourceExtension(string resources)
    {
        this.Resources = resources;
    }

    public string Separator { get; set; }

    [ConstructorArgument(""resources"")]
    public string Resources { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Resources != null)
        {
            foreach (string resourceName in Resources.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    if (new StaticResourceExtension(resourceName).ProvideValue(serviceProvider) is object resource)
                    {
                        return resource;
                    }
                }
                catch { }
            }
        }

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

<p>But when I come to unit testing <code>CoalesceResourceExtension</code>, I can't seem to find a way to setup the <code>StaticResourceExtension</code> so that it will find the desired mocked resources. Is there a way I can setup things for the <code>StaticResourceExtension</code> to find my mocked resources?</p>
",https://stackoverflow.com/questions/60211344/how-can-i-setup-staticresourceextension-when-unit-testing-a-markup-extension-tha,"['c#', 'wpf', 'unit-testing', 'moq', 'markup-extensions']",229,True,1,2
DELETE method in Spring boot using Mockito and JUnit,"<p>In Spring boot framework, I'm finding a difficulty with the controller Unit testing using JUnit and Mockito. I want to test this method. How to test DELETE Request method:</p>

<p>// delete application <strong>Controller class</strong></p>

<pre><code>    @DeleteMapping(""/all"")
fun deleteAllApplications(): ResponseEntity&lt;Void?&gt;? {
    applicationService.deleteAllApplications()
    return ResponseEntity(HttpStatus.OK)
}
</code></pre>

<p>// delete application <strong>Service class</strong></p>

<pre><code>    override fun deleteApplication(appID: String){

     applicationRepository.findById(appID).map { app  -&gt;
        applicationRepository.delete(app)
        ResponseEntity&lt;Void&gt;(HttpStatus.OK)
    }.orElse(ResponseEntity.notFound().build())


}
</code></pre>

<p>delete Application <strong>Full Test class</strong></p>

<pre class=""lang-kotlin prettyprint-override""><code>@RunWith(SpringJUnit4ClassRunner::class)
@SpringBootTest
class CartoApplicationTests {

    @InjectMocks
    var applicationService: ApplicationServiceImpl? = null

    @Mock
    var applicationRepository: ApplicationRepository? = null

@Test
fun deleteApplicationTest(){
    applicationService?.deleteApplication(appTest.id!!)
    when(applicationRepository?.delete(appTest)){}
}
}

</code></pre>

<p><strong>ERROR!</strong>
<a href=""https://i.stack.imgur.com/rr4pW.png"" rel=""nofollow noreferrer"">error message</a></p>

<p>Thanks for u help</p>
",https://stackoverflow.com/questions/61179128/delete-method-in-spring-boot-using-mockito-and-junit,"['mongodb', 'spring-boot', 'kotlin', 'junit', 'mockito']",267,False,0,0
Is is possible to represent a firestore Query as string,"<p>It is possible to represent a      <code>CollectionReference</code> as a string with the getter proprety <code>path</code> .
This is very handy for unit tests.
For example <code>admin.firestore().collection('cities').doc('LA').path</code> returns <code>&quot;cities/LA&quot;</code></p>
<p>What about <code>Query</code> represented as String ?</p>
<p>For example is there a way to something like this <code>admin.firestore().collection('cities').where('name','==','LA').toString()</code> to print something like this this: <code>&quot;cities/{where $name=='LA'}&quot;</code></p>
<p>This would be handy for unit testing</p>
",https://stackoverflow.com/questions/63339651/is-is-possible-to-represent-a-firestore-query-as-string,"['node.js', 'firebase', 'google-cloud-firestore']",365,False,2,1
Should Match Snapshot jest unit testing with Angular,"<p>Trying to do the Snapshot test with Jest in angular 10 and test application is failed</p>
<pre><code>expect(received).toMatchSnapshot()

    Snapshot name: `DestinationComponent Should Match Snapshot 1`

    - Snapshot  - 5
    + Received  + 5

    @@ -12,15 +12,15 @@
        formGroupDirective={[Function FormGroupDirective]}
        index=&quot;0&quot;
        listSvg={[Function Object]}
        loading={[Function Boolean]}
        ngForm={[Function ElementRef]}
    -   onCancelled={[Function EventEmitter]}
    -   onLoaded={[Function EventEmitter]}
    -   onServerError={[Function EventEmitter]}
    -   onSubmitted={[Function EventEmitter]}
    -   onValidationError={[Function EventEmitter]}
    +   onCancelled={[Function EventEmitter_]}
    +   onLoaded={[Function EventEmitter_]}
    +   onServerError={[Function EventEmitter_]}
    +   onSubmitted={[Function EventEmitter_]}
    +   onValidationError={[Function EventEmitter_]}
        prefilledActions={[Function Object]}
        router={[Function Router]}
        sessionMapApi={[Function Object]}
        sub={[Function Subscriber]}
        submitted=&quot;false&quot;

      73 | 
      74 |   it('Should Match Snapshot', async () =&gt; {
    &gt; 75 |     (expect(fixture) as any).toMatchSnapshot();
         |                              ^
      76 |   });
      77 | });
      78 | 

      at src/app/pages/destination/destination.component.spec.ts:75:30
      at node_modules/tslib/tslib.js:114:75
      at new ZoneAwarePromise (node_modules/zone.js/dist/zone.js:913:33)
      at Object.__awaiter (node_modules/tslib/tslib.js:110:16)
      at src/app/pages/destination/destination.component.spec.ts:74:42
      at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:386:30)
      at ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:117:43)
      at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:385:36)
      at Zone.run (node_modules/zone.js/dist/zone.js:143:47)
</code></pre>
<p><strong>date-selection.component.spec.ts</strong></p>
<pre><code>describe('DateSelectionComponent', () =&gt; {
  let component: DateSelectionComponent;
  let fixture: ComponentFixture&lt;DateSelectionComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [DateSelectionComponent, SafePipe],
      imports: [
        SharedModule,
        NgReduxTestingModule,
        RouterTestingModule.withRoutes([])
      ],
      providers: [
        {
          provide: PageAPIActions, useValue: { setPageState() { } }
        }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(DateSelectionComponent);
    component = fixture.componentInstance;
    Object.defineProperties(component, {
      page$: {
        value: of('value'),
        writable: true
      },
      page: {
        value: { destination: 'value' },
        writable: true
      },
      startDate: {
        value: new NgbDate(2019, 2, 27),
        writable: true
      },
      minDate: {
        value: new NgbDate(2019, 2, 27),
        writable: true
      }
    });
    fixture.detectChanges();
  });

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

  it('Should Match Snapshot', async () =&gt; {
    (expect(fixture) as any).toMatchSnapshot();
  });
});
</code></pre>
<p>I can see the .snap file is created, I am new to the jest unit testing, can anyone please help me what I am doing wrong, not able to find out the mistake</p>
",https://stackoverflow.com/questions/63887446/should-match-snapshot-jest-unit-testing-with-angular,"['javascript', 'angular', 'typescript', 'jestjs', 'angular-jest']",935,True,2,1
Unresolved External Symbol errors while using Catch2,"<p>I am trying to do Catch2 Unit Testing in Visual Studio. I have created a small test project to practice. When I try to compile this test project, I get a linker error. I am now trying to diagnose this linker error, but the <code>Catch2.hpp</code> header file contains thousands of lines of code. My hope is that someone who is more familiar with Catch2 or unit testing in general can diagnose what the issue is.</p>
<p>I will describe the process by which I created this project. I created a new project in a new solution. I have 4 files, all in the same directory, listed below.</p>
<p>The class I want to test:</p>
<pre><code>//a.h

#pragma once

class A {
    friend int A_Tester_Func1(A a);
public:
    A(int num) : my_num_(num) {
    }
private:
    int my_num_;
};

</code></pre>
<p>The test:</p>
<pre><code>//atester.cpp

#pragma once

#include &quot;catch.hpp&quot;
#include &quot;a.h&quot;

int A_Tester_Func1(A a) {
    return a.my_num_;
}

TEST_CASE(&quot;a contains a positive integer&quot;, &quot;[a]&quot;) {
    //...
    A a(3);
    REQUIRE(A_Tester_Func1(a) == 3);

}
</code></pre>
<p>The main function that runs the tests:</p>
<pre><code>//tester.cpp

#define CATCH_CONFIG_MAIN
#include &quot;catch.hpp&quot; // this should create the main function
</code></pre>
<p>The Catch2 Testing Framework:</p>
<pre><code>// catch.hpp

/*
 *  Catch v2.13.2
 *  Generated: 2020-10-07 11:32:53.302017
*/

//~17-18k lines of code that from Catch2

#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
</code></pre>
<p>When I try to compile this code in Visual Studio using the Local Windows Debugger button, I get a bunch of Unresolved External Symbol linker errors. I believe I read somewhere that Catch2 is &quot;partially compiled.&quot; That may have something to do with it, but I don't know. Following this guide (<a href=""https://stackoverflow.com/questions/59645381/best-practices-for-unit-testing-with-catch2-in-visual-studio"">StackOverflow: Best practices for Unit testing with Catch2 in Visual Studio</a>) has worked for me, but I'm trying to understand why the small example above is not successfully linking.</p>
<p>I have included the linker errors below for completeness, although I feel that they will probably not be necessary for the question.</p>
<pre><code>1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: __thiscall Catch::StringRef::StringRef(char const *)&quot; (??0StringRef@Catch@@QAE@PBD@Z) referenced in function &quot;public: class Catch::BinaryExpr&lt;int const &amp;,int const &amp;&gt; const __thiscall Catch::ExprLhs&lt;int const &amp;&gt;::operator==&lt;int&gt;(int const &amp;)&quot; (??$?8H@?$ExprLhs@ABH@Catch@@QAE?BV?$BinaryExpr@ABHABH@1@ABH@Z)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;struct Catch::ITestInvoker * __cdecl Catch::makeTestInvoker(void (__cdecl*)(void))&quot; (?makeTestInvoker@Catch@@YAPAUITestInvoker@1@P6AXXZ@Z) referenced in function &quot;void __cdecl `anonymous namespace'::`dynamic initializer for 'autoRegistrar1''(void)&quot; (??__EautoRegistrar1@?A0xf9ca9c7d@@YAXXZ)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: __thiscall Catch::NameAndTags::NameAndTags(class Catch::StringRef const &amp;,class Catch::StringRef const &amp;)&quot; (??0NameAndTags@Catch@@QAE@ABVStringRef@1@0@Z) referenced in function &quot;void __cdecl `anonymous namespace'::`dynamic initializer for 'autoRegistrar1''(void)&quot; (??__EautoRegistrar1@?A0xf9ca9c7d@@YAXXZ)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: __thiscall Catch::AutoReg::AutoReg(struct Catch::ITestInvoker *,struct Catch::SourceLineInfo const &amp;,class Catch::StringRef const &amp;,struct Catch::NameAndTags const &amp;)&quot; (??0AutoReg@Catch@@QAE@PAUITestInvoker@1@ABUSourceLineInfo@1@ABVStringRef@1@ABUNameAndTags@1@@Z) referenced in function &quot;void __cdecl `anonymous namespace'::`dynamic initializer for 'autoRegistrar1''(void)&quot; (??__EautoRegistrar1@?A0xf9ca9c7d@@YAXXZ)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: virtual __thiscall Catch::AutoReg::~AutoReg(void)&quot; (??1AutoReg@Catch@@UAE@XZ) referenced in function &quot;void __cdecl `anonymous namespace'::`dynamic atexit destructor for 'autoRegistrar1''(void)&quot; (??__FautoRegistrar1@?A0xf9ca9c7d@@YAXXZ)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: static class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; __cdecl Catch::StringMaker&lt;int,void&gt;::convert(int)&quot; (?convert@?$StringMaker@HX@Catch@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) referenced in function &quot;class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; __cdecl Catch::Detail::stringify&lt;int&gt;(int const &amp;)&quot; (??$stringify@H@Detail@Catch@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABH@Z)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: virtual __thiscall Catch::ITransientExpression::~ITransientExpression(void)&quot; (??1ITransientExpression@Catch@@UAE@XZ) referenced in function &quot;public: virtual __thiscall Catch::BinaryExpr&lt;int const &amp;,int const &amp;&gt;::~BinaryExpr&lt;int const &amp;,int const &amp;&gt;(void)&quot; (??1?$BinaryExpr@ABHABH@Catch@@UAE@XZ)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;void __cdecl Catch::formatReconstructedExpression(class std::basic_ostream&lt;char,struct std::char_traits&lt;char&gt; &gt; &amp;,class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;,class Catch::StringRef,class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;)&quot; (?formatReconstructedExpression@Catch@@YAXAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@3@VStringRef@1@1@Z) referenced in function &quot;private: virtual void __thiscall Catch::BinaryExpr&lt;int const &amp;,int const &amp;&gt;::streamReconstructedExpression(class std::basic_ostream&lt;char,struct std::char_traits&lt;char&gt; &gt; &amp;)const &quot; (?streamReconstructedExpression@?$BinaryExpr@ABHABH@Catch@@EBEXAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@@Z)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: __thiscall Catch::AssertionHandler::AssertionHandler(class Catch::StringRef const &amp;,struct Catch::SourceLineInfo const &amp;,class Catch::StringRef,enum Catch::ResultDisposition::Flags)&quot; (??0AssertionHandler@Catch@@QAE@ABVStringRef@1@ABUSourceLineInfo@1@V21@W4Flags@ResultDisposition@1@@Z) referenced in function &quot;void __cdecl ____C_A_T_C_H____T_E_S_T____0(void)&quot; (?____C_A_T_C_H____T_E_S_T____0@@YAXXZ)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: void __thiscall Catch::AssertionHandler::handleExpr(struct Catch::ITransientExpression const &amp;)&quot; (?handleExpr@AssertionHandler@Catch@@QAEXABUITransientExpression@2@@Z) referenced in function &quot;void __cdecl ____C_A_T_C_H____T_E_S_T____0(void)&quot; (?____C_A_T_C_H____T_E_S_T____0@@YAXXZ)
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: void __thiscall Catch::AssertionHandler::handleUnexpectedInflightException(void)&quot; (?handleUnexpectedInflightException@AssertionHandler@Catch@@QAEXXZ) referenced in function __catch$?____C_A_T_C_H____T_E_S_T____0@@YAXXZ$0
1&gt;atester.obj : error LNK2019: unresolved external symbol &quot;public: void __thiscall Catch::AssertionHandler::complete(void)&quot; (?complete@AssertionHandler@Catch@@QAEXXZ) referenced in function __catch$?____C_A_T_C_H____T_E_S_T____0@@YAXXZ$0
1&gt;MSVCRTD.lib(exe_main.obj) : error LNK2019: unresolved external symbol _main referenced in function &quot;int __cdecl invoke_main(void)&quot; (?invoke_main@@YAHXZ)
</code></pre>
<p>What is causing these errors? How do I fix these errors while keeping <code>catch.hpp</code> in the same project as my source files?</p>
",https://stackoverflow.com/questions/64459095/unresolved-external-symbol-errors-while-using-catch2,"['c++', 'visual-studio', 'unit-testing', 'linker-errors', 'catch2']",2212,True,4,3
Node.js - Is it a good practice to export all files in index.js for each directory?,"<pre class=""lang-js prettyprint-override""><code>// configs/index.js
module.exports = {
  AppConfig: require('./app-config'),
  AuthConfig: require('./auth-config'),
  DbConfig: require('./database-config'),
};

// controllers/some-controller.js
const { AppConfig } = require('../configs');

// tests/some-test.spec.js
// it fails because the controller require() the root index.js and it runs all exported files implicitly.
const SomeController = require('../controllers/some-controller');
</code></pre>

<p>The above example works well in development, but it fails in unit testing using <code>mocha</code> because it runs all exported files implicitly. My workaround is to import the file directly like this <code>require('../configs/app-config')</code>. <strong>What is your preferred solution? Should I export all files at all? Is it a good practice?</strong></p>
",https://stackoverflow.com/questions/62428663/node-js-is-it-a-good-practice-to-export-all-files-in-index-js-for-each-directo,['node.js'],60,True,0,1
Percentage widths don&#39;t work in react testing,"<p>Unit testing in react doesn't seem to regard percentage widths. I encountered this problem testing a more complex component and reproduced it in a simpler scenario.
I ran the below tests differently.</p>

<pre><code>let div: HTMLElement = null
beforeEach(() =&gt; {
   div = document.createElement('div');
   document.body.appendChild(div);
})


//Test 1
it('testing widths', async () =&gt; {
        act(() =&gt; {
            render(&lt;div id=""big"" style={{ width: ""100px"" }}&gt;&lt;div id=""small"" style={{ width: ""100%"" }}&gt;&lt;/div&gt;&lt;/div&gt;, div);
        })

        expect($(""#big"").width()).toBe(100) //passes
        expect($(""#stup"").width()).toBe(100) //fails (recieved - 0)
    });


//Test 2
it('testing widths', async () =&gt; {
        act(() =&gt; {
            render(&lt;div id=""big"" style={{ width: ""100px"" }}&gt;&lt;div id=""small"" style={{ width: ""100px"" }}&gt;&lt;/div&gt;&lt;/div&gt;, div);
        })

        expect($(""#big"").width()).toBe(100) //passes
        expect($(""#stup"").width()).toBe(100) //passes
    });


//Test 3
it('testing widths', async () =&gt; {
        act(() =&gt; {
            render(&lt;div id=""big"" style={{ width: ""100px"" }}&gt;&lt;div id=""small""&gt;&lt;/div&gt;&lt;/div&gt;, div);
        })

        $(""#small"").width(""100%"")
        expect($(""#big"").width()).toBe(100) //passes
        expect($(""#small"").width()).toBe(100) //fails (recieved - 0)
    });


//Test 4
it('testing widths', async () =&gt; {
        act(() =&gt; {
            render(&lt;div id=""big"" style={{ width: ""100px"" }}&gt;&lt;div id=""small""&gt;&lt;/div&gt;&lt;/div&gt;, div);
        })

        $(""#small"").width(""100"")
        expect($(""#big"").width()).toBe(100) //passes
        expect($(""#small"").width()).toBe(100) //passes
    });
</code></pre>

<p>And for some reason, this fails too (100 instead of 100px)</p>

<pre><code>it('testing widths', async () =&gt; {
        act(() =&gt; {
            render(&lt;div id=""big"" style={{ width: ""100"" }}&gt;&lt;div id=""small"" style={{ width: ""100"" }}&gt;&lt;/div&gt;&lt;/div&gt;, div);
        })

        expect($(""#big"").width()).toBe(100) //fails (recieved - 0)
        expect($(""#small"").width()).toBe(100) //fails (recieved - 0)
    });
</code></pre>

<p>How can I fix this?</p>
",https://stackoverflow.com/questions/61444234/percentage-widths-dont-work-in-react-testing,"['reactjs', 'unit-testing', 'width']",142,False,0,0
How to test for label of a field from translate service using jasmine,"<p>I am new to unit testing of angular code using jasmine. I am trying to test the label of a field , which is got from translate service in HTML file.
I have used the below code, but i am getting error &quot;Failed: Cannot read property 'textContent' of null&quot;</p>
<pre><code>it('label should be Enter your mobile number', async(() =&gt; {
     const de = fixture.debugElement;
     expect(fixture.debugElement.nativeElement.querySelector('[id=textFormat] label').textContent).toEqual('ENTER_YOUR_MOBILE_NUMBER'); 
     translate.setTranslation('en', { ENTER_YOUR_MOBILE_NUMBER : 'Enter your mobile number' });
    translate.use('en');
    fixture.detectChanges();
    expect(fixture.debugElement.nativeElement.querySelector('[id=textFormat] label').textContent).toEqual('Enter your mobile number'); 
       }));


HTML :

&lt;div class=&quot;form-group&quot; id=&quot;email&quot;&gt;
        &lt;label for=&quot;mobileNumber&quot; class=&quot;col-form-label col-form-label-lg&quot; id=&quot;textFormat&quot;&gt;
            {{ 'ENTER_YOUR_MOBILE_NUMBER' | translate }}&amp;nbsp;&lt;span class=&quot;labelHint&quot; id=&quot;numbFormat&quot;&gt;(05XXXXXXXX)&lt;/span&gt;
        &lt;/label&gt;
       
    &lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/63131720/how-to-test-for-label-of-a-field-from-translate-service-using-jasmine,"['jasmine', 'ngx-translate']",277,False,0,1
Unit testing an array converted set,"<p>I have an array. I am required to convert it into set and then unit test. I successfully did the array to set conversation. But the unit test is not working. I am a new learner specially in unit testing. Please help.</p>
<pre><code>public class ArrToSet {

    public static void main(String[] args) {
        String[] array = {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;};
        System.out.println(&quot;Original Array: &quot; + Arrays.toString(array));
    
        System.out.println(&quot;Array converted to Set: &quot; + Arrays.stream(array).collect(Collectors.toSet()));
    
    }
}
</code></pre>
<p>The unit test case I have written:</p>
<pre><code>class ArrToSetTest {
    @Test
    void test() {

        ArrToSet ar = new ArrToSet();
    
         Set&lt;String&gt; set = new HashSet&lt;&gt;();
            set.add(&quot;a&quot;);
            set.add(&quot;b&quot;);
            set.add(&quot;c&quot;);

        String actual[] = {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;};
    
        assertEquals(set,actual);
   }
}
</code></pre>
",https://stackoverflow.com/questions/63019542/unit-testing-an-array-converted-set,['java'],477,True,-2,1
angular5 unit testing jasmine+karma,"<p>I have a simple method that i want to test:</p>
<p>ts file:</p>
<pre><code>policyOptions(event): void {
    this.selectedPolicy = event.srcElement[&quot;value&quot;];
    this.detectFormValueChanges();
  }
</code></pre>
<p>spec file, what i wrote:</p>
<pre><code>it(&quot;policyOptions function test case&quot;, () =&gt; {
    const mockSelectedPolicy = {&quot;value&quot;: &quot;DEFAULT&quot;};
    component.policyOptions(mockSelectedPolicy);
    component.detectFormValueChanges();
  });
</code></pre>
<p>html code:</p>
<pre><code>    &lt;input id=&quot;enable&quot; (change)=&quot;policyOptions($event)&quot; type=&quot;radio&quot; value=&quot;ENABLED&quot; name=&quot;antiPhishingSelectPolicy&quot; class=&quot;radio__input&quot; [checked]=&quot;selectedPolicy==='ENABLED'&quot;&gt;
</code></pre>
<p>I am getting error: <code>&quot;value is undefined&quot;</code>. What am i doing wrong? how can i resolve it?</p>
<p>I am new to angular, so i am finding unit testing difficult to overcome. Please help.</p>
",https://stackoverflow.com/questions/62750156/angular5-unit-testing-jasminekarma,"['angular', 'unit-testing', 'karma-jasmine']",95,True,0,1
How do define certain tests on certain branches?,"<p>I am new to gitlab ci/cd. i like how it works. I would like to run certain tests in certain branches. how can i define the same in yml file?</p>
<p>I am using gitlab ci/cd for R package development and using testthat package for unit-testing.</p>
",https://stackoverflow.com/questions/65236127/how-do-define-certain-tests-on-certain-branches,"['r', 'unit-testing', 'yaml', 'gitlab-ci', 'testthat']",98,True,-1,1
HOW DO TESTING ANGULAR - catchError operator &#39;rxjs&#39;,"<p><a href=""https://i.stack.imgur.com/RDsyi.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RDsyi.png"" alt=""enter image description here"" /></a></p>
<p>can you please help me to test the code. I have not been able to test the catchError operator that is inside the pipe of the observable interval (1000) ...</p>
<p>I don't know much unit testing in angular for observables of an inteval (1000). I need to simulate the execution of an interval, and simulate the error. I did not do the code, the code was already done, I am a new employee and I was assigned the task of doing unit testing. I don't know if it is necessary to catchError on an interval.</p>
<p>My file ts is:</p>
<pre><code>import { Injectable, EventEmitter } from '@angular/core';
import {Subscription, Observable, interval, BehaviorSubject, throwError} from 'rxjs';
import {take, map, catchError, finalize} from 'rxjs/operators';
import { environment } from 'environments/environment';

/**
 * @Class CounterSessionProvider
 * @description This class is a provider for control session time
 * @author Andres Giraldo Londoño, Pragma S.A.
 */
@Injectable({
  providedIn: 'root',
})
export class CounterSessionProvider {
  // 4 minutes
  public inactivityTime = 20; // environment.inactivityTime; // environment.inactivityTime -&gt; 20 seconds
  counterStateEmitter = new EventEmitter();
  currentSubscription: Subscription;
  public substracCounter$: BehaviorSubject&lt;boolean&gt;;

  constructor() {
    this.substracCounter$ = new BehaviorSubject(false);
  }

  public start() {
    this.currentSubscription = this.initInterval().subscribe();
  }

  public initInterval(): Observable&lt;number&gt; {
    return interval(1000).pipe(
      take(this.inactivityTime),
      map((index: number) =&gt; this.inactivityTime - (index + 1)),
      catchError(err =&gt; {
        this.counterStateEmitter.error(err);
        return throwError(err);
      })
    );
  }

  public restarCounterTime(): void {
    this.substracCounter$.next(true);
  }

  public stop() {
    if (this.currentSubscription) {
      this.currentSubscription.unsubscribe();
    }
    this.counterStateEmitter.emit('ABORTED');
  }
}
</code></pre>
<p>My file spec.ts is:</p>
<pre><code>import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import { CounterSessionProvider } from './counter-session.provider';
import {interval, Observable, Subscription, throwError} from 'rxjs';
import {catchError, take} from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';

describe('CounterSessionProvider', () =&gt; {
  let counterSessionProvider: CounterSessionProvider;
  let scheduler: TestScheduler;

  beforeEach(() =&gt; {
    counterSessionProvider = new CounterSessionProvider();
  });

  /*beforeEach(() =&gt; {
    scheduler = new TestScheduler((actual, expected) =&gt; {
      expect(actual).toEqual(expected);
    });
  });*/

  /*it('should throw error when initInterval interval', fakeAsync(() =&gt; {
    scheduler.run(helpers =&gt; {
      spyOn(counterSessionProvider, 'initInterval').and.returnValue(throwError('ERROR'));
      const actions$ = helpers.hot('--a', { a: 1000 });
      const completion$ = helpers.cold('--c', { c: 1000 });
      expect(counterSessionProvider.initInterval).toBe(completion$);
    });
  }));*/

  it('should initialize currentSubscription from interval', fakeAsync(() =&gt; {
    let currentVal = null;
    const numberObservable = counterSessionProvider.initInterval();
    counterSessionProvider.currentSubscription = numberObservable.subscribe((value: number) =&gt; {
      currentVal = value;
    });
    tick(1000);
    expect(currentVal).toEqual(19);
    counterSessionProvider.currentSubscription.unsubscribe();
  }));

  it('should emit a String COMPLETE when start() is called', () =&gt; {
    spyOn(counterSessionProvider, 'start');
    counterSessionProvider.start();
    counterSessionProvider.counterStateEmitter.subscribe(value =&gt; {
      expect(value).toEqual('COMPLETE');
    });
    expect(counterSessionProvider.start).toHaveBeenCalled();
  });

  it('should call stop()', () =&gt; {
    spyOn(counterSessionProvider, 'stop');
    counterSessionProvider.currentSubscription = new Subscription();
    counterSessionProvider.stop();
    counterSessionProvider.counterStateEmitter.subscribe((value: string) =&gt; {
      expect(value).toEqual('ABORTED');
    });
    expect(counterSessionProvider.stop).toHaveBeenCalled();
  });

  it('should call method start and initilize currentSubscription', fakeAsync(() =&gt; {
    counterSessionProvider.start();
    tick(1000);
    counterSessionProvider.currentSubscription.unsubscribe();
    expect(counterSessionProvider.currentSubscription).not.toBeNull();
  }));

  it('should call restarCounterTime() and emit a TRUE', () =&gt; {
    counterSessionProvider.restarCounterTime();
    counterSessionProvider.substracCounter$.subscribe(value =&gt; expect(value).toBeTruthy());
  });

  it('should call method stop and emit ABORTED', fakeAsync(() =&gt; {
    counterSessionProvider.start();
    tick(1000);
    counterSessionProvider.stop();
  }));

  /*beforeEach(() =&gt; {
    counterSessionProvider = TestBed.get(CounterSessionProvider);
  });

  it('should be created', () =&gt; {
    expect(counterSessionProvider).toBeTruthy();
  });

  it('should return ABORTED when stop function is called', () =&gt; {
    counterSessionProvider.start();
    counterSessionProvider.counterState.subscribe((msg: string) =&gt; {
      expect(msg).toEqual('ABORTED');
    });
    counterSessionProvider.stop();
  });*/
});
</code></pre>
<p>But I need to cover all the code of your coverage. In the following image I show the coverage that I need.</p>
<p>Trying to apply the suggestions that Shashank Vivek gave me, it gives these results:</p>
<p><a href=""https://i.stack.imgur.com/l0VXO.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/l0VXO.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63550143/how-do-testing-angular-catcherror-operator-rxjs,"['angular', 'typescript', 'unit-testing', 'rxjs', 'karma-jasmine']",12042,True,1,1
Unit Test - Leafletjs Add Layer / Remove Layer,"<p>I am looking to create unit tests for the component below to check addLayer and removeLayer being called,</p>
<pre><code>function App (()=&gt;{
    const marker = useRef&lt;L.Marker | undefined&gt;( undefined);
    const fg : L.FeatureGroup&lt;any&gt; = fg(); 
    
    useEffect(()=&gt;{
    var myIcon = L.divIcon({className:'my-div-icon',html:renderToStaticMarkup(&lt;ArrowRight/&gt;)});
    marker.current = L.marker([50.5, 30.5], {icon:myIcon});
     if(fg) fg.addLayer(marker.current);
      &lt;div&gt;Text&lt;/div&gt;;
    
     return (){
    if(marker.current &amp;&amp; fg)
    {fg.removeLayer(marker.current);}
   
    } 
    },[fg]);
    
    });
</code></pre>
<p>RTL test:</p>
<pre><code>const mockAddLayer = jest.fn();
describe(&quot;Test Leaflet methods&quot;,()=&gt;{
it(&quot;Test add Layer&quot;,()=&gt;{
const {wrapper} = render (&lt;App/&gt;);
expect(wrapper.getByText('Text')).toBeTruthy();
expect(mockAddLayer).toBeCalled();
});
});
</code></pre>
<p>The above test is failing with</p>
<pre><code>expect(jest.fn()).toBeCalled()
expected number of calls:  &gt;= 1
received number of calls: 0
</code></pre>
<p>Is it possible to test fg.addLayer() and fg.removeLayer() are being called?
I am a beginner in unit testing with leafletjs. Any leads are appreciated.</p>
",https://stackoverflow.com/questions/64472730/unit-test-leafletjs-add-layer-remove-layer,"['javascript', 'unit-testing', 'jestjs', 'leaflet', 'react-testing-library']",138,False,1,0
pyspark init super class warning,"<p>I have created a class for Unit testing in pyCharm of my pySpark program.</p>

<pre><code>class TableLiteral(unittest.TestCase):
   def __init__(self, table_value):
      self.table_value = [x.strip().strip(""|"") for x in table_value.split(""\n"") if x.strip() != '']
      # The above code is as part of my development
</code></pre>

<p>Now, my only concern is the <em>__init_</em> is highlighting a warning call to <strong><em>__init_</em> of super class is missed</strong>. Could you please update where I have to update as I'm new to python class.</p>
",https://stackoverflow.com/questions/60339477/pyspark-init-super-class-warning,"['python', 'pyspark', 'superclass']",182,False,0,1
Could not find a parameterless constructor,"<p>i'm new to unit testing and Moq. I wrote 4 tests who all throw the same exception and i think i need to add these parameters CombatHelperContext, IMapper when mocking the CharacterRepository but how do i do that?</p>

<p>My goal is to test crud functionality, views and more.</p>

<pre><code>public class CharacterTests
{
    [Fact]
    public async Task GetAll_ReturnsAViewResult_WithAListOfCharacters()
    {
        // Arrange
        var mockRepo = new Mock&lt;CharacterRepository&gt;();
        mockRepo.Setup(repo =&gt; repo.GetAll())
        .Returns(GetTestCharacters());
        var controller = new CharacterController(mockRepo.Object);

        // Act
        var result = await controller.Get();

        // Assert
        var viewResult = Assert.IsType&lt;ViewResult&gt;(result);
        var model = Assert.IsAssignableFrom&lt;List&lt;CharacterDto&gt;&gt;(
            viewResult.ViewData.Model);

        Assert.Equal(4, model.Count());
    }

    [Fact]
    public async Task Delete_Character()
    {
        // Arrange
        var mockRepo = new Mock&lt;CharacterRepository&gt;();
        mockRepo.Setup(repo =&gt; repo.Delete(1));

        var controller = new CharacterController(mockRepo.Object);
        var characters = GetTestCharacters();

        // Act
        var result = await controller.Get();

        // Assert
        Assert.Null(characters.Where(c =&gt; c.Id == 1));
    }

    [Fact]
    public async Task Post_NewCharacter_ReturnsInViewResult()
    {
        // Arrange
        CharacterDto newCharacterDto = new CharacterDto();
        newCharacterDto.Id = 5;

        var mockRepo = new Mock&lt;CharacterRepository&gt;();
        mockRepo.Setup(repo =&gt; repo.Add(newCharacterDto));

        var controller = new CharacterController(mockRepo.Object);
        var characters = GetTestCharacters();

        // Act
        var result = await controller.Get();

        // Assert
        var viewResult = Assert.IsType&lt;ViewResult&gt;(result);
        var model = Assert.IsAssignableFrom&lt;List&lt;CharacterDto&gt;&gt;(
            viewResult.ViewData.Model);

        Assert.Equal(5, model.Count());
    }

    [Fact]
    public async Task Update_Character()
    {
        // Arrange
        var mockRepo = new Mock&lt;CharacterRepository&gt;();
        var characters = GetTestCharacters();
        CharacterDto characterToUpdate = characters.FirstOrDefault(c =&gt; c.Name == ""Zero Two"");
        var controller = new CharacterController(mockRepo.Object);

        // Act
        var result = await controller.Get();
        characterToUpdate.Name = ""Zero Three"";
        mockRepo.Setup(repo =&gt; repo.Update(characterToUpdate));

        // Assert
        Assert.NotNull(characters.FirstOrDefault(c =&gt; c.Name == ""Zero Three""));
    }


    private IQueryable&lt;CharacterDto&gt; GetTestCharacters()
    {
        var characters = new List&lt;CharacterDto&gt;();
        characters.Add(new CharacterDto()
        {
            Id = 1,
            Name = ""Zero Two""
        });
        characters.Add(
            new CharacterDto
            {
                Id = 2,
                Name = ""Ander""
            });
        characters.Add(
            new CharacterDto
            {
                Id = 3,
                Name = ""Jingles""
            });
        characters.Add(new CharacterDto
        {
            Id = 4,
            Name = ""Arthas Menethil""
        });
        var queryableCharacters = characters.AsQueryable();
        return queryableCharacters;
    }
}
</code></pre>

<p>This the Repository i'm mocking </p>

<pre><code>public class CharacterRepository : MappingRepository&lt;Character, CharacterDto&gt;
{
    public CharacterRepository(CombatHelperContext combatHelperContext, IMapper mapper) : base(combatHelperContext, mapper)
    {
    }
}
</code></pre>
",https://stackoverflow.com/questions/62052476/could-not-find-a-parameterless-constructor,"['c#', 'unit-testing', 'testing', 'moq', 'xunit']",2298,True,3,1
How to write Transactional Unit Tests for Transactional Methods in Spring?,"<p>The Unit-Test Classes I have in my Project extend an <code>AbstractUnitTest</code> class which is <code>@Transactional</code>. The tests in these classes are running on some methods which themselves are <code>@Transactional</code>.</p>

<p>Whenever these methods bring tested fail, instead of rolling back, the Transactions are partially persisted (<em>in the Testing Environment, ordinarily they behave atomically</em>). 
This is preventing me from testing Transactional behavior of my  Project Modules. </p>

<p><em>More specifically</em>, I have a Unit-Test for an <code>addList()</code> method. However, on encountering an Exception, during unit-testing, the input list is partially added and not rolled back <em>since</em>, the test is itself running in a Transaction(by virtue of <code>AbstractUnitTest</code> being Transactional)</p>

<p>On removing the <code>@Transactional</code> from <code>AbstractUnitTest</code>, the tests work fine.
What is the reason for this behavior and <strong>how can you perform unit-testing of Transactional methods if the Unit Test class itself is Transactional?</strong></p>
",https://stackoverflow.com/questions/59577563/how-to-write-transactional-unit-tests-for-transactional-methods-in-spring,"['java', 'spring', 'transactions']",939,True,1,1
query selector value is not getting in jasmine unit testing angular,"<p>I have two input fields like below</p>
<pre><code>&lt;input type=&quot;number&quot; [value]=&quot;celsius&quot; class=&quot;large&quot; data-test-id=&quot;celsius-input&quot; (keyup)=&quot;getCelsius($event)&quot;&gt;

&lt;input type=&quot;number&quot; [value]=&quot;fahren&quot; class=&quot;large&quot; (keyup)=&quot;getFahren($event)&quot; data-test-id=&quot;fahrenheit-input&quot;/&gt;
  
</code></pre>
<p>now I'm trying testing this using jasmine unit testing. for this I have written code like below</p>
<pre><code>let component: TemperatureConverter;
  let fixture: ComponentFixture&lt;TemperatureConverter&gt;;
  let compiled;
  let celsiusInput;
  let fahrenheitInput;

  const pushCelsiusValue = async (value) =&gt; {
    celsiusInput.value = value;
    celsiusInput.dispatchEvent(new Event('change'));
    celsiusInput.dispatchEvent(new Event('input'));
    await fixture.whenStable();
    await fixture.detectChanges();
  };

  const pushFahrenheitValue = async (value) =&gt; {
    fahrenheitInput.value = value;
    fahrenheitInput.dispatchEvent(new Event('change'));
    fahrenheitInput.dispatchEvent(new Event('input'));
    await fixture.whenStable();
    await fixture.detectChanges();
  }

  const getByTestId = (testId: string) =&gt; {
    return compiled.querySelector(`[data-test-id=&quot;${testId}&quot;]`);
  };

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TemperatureConverter);
    fixture.autoDetectChanges(true);
    compiled = fixture.debugElement.nativeElement;
    component = fixture.componentInstance;
    celsiusInput = getByTestId('celsius-input');
    fahrenheitInput = getByTestId('fahrenheit-input');
    fixture.detectChanges();
  });

  it('Typing value in Celsius field gets correct Fahrenheit value', async() =&gt; {
    await pushCelsiusValue(500);
    fahrenheitInput = getByTestId('fahrenheit-input');
    expect(Number(fahrenheitInput.value)).toEqual(932);
  });
</code></pre>
<p>but I'm not able to get any value  <code>fahrenheitInput = getByTestId('fahrenheit-input');</code> and I'm not to match anything in     <code>expect(Number(fahrenheitInput.value)).toEqual(932);</code></p>
<p>I'm not able to figure out what is the error.</p>
",https://stackoverflow.com/questions/63856377/query-selector-value-is-not-getting-in-jasmine-unit-testing-angular,"['angular', 'unit-testing', 'jasmine']",1605,False,0,1
"MockMvc response returns 404, expected response 201","<p>I am new to unit testing REST API in Spring Boot.</p>
<p>I am expecting response status as CREATED but instead I am getting a PAGE NOT FOUND error.</p>
<p>Below is the code for:-</p>
<p><strong>UserControllerUnitTests</strong></p>
<pre><code>@SpringBootTest
@ContextConfiguration(classes = { CommonConfig.class, SecurityConfig.class})
@RunWith(SpringRunner.class)
class UserControllerUnitTests {

    private static ObjectMapper mapper;
    private static final String URI = &quot;/users&quot;;

    MockMvc mvc;

    @Autowired
    WebApplicationContext webAppContext;

    @Mock
    UserService userService;

    MvcResult mvcResult;

    @BeforeAll
    static void setUp() {
        mapper = new ObjectMapper();
    }

    @BeforeEach
    void initialize() throws Exception {
        mvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
    ....
    ....
    ....
   
    void shouldReturnStatusCreatedIfValidUserPassedForPostUser(long index) throws Exception {
        int expectedStatus = HttpStatus.CREATED.value();
        UserDAO returnUser;
    
        UserDAO user = userList.get(index);
        userList.remove(index);
        String jsonContent = mapper.writeValueAsString(user);
    
        user.setId(index);
        user.setEncryptedPassword(null);
    
        Mockito.when(userService.addUser(Mockito.any())).thenReturn(user);
    
        mvcResult = mvc.perform(MockMvcRequestBuilders.post(URI)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .content(jsonContent)).andReturn();
    
        //Mockito.verify(userService, Mockito.times(1)).addUser(Mockito.any());
    
        int actualStatus = mvcResult.getResponse().getStatus();
        Assert.assertEquals(&quot;Response status should be CREATED&quot;, expectedStatus, actualStatus);
    
        jsonContent = mvcResult.getResponse().getContentAsString();
        returnUser = mapper.readValue(jsonContent, UserDAO.class);
    
        Assert.assertEquals(&quot;EncryptedPassword should not be returned&quot;, null, 
                                          returnUser.getEncryptedPassword());
    }
</code></pre>
<p><strong>User Controller.class</strong></p>
<pre><code> @RestController
 @RequestMapping(&quot;users/&quot;)
 public class UserController {

     UserService userService;
    
     @Autowired
     public UserController(UserService userService) {
         this.userService = userService;
     }
     ....
     ....
     ....

     @PostMapping(path = &quot;&quot;,
            consumes = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }, 
            produces = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public ResponseEntity&lt;UserDAO&gt; createUser(@Valid @RequestBody UserDAO user) {
        String password = user.getEncryptedPassword();
        user.setEncryptedPassword(null);
        UserDAO retreivedUser;
    
        if(user.getId() != 0)
            return new ResponseEntity&lt;&gt;(HttpStatus.BAD_REQUEST);
    
        user.setEncryptedPassword(password);
        retreivedUser = userService.addUser(user);
        if(retreivedUser != null)
            return new ResponseEntity&lt;&gt;(retreivedUser, HttpStatus.CREATED);
        return new ResponseEntity&lt;&gt;(HttpStatus.CONFLICT);
    }
}
</code></pre>
<p>The full code can be found at <a href=""https://github.com/vineethmaller/springboot-userservice"" rel=""nofollow noreferrer"">https://github.com/vineethmaller/springboot-userservice</a></p>
",https://stackoverflow.com/questions/64088842/mockmvc-response-returns-404-expected-response-201,"['spring-boot', 'rest', 'spring-mvc', 'junit', 'mockito']",1095,True,0,1
How to write unit test for code with inputs (Python),"<p>I'm new to unit testing and I have to add a unit test class to a solution to a problem. The problem is the one found here <a href=""https://practice.geeksforgeeks.org/problems/penalty-shooters/0#"" rel=""nofollow noreferrer"">https://practice.geeksforgeeks.org/problems/penalty-shooters/0#</a> and my code is as follows. I'm having trouble figuring out how to unit test with user input.</p>
<pre><code>T = int(input())

for x in range(T):
    # Allows us to input and apply method to all iterables in a | no. of tests \n x_energy y_energy z_energy | format. T = number of tests, x is Lohia energy, y is Gosu energy and z is Goalkeeper energy
    x, y, z = list(map(int, input().split(&quot; &quot;)))
    Goal_Lohia, Goal_Gosu = 0, 0

    # Session ends when goalkeepers energy decrements to 1
    while z &gt; 1:
        # Goalkeepers energy in this case is a factor of both strikers' energy, so both score.
        if x % z == 0 and y%z == 0:
            x = x - 1
            Goal_Lohia = Goal_Lohia + 1
            y = y - 1
            Goal_Gosu = Goal_Gosu + 1
        # In this case, the goalkeepers energy is only a factor of Lohia's. Note Lohia goes first as the problem states.
        elif x % z == 0:
            x = x - 1
            Goal_Lohia = Goal_Lohia + 1
        # And in this case, it is only a factor of Gosu's
        elif y % z == 0:
            y = y - 1
            Goal_Gosu = Goal_Gosu + 1
        # If goalkeepers energy is a factor of neither Gosu nor Lohia, the goalkeeper will save (no goal scored) and will lose energy.
        else:
            z = z - 1
    print(Goal_Lohia, Goal_Gosu)
</code></pre>
<p>Many thanks!</p>
",https://stackoverflow.com/questions/64487301/how-to-write-unit-test-for-code-with-inputs-python,['python'],338,False,3,2
NullPointerException at androidx.sqlite.db.framework.FrameworkSQLiteDatabase.inTransaction - Android Room,"<p>In the unit testing test proyect im trying to query the entity <code>EndPoint</code> but i got this error:</p>
<pre><code>java.lang.NullPointerException
    at androidx.sqlite.db.framework.FrameworkSQLiteDatabase.inTransaction(FrameworkSQLiteDatabase.java:100)
    at androidx.room.InvalidationTracker.syncTriggers(InvalidationTracker.java:480)
    at androidx.room.RoomDatabase.beginTransaction(RoomDatabase.java:353)
    at com.mypackged.data.dao.ConfigurationDao_Impl.setUpdateEndPointConfig(ConfigurationDao_Impl.java:120)
    at com.mypackged.business.server.ServicioGeneralTests.test_just_run_please(ServicioGeneralTests.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
<p>Here is the code im trying to test using <code>MockitoJUnitRunner</code>:</p>
<pre><code>    @Test
    public void test_just_run_please() throws InterruptedException {

        assertNotNull(context);
        CIDatabase db = Room.databaseBuilder(context, CIDatabase.class, CIDatabase.DB_NAME)
                .allowMainThreadQueries()
                .build();
        assertNotNull(db);

        ConfigurationDao configdao = db.getConfiguracionDao();
        assertNotNull(configdao);

        EndPointConfig endPointConfig1 = new EndPointConfig();
        endPointConfig1.setUrl(&quot;url&quot;);
        configdao.setUpdateEndPointConfig(endPointConfig1); // &lt;--- NullPointerException here

        EndPointConfig endPointConfig = configdao.getEndpointConfig();
        assertNull(endPointConfig);


    }
</code></pre>
<p>This is the entity:</p>
<pre><code>@Entity(tableName = &quot;endpoint_config&quot;)
public class EndPointConfig {


    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = &quot;id&quot;)
    private int id;

    @ColumnInfo(name = &quot;url&quot;)
    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
</code></pre>
<p>Dao:</p>
<pre><code>@Dao
public interface ConfigurationDao {

    @Insert(entity = EndPointConfig.class, onConflict = OnConflictStrategy.ABORT)
    void setUpdateEndPointConfig(EndPointConfig endPointConfig);
    // .. more methods
}
</code></pre>
<p>Database :</p>
<pre><code>@Database(entities = {TitularCuenta.class, Familiar.class, Parentesco.class, AppConfiguration.class, EndPointConfig.class} , version = 2)
public abstract class CIDatabase extends RoomDatabase {
    public static final String DB_NAME = &quot;please_work_database&quot;;

    public abstract ConfigurationDao getConfiguracionDao();
    // more dao methods...
}
</code></pre>
<p>Here the gradle dependencies:</p>
<pre><code>    implementation &quot;android.arch.persistence.room:runtime:2.2.4&quot;
    implementation &quot;android.arch.persistence.room:compiler:2.2.4&quot;
    implementation &quot;androidx.room:room-runtime:$room_version&quot;
    kapt &quot;android.arch.persistence.room:compiler:1.0.0&quot;
</code></pre>
<p>If i navigate to the <code>androidx.sqlite.db.framework.FrameworkSQLiteDatabase.inTransaction</code> method here is the line that is throwing the error:</p>
<pre><code>@Override
public boolean inTransaction() {
    return mDelegate.inTransaction();
}
</code></pre>
",https://stackoverflow.com/questions/64503259/nullpointerexception-at-androidx-sqlite-db-framework-frameworksqlitedatabase-int,"['java', 'android', 'sqlite', 'android-room']",203,False,1,0
Mock DbContext.Entry function?,"<p>While Unit Testing, I have Mocked the repository class and want to unit test the Update method which is having below two line of code:</p>
<pre><code>_dIContext.Entry(originalModel).CurrentValues.SetValues(processModel);
_dIContext.Entry(originalModel).State = EntityState.Modified;
</code></pre>
<p>at first line I am getting NullReferenceException.</p>
<p>Below is my SetUp method of Unit test class:</p>
<pre><code>_mockContext = new Mock&lt;ContextClass&gt;(null);
processModels = CreateProcessModelList();
mockDbSet = new Mock&lt;DbSet&lt;ProcessModel&gt;&gt;();
mockDbSet.As&lt;IQueryable&lt;ProcessModel&gt;&gt;().Setup(m =&gt; m.Provider).Returns(processModels.AsQueryable().Provider);
mockDbSet.As&lt;IQueryable&lt;ProcessModel&gt;&gt;().Setup(m =&gt; m.Expression).Returns(processModels.AsQueryable().Expression);
mockDbSet.As&lt;IQueryable&lt;ProcessModel&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(processModels.AsQueryable().ElementType);
mockDbSet.As&lt;IQueryable&lt;ProcessModel&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(processModels.AsQueryable().GetEnumerator());
_mockContext.Setup(x =&gt; x.ProcessModels).Returns(mockDbSet.Object);
_repository = new ProcessRepository(_mockContext.Object);
</code></pre>
<p>Can anyone correct me if my code is wrong?</p>
",https://stackoverflow.com/questions/63739212/mock-dbcontext-entry-function,"['c#', '.net-core', 'entity-framework-core', 'nunit', 'moq']",385,False,1,0
Mocha Chai unit testing run specific folder,"<p>I have a application where it contains the test folder in main directory to maintain the <code>*test.js</code> files inside test folder. This test folder contains multiple sub folder representing each functionality and these sub folder conatains many <code>*test.js</code> files. How to run the specific testcase from selected folder in Mocha unit testing.</p>
",https://stackoverflow.com/questions/63153627/mocha-chai-unit-testing-run-specific-folder,"['node.js', 'mocha.js', 'chai']",454,False,1,1
"Jest, Babel and Storybook, export vs module.exports","<p>I am using Jest to test my services and Storybook and Babel to develop my React components.</p>

<p>I have a service which my component needs to use. I currently export with <code>module.exports = someFunction;</code> and it passes my Jest unit tests, but storybook tells me <code>Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</code> in the browser console.</p>

<p>If I change the service to <code>export default someFunction</code>, the component works but the Jest unit test fails with <code>SyntaxError: Unexpected token export</code>.</p>

<p><em>What do I do to make both work?</em></p>

<p>Notes:</p>

<ul>
<li>I don't care whether I consistently export with <code>module.exports</code> or <code>export</code>. I have no real preference at this time.</li>
<li>I'm prepared to use a different unit-testing library, but I wasn't happy with Ava last time, and I don't remember having any luck with unit testing software and babel.</li>
<li>Last time I was using Babel I didn't have a problem with <code>module.exports</code>. Would a downgrade help? If so, what would I downgrade to?</li>
</ul>
",https://stackoverflow.com/questions/59626208/jest-babel-and-storybook-export-vs-module-exports,"['javascript', 'babeljs']",345,False,0,1
XUnit test to return a see if a list is being returned,"<p>I'm learning Unit Testing and I'm struggling to grasp how we can test to see if a type of list is returning, not necessarily the content of the list but to make sure its a LIST that is being returned.</p>

<p>Returning an empty list of strings </p>

<pre><code>    public List&lt;string&gt; GetList()
    {
        var names = new List&lt;string&gt;();

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

<p>My test, trying to return a typeofList: </p>

<pre><code>    [Fact]
    public void GetListTest()
    {
        Assert.Equal(typeof(List&lt;string&gt;), GetList());
    }
</code></pre>
",https://stackoverflow.com/questions/60076388/xunit-test-to-return-a-see-if-a-list-is-being-returned,"['c#', 'tdd', 'xunit']",1338,True,2,2
Unit Testing for Providers in Flutter,"<p>We have started a new project on Flutter in the TDD approach. I am using providers for State Management.
While trying to write the Widget Testing we are facing the issue to test the providers.
Can you please suggest with an example to write the unit testing for providers and widget injects the provider.</p>
<p>I'm getting the following issue</p>
<pre><code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════
The following ProviderNotFoundException was thrown running a test:
Error: Could not find the correct Provider above this SplashScreen Widget

To fix, please:

Ensure the Provider is an ancestor to this SplashScreen Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Always use package imports. Ex: `import 'package:my_app/my_code.dart';
Ensure the correct context is being used.
</code></pre>
<p>══╡ Splash Screen Code╞════════════════════════════════════</p>
<pre class=""lang-dart prettyprint-override""><code>import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../routes.dart';
import '../../constants/constants.dart';
import '../../providers/provider.dart';
import '../../services/navigation_service.dart';
import '../../utils/utlis.dart';

class SplashScreen extends StatefulWidget {
  @override
  SplashScreenState createState() =&gt; SplashScreenState();
}

class SplashScreenState extends State {
  void startTime() {
    const _duration = Duration(seconds: Preferences.splashScreenTime);
    Timer(_duration, _getInitialData);
    _getInitialData();
  }

  dynamic _getInitialData() async {
    final TokenProvider tokenProvider =
    Provider.of(context, listen: false);

    await tokenProvider.setAccessToken();

    navigationPage();
  }

  void navigationPage() {
    NavigationService.pushReplacementNamedTo(Routes.home_screen);
  }

  @override
  void initState() {
    super.initState();
    startTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        key: const Key('splashScreen_body'),
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/flutter.png',
            key: const Key('splashScreen_image'),
          )
        ],
      ),
    );
  }
}
</code></pre>
<p>thank in advance</p>
",https://stackoverflow.com/questions/59735075/unit-testing-for-providers-in-flutter,"['flutter', 'flutter-dependencies', 'flutter-test', 'flutter-plugin', 'flutter-channel']",10501,True,12,2
How to create customised vertex without creating the graph.?,"<p>I need to make an object of vertex in apache.tinkerpop for unit testing without creating an actual graph . Basically , I see no point to create an actual vertex in graph database.</p>

<p>I read about detached vertex , but not sure how to use it . Is there any other way to do this?</p>
",https://stackoverflow.com/questions/61175007/how-to-create-customised-vertex-without-creating-the-graph,"['java', 'unit-testing', 'mockito', 'tinkerpop']",28,True,0,1
i want to write unit test case for my angular js app,"<p>I have a weather app that uses <a href=""https://metaweather.com/api/"" rel=""nofollow noreferrer"">https://metaweather.com/api/</a> to fetch the weather the js code is as</p>
<pre><code>angular.module('ourAppApp')
.controller('MainCtrl', function($scope,apiFac) {

    $scope.displayCity = false;
    $scope.displayWeather = false;
    $scope.today = new Date();
    $scope.searchCity = function(){

        if($scope.cityInput != &quot;&quot;){ 
          apiFac.searchCity($scope.cityInput).then(function(response){
            $scope.searchResponse = response;
            $scope.displayCity = true;
          })
        }   
    }

    $scope.getcitydetails = function(item){
      $scope.cityInput = &quot;&quot;;
      $scope.displayCity = false;
      $scope.selectedCity = item;

      apiFac.weatherReport(item.woeid).then(function(response){
        $scope.weatherResponse = response;
        $scope.displayCity = false;
        $scope.displayWeather = true;
      })
    }


})
</code></pre>
<p>and the index.html is as</p>
<pre><code>    &lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.min.js&quot;&gt;&lt;/script&gt;
  &lt;base href=&quot;/&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;styles/style.css&quot;&gt;
  &lt;title&gt;Weather app&lt;/title&gt;
&lt;/head&gt;
&lt;body ng-app=&quot;ourAppApp&quot;&gt;
  &lt;div ng-view=&quot;&quot;&gt;
  &lt;/div&gt;

  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
  &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js&quot;&gt;&lt;/script&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;&gt;
  &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;scripts/app.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;scripts/controllers/main.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;scripts/factory/apiFac.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>I want to write the unit test case for the angularjs functions, I am new to unit testing any help would be really appreciated thanks in advance</p>
",https://stackoverflow.com/questions/65202692/i-want-to-write-unit-test-case-for-my-angular-js-app,"['javascript', 'html', 'angularjs', 'unit-testing']",204,False,0,1
Integration test with Cypress or React Testing Library?,"<p>I'm new to testing and as I understand, integration tests are aimed to test a bunch of components and how they interact with each other.</p>
<p>But if in a project we use both Cypress for E2E and React testing library for unit testing, which one to use for integration tests, and what are the pros and cons?</p>
",https://stackoverflow.com/questions/65063082/integration-test-with-cypress-or-react-testing-library,"['reactjs', 'testing', 'frontend', 'cypress', 'react-testing-library']",2246,True,5,2
How can I test styles from props in a styled component?,"<p>Good afternoon, I am a begginer in unit testing. I created a component <code>&lt;CustomLink /&gt;</code> in it I use styled-component <code>Link</code>. I need to write a unit test using any of the tools (Mocha, Enzime, etc.) except Jest, which would check that the font in my styled-component is 18px.</p>

<pre><code>export const CustomLink = props =&gt; {
    return(
        &lt;WrapperLink&gt;
            &lt;Link fontSize=""18px""&gt;{props.text}&lt;/Link&gt;
        &lt;/WrapperLink&gt;
    )
};
</code></pre>

<p>Styled-component:</p>

<pre><code>import styled from 'styled-components';

    export const Link = styled.a`
        font-size: ${props =&gt; props.fontSize};
        cursor: pointer;
    `;
</code></pre>
",https://stackoverflow.com/questions/60880956/how-can-i-test-styles-from-props-in-a-styled-component,"['reactjs', 'unit-testing', 'mocha.js', 'tdd', 'enzyme']",637,True,0,1
Test if Material-UI withStyles component with required PropTypes is rendered?,"<p>I'm new to unit testing and having trouble testing whether a Material-UI withStyles component with required propTypes is rendering children Material-UI elements.</p>
<p>profile.js</p>
<pre><code>const StaticProfile = (props) =&gt; {
  const { classes, profile } = props
}

return (
  &lt;Paper&gt;
    &lt;div&gt;
      &lt;MuiLink&gt;&lt;/MuiLink&gt;
      &lt;Typography&gt;
      &lt;LocationOn&gt;
      &lt;LinkIcon&gt;
      &lt;Calendar&gt;
    &lt;/div&gt;
  &lt;/Paper&gt;
)
</code></pre>
<p>profile.test.js</p>
<pre><code>describe('&lt;StaticProfile /&gt;', () =&gt; {
  let shallow;
  let wrapper;

  const myProps = {
    profile: {},
    classes: {}
  }

  beforeEach(() =&gt; {
    shallow = createShallow();
    wrapper = shallow(&lt;StaticProfile {...myProps} /&gt;);
  })

  it('should render a Paper element', () =&gt; {
    expect(wrapper.find(Paper).length).toBe(1);
  })
})
</code></pre>
<p>However, it doesn't seem like the component is rendered at all with this error received.</p>
<pre><code>expect(received).toBe(expected) // Object.is equality

Expected: 1
Received: 0
</code></pre>
<p>Could someone please point me in the right direction?</p>
",https://stackoverflow.com/questions/62826380/test-if-material-ui-withstyles-component-with-required-proptypes-is-rendered,"['reactjs', 'jestjs', 'material-ui']",46,True,0,1
Function not found,"<p>I am trying to create a class that spins up a test db from sample JSON data using testing.postgresql. I want to call in 5 JSON files and create 5 tables that I can use for unit-testing operators and queries in airflow.</p>
<p>code so far is</p>
<pre><code>import json
import decimal, datetime
import testing.postgresql
import psycopg2

class PostgresMock:
    
    with testing.postgresql.Postgresql() as postgresql:
        #engine = create_engine(postgresql.url())
        db = psycopg2.connect(**postgresql.dsn())

        #load Json file with dummy data
        def load_data(self):
            with open(self) as f:
                data=json.load(f)
            return data
        
        #build create statement from sql file
        def create_sql(self):
            # Find all keys
            keys = []
            for row in data:
                for key in row.keys():
                    if key not in keys:
                        keys.append(key)

            create_statement=(&quot;&quot;&quot;CREATE TABLE MY_TABLE({0});&quot;&quot;&quot;.format(&quot;,\n  &quot;.join(map(lambda key: &quot;{0} VARCHAR&quot;.format(key), keys))))

            return  create_statement
        
        #build insert statement
        def sql_insert(data):
            for row in data:
                print (&quot;&quot;&quot;INSERT INTO MY_TABLE VALUES({0});&quot;&quot;&quot;.format(
        &quot;,&quot;.join(map(lambda key: &quot;'{0}'&quot;.format(row[key]) if key in row else &quot;NULL&quot;, keys))))
         
        #create handler for test db and insert 
        def handler(postgresql):
            conn = psycopg2.connect(**postgresql.dsn())
            cursor = conn.cursor()
            cursor.execute(create_sql(file))
            for statement in sql_insert(data):
                try:
                    cursor.execute(f'{statement}')
                    conn.commit()
                except psycopg2.Error as errorMsg:
                    print(errorMsg)
                    conn.rollback()
            cursor.close()
            conn.commit()
            conn.close()
            
         # Use `handler()` on initialize database
    PostgresqlMock = testing.postgresql.PostgresqlFactory(cache_initialized_db=True,
                                                  on_initialized=handler)
</code></pre>
<p>Getting the error</p>
<pre><code>name 'create_sql' is not defined
</code></pre>
",https://stackoverflow.com/questions/65321821/function-not-found,"['python', 'postgresql', 'function', 'class']",72,True,0,1
Unit testing interfaces using lambdafunction AWS annotation,"<p>I'm looking a way to unit testing a call to an external lambda. I have an interface using @LambdaFunction (<code>functionName = &quot;external-lambda&quot;</code>) on a method that call the external handler. I don't figure out how to (mock maybe?) Stub this component inside my unit test. There is a correct way to attain this?</p>
",https://stackoverflow.com/questions/63043674/unit-testing-interfaces-using-lambdafunction-aws-annotation,"['amazon-web-services', 'junit', 'aws-lambda', 'mockito']",40,False,0,0
Is possible to access ATTR for Perl packages without defining a getter?,"<p>I am currently working on a Perl 5.8 project.
I have package that looks like:</p>
<pre><code>package Foo::Bar;

use strict;
use warnings;
use Class::Std;

our @EXPORT_SAFE = qw(Class::Std);

my %baz :ATTR;

sub BUILD {
  my ($self, $ident, $args) = @_;
  
  $baz{$ident} = $$args{something};
}
</code></pre>
<p>I am not exposing <code>baz</code> with any getter, but I would like to fetch it's content for unit testing purposes. There is any way to do it in Perl?</p>
<p>e.g. in Ruby you can <code>some_instance.instance_variable_get(&quot;@#{name}&quot;)</code></p>
<p>Thank you very much in advance</p>
",https://stackoverflow.com/questions/63595446/is-possible-to-access-attr-for-perl-packages-without-defining-a-getter,['perl'],115,True,3,2
"Getting repetitive iterations while solving sinon, unable to do unit testing in nodejs","<p>I am trying to do unit testing in Nodejs using sinon.</p>
<p>And I have installed the following libraries -</p>
<p><a href=""https://i.stack.imgur.com/tPjUU.png"" rel=""nofollow noreferrer"">1</a> npm i mocha</p>
<p>[2] npm i chai</p>
<p>[3] npm i sinon</p>
<p>And here is my code -</p>
<p><strong>unitTest-app.js</strong></p>
<pre><code> var sinon = require('sinon');


it('calls the original function', function(){

   var callback = sinon.fake();
   var proxy = once(callback);


   proxy();

   assert(callback.called);

   });



it('calls the original function only once', function () {
   var callback = sinon.fake();
   var proxy = once(callback);

    proxy();
    proxy();

     assert(callback.calledOnce);
     // ...or:
    // assert.equals(callback.callCount, 1);
   });
</code></pre>
<p><strong>unitTest.js</strong></p>
<pre class=""lang-js prettyprint-override""><code>function once(fn) {
  var returnValue,
    called = false;
  return function() {
    if (!called) {
      called = true;
      returnValue = fn.apply(this, arguments);
    }

    return returnValue;
  };
}
</code></pre>
<p>Unable to run the unit tests.</p>
<p>when running the command  -</p>
<pre><code>npm run test
</code></pre>
<p>Getting error -</p>
<p><a href=""https://i.stack.imgur.com/tPjUU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tPjUU.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/64852147/getting-repetitive-iterations-while-solving-sinon-unable-to-do-unit-testing-in,"['javascript', 'angular', 'unit-testing', 'mocha.js', 'sinon']",48,False,0,1
Nsubstitute executing Action as parameter on a mocked interface,"<p>Is there anyway I can execute an action as a parameter from a mocked out service?</p>
<p>I have an interface that is used in the method I am unit testing:</p>
<pre><code>interface IMyTracker
{
    void TrackerMethod(string name, Action action);
}
</code></pre>
<p>This is the method I want to unit test:</p>
<pre><code>private void Method1(IMyTracker myTracker)
{

    myTracker.TrackerMethod(&quot;Method1&quot;,() =&gt;
    {       
        // This is stuff I want to execute!
    }
}
</code></pre>
<p>Here is my unit test</p>
<pre><code>[Test]
public void TestMethod1()
{
    var trackerSub = Substitute.For&lt;IMyTracker&gt;();
    trackerSub.TrackerMethod(Arg.Any&lt;string&gt;(), Arg.Invoke&lt;Action&gt;()); //How do I execute the logic inside the lambda expression action? Is it at all possible? Or once it's mocked, is that logic lost?
    GetClassInstance().Method1(trackerSub);
}
</code></pre>
<p>Any help here would be great.</p>
",https://stackoverflow.com/questions/63641926/nsubstitute-executing-action-as-parameter-on-a-mocked-interface,"['c#', 'mocking', 'action', 'nsubstitute']",325,True,0,1
Is it possible to mock system calls(ex: malloc) without modifying source code using gmock?,"<p>I would like to mock system calls such as malloc/file-open for unit testing my code without modifying the production code.
Also, creating wrappers for these system calls in source code is not feasible and hence that option is ruled out.</p>

<p>Any inputs/solution for the will be helpful.</p>
",https://stackoverflow.com/questions/60565221/is-it-possible-to-mock-system-callsex-malloc-without-modifying-source-code-us,"['unit-testing', 'malloc', 'system-calls', 'googletest', 'googlemock']",404,True,0,1
How to read entire string from JsonTextReader,"<p>I have a JsonConverter. I created a unit test for the ReadJson. I have an error in my unit test that says the reader value is null. How can I read the entire string from the reader?</p>
<pre><code>public class StringConverter&lt;T&gt; : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(T);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return JsonConvert.DeserializeObject&lt;T&gt;((string)reader.Value);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JsonConvert.SerializeObject(value);
    }
}
</code></pre>
<p>My code for unit testing</p>
<pre><code>    private Converter.StringConverter&lt;InstanceSettings&gt; _converter;

    private JsonTextReader CreateJsonReader(string json)
        =&gt; new JsonTextReader(new StringReader(json));

    [SetUp]
    public override void Setup()
    {
        base.Setup();
        _converter = new Converter.InstanceSettingsConverter();
    }

   public void StringConverter_ReadJson_InvalidJson_EmptyInstanceSettings()
    {
        // Arrange
        var serializer = new JsonSerializer();
        var json = &quot;{\&quot;property\&quot;:{\&quot;search\&quot;:true}}&quot;;
        var reader = CreateJsonReader(json);

        // Act
        var result = _converter.ReadJson(reader, typeof(InstanceSettings), null, serializer);

        Assert.IsNotNull(result);
        Assert.IsAssignableFrom&lt;InstanceSettings&gt;(result);
    }
</code></pre>
<p>I user the converter to convert string to my type</p>
<pre><code>    [JsonConverter(typeof(StringConverter&lt;InstanceSettings&gt;))]
    [JsonProperty(&quot;settings&quot;)]
    public InstanceSettings Settings { get; set; }
    
</code></pre>
",https://stackoverflow.com/questions/64000529/how-to-read-entire-string-from-jsontextreader,"['c#', 'json', 'jsonconvert']",2422,True,1,1
Unit Testing in Angular not.toBe(true) vs toBeFalsy(),"<p>I am writing a Angular Unit Testing which I am facing with an error.
If I write toBeFalsy() the test will fail.
But If I write not.toBe(true) the test will work.</p>

<p>May someone help me.</p>

<pre><code>let fixture: ComponentFixture&lt;RootComponent&gt;;
let debugElement: DebugElement;

beforeEach(async () =&gt; {
    fixture = TestBed.createComponent(RootComponent);
    await executeChangeDetection(fixture);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement.query(By.css('#overlay'));
  });


it('should hide overlay and reset timeout', () =&gt; {
    const appState = new ApplicationStateService(null as any);
    appState.timeout = false;
    component.isTimeoutOverlayVisible = appState.timeout;
    fixture.detectChanges();
    expect(debugElement.nativeElement).toBeFalsy();
  });
</code></pre>

<p><strong>toBeFalsy()</strong> the test will fail but as message will come that.<br>
<code>Expected &lt;overlay id=""overlay""&gt;...&lt;/overlay&gt; to be falsy.</code></p>

<p><strong>not.toBe(true)</strong> the test will work.</p>
",https://stackoverflow.com/questions/59632008/unit-testing-in-angular-not-tobetrue-vs-tobefalsy,"['angular', 'jasmine', 'protractor', 'karma-jasmine']",3596,True,1,1
How to unit test django application using jena-fuseki?,"<p>My django application uses sparql with jena-fuseki RDF-database. How should I run my unit tests as thete's hardly any information in availble for creatig in-memory jena database for a django unittesting ?  So far I've been just running a local fuseki-server, but that's not the way unit testing should be done, right ?</p>
",https://stackoverflow.com/questions/60597836/how-to-unit-test-django-application-using-jena-fuseki,"['django', 'sparql', 'python-unittest', 'jena', 'fuseki']",103,False,2,0
Mocking React custom hook with Jest,"<p>I need to mock my custom hook when unit testing React component. I have read few tutorials and stackoverflow answers to this simple task, but without luck to implement it correctly.</p>
<p>My simplest possible setup for single test is as following:</p>
<pre><code>// TestComponent.js

import React from &quot;react&quot;;
import useTest from &quot;./useTest&quot;;

const TestComponent = () =&gt; {
  const { state } = useTest(&quot;initial_value&quot;);

  return &lt;div&gt;{state}&lt;/div&gt;;
};

export default TestComponent;
</code></pre>
<pre><code>// useTest.jsx - simple custom hook

import React, { useState } from &quot;react&quot;;

const useTest = (initialState) =&gt; {
  const [state] = useState(initialState);
  return { state };
};

export default useTest;

</code></pre>
<pre><code>// TestComponent.test.jsx - my test case

import React from &quot;react&quot;;
import { render } from &quot;@testing-library/react&quot;;
import TestComponent from &quot;./TestComponent&quot;;

jest.mock(&quot;./useTest&quot;, () =&gt; ({
  useTest: () =&gt; &quot;mocked_value&quot;,
}));

test(&quot;rendertest&quot;, () =&gt; {
  const component = render(&lt;TestComponent /&gt;);
  expect(component.container).toHaveTextContent(&quot;mocked_value&quot;);
});

</code></pre>
<p>So I trying to mock <code>useTest</code> custom hook to return &quot;mocked_value&quot;, instead of &quot;initial_value&quot; from real custom hook. But above code just gives me this error:</p>
<pre><code>TypeError: (0 , _useTest.default) is not a function

      3 | 
      4 | const TestComponent = () =&gt; {
    &gt; 5 |   const { state } = useTest(&quot;initial_value&quot;);
        |                     ^
      6 | 
      7 |   return &lt;div&gt;{state}&lt;/div&gt;;
      8 | };
</code></pre>
<p>I have also tried:</p>
<pre><code>import useTest from './useTest';
// ...
jest.spyOn(useTest, &quot;useTest&quot;).mockImplementation(() =&gt; &quot;mocked_value&quot;);
</code></pre>
<pre><code>import useTest from './useTest';
// ...
jest.spyOn(useTest, &quot;useTest&quot;).mockReturnValue(&quot;mocked_value&quot;);
</code></pre>
<p>But both gives me error <code>Cannot spy the useTest property because it is not a function; undefined given instead</code>.</p>
<p>How do I implement this test?</p>
",https://stackoverflow.com/questions/65270255/mocking-react-custom-hook-with-jest,"['reactjs', 'jestjs', 'mocking', 'react-hooks']",25645,True,23,3
How to unit test django application using jena-fuseki?,"<p>My django application uses sparql with jena-fuseki RDF-database. How should I run my unit tests as thete's hardly any information in availble for creatig in-memory jena database for a django unittesting ?  So far I've been just running a local fuseki-server, but that's not the way unit testing should be done, right ?</p>
",https://stackoverflow.com/questions/60597836/how-to-unit-test-django-application-using-jena-fuseki,"['django', 'sparql', 'python-unittest', 'jena', 'fuseki']",103,False,2,0
How to properly set getter setter in interface projection for a boolean variable starting with is?,"<p>I am using <a href=""https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.interfaces"" rel=""nofollow noreferrer"">interface projection</a> . For unit testing purpose i have to add both getter and setter. In Jpa query i have a Boolean parameter named <code>isPublic</code>. But getter setter not working. i tried following</p>
<pre><code>  Boolean isPublic();

  void setPublic(Boolean isPublic);

</code></pre>
<p>and this</p>
<pre><code>  Boolean getIsPublic();

  void setIsPublic(Boolean isPublic);

</code></pre>
<p>and this</p>
<pre><code>  Boolean getPublic();

  void setPublic(Boolean isPublic);

</code></pre>
<p>But everything works when i change variable name to <code>public</code> with setter <code>setPublic</code> and getter <code>getPublic</code>. How do i properly set getter setter for <code>isPublic</code>?</p>
",https://stackoverflow.com/questions/63180127/how-to-properly-set-getter-setter-in-interface-projection-for-a-boolean-variable,"['spring-boot', 'spring-data-jpa', 'projection']",2310,True,4,2
Unit testing; How to mock out a class object which is going to be passed to a function in Python?,"<p>I'm in the means of doing a Python embedded project where I'm using Python-OpenZwave to communicate with a sensor via a z-wave dongle. And I need to do some unit testing on functions I have implemented. I'm not that experienced in unit testing, and have run into a problem with dependencies that I need to get rid of during the unit testing, because some of these funtions I have implemented communicates with the sensor and therefore only work on my embedded platform.</p>
<p>One of the functions I need to test is shown below, it takes 2 arguments, first is the ID of the sensor, the second is a network class object from the OpenZWave libary. It first sets the ID of the sensor we are working with in the class through a function call, second gets all data from the sensor and saves it as a dict in the class object, whereafter I search through all the data for the temperature value and return it;</p>
<pre><code>def get_temperature(sensor_id, network_obj):
    multisensor = network_obj.nodes[sensor_id]
    multisensor.get_values()
    values = {}
    for value in multisensor.values:
        if multisensor.values[value].label == 'Temperature':
            values = {'Temperature': multisensor.values[value].data}
    return values
</code></pre>
<p>The thing I need help with, is how I can get rid of the dependency coming from the class object which is parsed to the function? I have tried methods I found online Patching, MonkeyPatching, Mock and MagicMock but haven't been able to make any of it work. So I would like some advice on how I can get rid of the dependencies and what libary / tool I should use in this case.</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/64753811/unit-testing-how-to-mock-out-a-class-object-which-is-going-to-be-passed-to-a-fu,"['python', 'unit-testing', 'mocking', 'monkeypatching', 'z-wave']",67,False,1,0
Unit Testing for Javascripts in Dynamics 365,"<p>I am looking for some references related to javascript unit testing for D365. Since the new object model ExecutionContext.getFormContext has replaced the old Xrm.Page model, I am unable to find some info on this new object model which has been used for writing unit test case. Has anyone tried or post something related to this.</p>
",https://stackoverflow.com/questions/61633987/unit-testing-for-javascripts-in-dynamics-365,"['javascript', 'dynamics-crm-365']",113,False,2,0
How do you unit test Google Cloud NDB code?,"<p>The recommended path for upgrading a Python 2 AppEngine app to the new runtime is to switch datastore code to Google Cloud NDB. However, I can't find anything about unit testing code that uses Cloud NDB (which was previously possible using the Python 2 testbed library).</p>

<p>How can Cloud NDB code be unit tested? (apart from standard abstracting the Cloud NDB dependency yourself)</p>
",https://stackoverflow.com/questions/60351198/how-do-you-unit-test-google-cloud-ndb-code,"['python', 'google-app-engine', 'google-cloud-datastore', 'app-engine-ndb', 'google-app-engine-python']",653,True,7,1
JEST testing canvas and ctx,"<p>I have created a method to get image base64 using canvas, i want to unit test it using jest in angular:</p>
<pre><code> getExistingImagebase64() {
    const img = new Image();
    img.crossOrigin = 'Anonymous';

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    img.onload = () =&gt; {
      canvas.height = img.naturalHeight;
      canvas.width = img.naturalWidth;
      ctx.drawImage(img, 0, 0);
      const uri = canvas.toDataURL('image/png');      
      const b64 = uri.replace(/^data:image.+;base64,/, '');
      this.companyGroupForm.patchValue({
        cgFormGroup: {
          logo: b64
        },
      });  
      this.populateForm(this.receivedItemFromNavigation);
    };
    const url = this.receivedItemFromNavigation.logo;
    img.src = url;
  }
</code></pre>
<p>in unit testing doing like this:</p>
<pre><code> it('should mark form as valid on edit scenario', fakeAsync(() =&gt; {
    TestBed.overrideProvider(Router, { useValue: new MockRouter('/edit') });
    TestBed.compileComponents();
    fixture = TestBed.createComponent(GroupCompanyAddComponent);
    component = fixture.componentInstance;

    trackImageOnload();

    const formSubmitSpy = spyOn(component, 'submitEditDataToApi').and.callThrough();
    const successDialogSpy = spyOn(component, 'successDialog').and.callThrough();

    fixture.detectChanges();
    tick(1000);
    imageOnload();

    fixture.detectChanges();
    fixture.whenStable();
    tick(1000);


    expect(component.companyGroupForm.valid).toBeTruthy();
  }));
</code></pre>
<p>I am getting error that <code>TypeError: ctx.drawImage is not a function</code>, in my <strong>UT</strong> <code>trackImageOnload();</code> is for mocking the imageonload, it is working as expected.</p>
<p>Need some help.</p>
<p>I have already added jest-canvas-mock</p>
",https://stackoverflow.com/questions/64444643/jest-testing-canvas-and-ctx,"['angular', 'jestjs']",2121,True,2,1
Unit Testing framework for Embedded platform in C++?,"<p>I am working on an embedded systems project using ACE Framework and all the development is done using eclipse IDE. I am looking for a good testing framework.
Basically the project involves parsing of incoming data and I am searching for a unit testing framework which suits my project. What are my options here?</p>
",https://stackoverflow.com/questions/59818467/unit-testing-framework-for-embedded-platform-in-c,"['c++', 'eclipse', 'unit-testing', 'ace']",994,True,2,2
Jestjs - uncaughtException: describe is not defined\nReferenceError: describe is not defined,"<p>I got this error <code>uncaughtException: describe is not defined\nReferenceError: describe is not defined</code> while doing unit testing with Jestjs in my Nodejs app. However, all tests still run well with <code>npm run test</code>.</p>

<p>I noticed that after I made a new test file in a sub-folder 2 levels below the root folder, the error appeared. </p>

<p>How can I fix it?</p>

<p><em>directory tree</em></p>

<pre><code>...
app.test.js // this doesn't cause the error
modules/
   ├── utils.js
   ├── utils.test.js // this doesn't cause the error
   ├── database
        ├── database.js
        ├── database.test.js // the error appeared after this file created
...
</code></pre>

<p><em>package.json</em></p>

<pre><code>...
""devDependencies"": {
    ""eslint"": ""^6.8.0"",
    ""eslint-config-airbnb-base"": ""^14.0.0"",
    ""eslint-plugin-import"": ""^2.19.1"",
    ""eslint-plugin-jest"": ""^23.6.0"",
    ""jest"": ""^24.9.0"",
    ""jsdoc"": ""^3.6.3"",
    ""nodemon"": ""^2.0.2"",
    ""supertest"": ""^4.0.2""
  },
""scripts"": {
    ""test"": ""jest --watchAll --verbose"",
    ""start"": ""nodemon server.js""
  },
  ""jest"": {
    ""testEnvironment"": ""node"",
    ""coveragePathIgnorePatterns"": [
      ""/node_modules/""
    ]
  },
...
</code></pre>

<p><em>eslintrc.json</em></p>

<pre><code>{
  ""env"": {
    ""browser"": true,
    ""commonjs"": true,
    ""es6"": true,
    ""jest"": true
  },
  ""extends"": [
    ""airbnb-base""
  ],
  ""plugins"": [""jest""],
  ""globals"": {
    ""Atomics"": ""readonly"",
    ""SharedArrayBuffer"": ""readonly""
  },
  ""parserOptions"": {
    ""ecmaVersion"": 2018
  },
  ""rules"": {
    ""no-shadow"": 0
  }
}
</code></pre>
",https://stackoverflow.com/questions/60040131/jestjs-uncaughtexception-describe-is-not-defined-nreferenceerror-describe-is,"['javascript', 'node.js', 'unit-testing', 'jestjs']",222,True,0,1
How do I test functions with different parameters using Unity Unit testing in C?,"<p>The function add_first(int n) adds a number to a linked list and it returns 0 if successful and -1 if not.</p>
<p>The test is good but I would like to test a wider variety of situations so to test more of the same function with different parameters.</p>
<p>If I modify test_add_first and add a parameter it gives me an error because MY_RUN_TEST and RUN_TEST will only accept &quot;myfunction(void)&quot;. Therefore I have to create individual functions for each number.</p>
<p>I have this code in my test.c file and I am using Unit testing - Unity as the title says.</p>
<pre><code>#define MY_RUN_TEST(func) RUN_TEST(func, 0)

ITEM *list = NULL;

void printList(struct ITEM *node) 
{
  if(node == NULL)
  {
    printf(&quot;list is empty&quot;);
  } 
    while (node != NULL) 
    { 
        printf(&quot;%d &quot;, node -&gt; value); 
        node = node-&gt;next; 
    } 
} 

void test_add_first_1()
{
  int ret;
  ret = add_first(&amp;list, 1);
  TEST_ASSERT_EQUAL(0, ret);
}

void setUp(void)
{
    // This is run before EACH test
}

void tearDown(void)
{
  // This is run after EACH test
  printList(list);
  printf(&quot;\n&quot;);
}

int main (int argc, char * argv[])
{
    
    
    UnityBegin();
   
    MY_RUN_TEST(test_add_first_1);
    
    return UnityEnd();
}

</code></pre>
<p>So my question to be more specific is there any way to test these as something like - MY_RUN_TEST(test_add_first(n)); - n being an integer?</p>
<p>If you find something else wrong at this piece of code please tell I am just starting with Unit Testing. :)</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/64404193/how-do-i-test-functions-with-different-parameters-using-unity-unit-testing-in-c,"['c', 'unit-testing']",1025,True,1,1
Jest Unit testing for conditional elements with react-hook-form,"<p>Im having a react hook form and some validation messages. I need to unit test this component. But all the time my conditional elements are not being rendered or updated. I've tried <code>wrapper.update();</code> but it's not serving the purpose.</p>
<p>My Component:</p>
<pre><code>&lt;form data-test='login-form' onSubmit={handleSubmit(onSubmit)}&gt;
   &lt;input data-test='password' name='password'
      ref={register({
           required: 'Password Required',
           minLength: {
              value: 6,
              message: 'Password should be 6 char long' ,
           },
          })}
    /&gt;
    {errors.password &amp;&amp; (
       &lt;p data-test='password-error'&gt;
          {(errors.password as any).message}
       &lt;/p&gt;
    )}
 &lt;button data-test='login-submit'&gt;
    Submit
 &lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>Unit Testing:</p>
<pre><code>const setup = (): ShallowWrapper =&gt;
      shallow(&lt;LoginForm  /&gt;);

 describe('Login Form Component', () =&gt; {
   let wrapper: ShallowWrapper;
   test('expect to show password required validation messages', async () =&gt; {
  
   wrapper = setup();
   const loginButton = wrapper.find(`[data-test='password-error']`);

   loginButton.simulate('click');

   wrapper.update();

   const emailError = wrapper.find(`[data-test='email-error']`);
   expect(emailError.length).toBe(1);
 });
});
</code></pre>
<p>This never passes.</p>
<p>Any help is appreciated.</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/64558048/jest-unit-testing-for-conditional-elements-with-react-hook-form,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'react-hook-form']",820,False,0,0
Append objects to an array fails unit tets,"<p>I am new to unit testing.</p>
<p>I have an extension method that appends objects to an array of objects. But it fails unit tests anytime I run it. Below is my extension method</p>
<pre><code>    /// &lt;summary&gt;
    /// Appends the given objects to the array source.
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;T&quot;&gt;The specified type of the array&lt;/typeparam&gt;
    /// &lt;param name=&quot;source&quot;&gt;The original array of values&lt;/param&gt;
    /// &lt;param name=&quot;toAdd&quot;&gt;The values to append to the source.&lt;/param&gt;
    /// &lt;returns&gt;The concatenated array of the specified type&lt;/returns&gt;
    public static T[] Append&lt;T&gt;(this IEnumerable&lt;T&gt; source, params T[] toAdd) =&gt; source.Concat(toAdd).ToArray();
</code></pre>
<p>... and here is my test</p>
<pre><code>    [Theory]
    [InlineData(&quot;Test&quot;, &quot;Local&quot;, 3, &quot;First Test&quot;)]
    [InlineData(&quot;Test&quot;, &quot;Removable&quot;, 15, &quot;Second Test&quot;)]
    [InlineData(&quot;Test&quot;, &quot;Dedicated&quot;, 33, &quot;Third Test&quot;)]
    public void AppendToArray_ArrayNotEmpty(string origin, string filePath, int lineNumber, string message)
    {
        object[] args = { };

        args.Append(origin, filePath, lineNumber, message);

        Assert.NotEmpty(args);
    }
</code></pre>
<p>Is there something I am missing? I am using XUnit as my test framework.</p>
",https://stackoverflow.com/questions/64859051/append-objects-to-an-array-fails-unit-tets,"['c#', 'arrays', 'unit-testing', 'xunit']",25,True,0,1
zsh: command not found: genhtml (Flutter + Code Coverage using Codemagic),"<p>I'm new in DevOps, I want to create <code>code coverage</code> from unit testing <code>result</code> in <code>Flutter</code>.</p>

<p>And this is our command to run that:</p>

<pre><code>flutter test --coverage &amp;&amp; genhtml coverage/lcov.info --output=coverage
</code></pre>

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

<pre><code>00:03 +1: All tests passed!                                                                                                                                                                         
zsh: command not found: genhtml
</code></pre>

<p>Does somebody know how to fix it? </p>

<p>And also when I running this:</p>

<pre><code>open coverage/index.html
</code></pre>

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

<pre><code>The file /Users/rrifafauzikomara/Documents/speed-interviews-flutter/coverage/index.html does not exist.
</code></pre>

<p>Does somebody know how to fix it? </p>

<p>This is my <a href=""https://blog.codemagic.io/flutter-unit-testing-bloc-with-codemagic/"" rel=""nofollow noreferrer"">tutorial</a> that I followed</p>
",https://stackoverflow.com/questions/61936414/zsh-command-not-found-genhtml-flutter-code-coverage-using-codemagic,"['flutter', 'code-coverage']",4845,True,3,1
Mocking Repositories to test Service in Spring,"<p>I occurred some failures after trying to mock repositories to unit test my services in Spring-Boot
Thats what I have (simplified)</p>

<pre class=""lang-java prettyprint-override""><code>

@ExtendWith(SpringExtension.class)
@ExtendWith(MockitoExtension.class)
@SpringBootTest
@ActiveProfiles(""test"")
public class UserTest{


    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepostiory userRepository;

    @Before
    public void setUp() {
       User user = new User(1L, ""email@email"", ""name"");
        when(userRepostitory.findById(1L)).thenReturn(Optional.of(user));
    }


    @Test
    public void findUserByIdReturnsUser() {

        User user = userService.getById(1L); =&gt; always throws error in Service, that no User is found with that Id, it calls the regular Repository: mock does nothing
        assertEquals(1L,user.getId());

    }
}
</code></pre>

<p>But I never get the User returned when the service calls the repo. I am kinda new to Unit Testing, and I am pretty sure, that I miss something here.</p>
",https://stackoverflow.com/questions/62100458/mocking-repositories-to-test-service-in-spring,"['spring', 'spring-boot', 'unit-testing', 'junit', 'spring-test']",2783,True,0,3
Jest detects open handle DNSCHANNEL if node package got is used,"<p>I'm programming server in <code>Node.js v12.18.3</code>, using <code>Express</code> framework. My code uses <code>Jest</code> for unit testing. In one of my module, I've used the <code>got</code> package. But it's not used in any unit test.</p>
<p>I've designed the following minimal test:</p>
<pre><code>const { app } = require('../app');
const { mongoose, database } = require('../database/database');
const api_dict = require(&quot;../api_dictionary&quot;);
var User = require('../models/user');

describe(&quot;===== POST &quot; + api_dict.users_create + &quot; Tests ===== &quot;, () =&gt; {

    var db;

    beforeAll(async () =&gt; {
        await mongoose.connect(database, { useNewUrlParser: true, useUnifiedTopology: true });
        db = mongoose.connection;
    });

    afterAll(async () =&gt; {
        await db.close();
    });

    test(&quot;Create user&quot;, () =&gt; {
    });
});
</code></pre>
<p>I'm using <code>jest --detectOpenHandles</code> command to detect open handles. Jest detected one:</p>
<pre><code>npm test

&gt; jetfire@0.0.0 test E:\Projects\github\project_name
&gt; cross-env NODE_ENV=test jest --detectOpenHandles

 PASS  tests/tests.js (8.118 s)
  ===== POST /user/create Tests =====
    √ Create user (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.196 s
Ran all test suites.

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  DNSCHANNEL

      at new CacheableLookup (node_modules/cacheable-lookup/source/index.js:75:14)
      at Object.&lt;anonymous&gt; (node_modules/got/dist/source/core/index.js:29:24)
      at Object.&lt;anonymous&gt; (node_modules/got/dist/source/as-promise/types.js:16:16)
</code></pre>
<p>How to ensure that this handle is closed when all unit tests are ran?</p>
",https://stackoverflow.com/questions/63577604/jest-detects-open-handle-dnschannel-if-node-package-got-is-used,"['node.js', 'unit-testing', 'jestjs']",845,False,3,0
SpringBoot Unit test - Service method is not invoked,"<p>I am new to Unit Testing. After referring google, I created a Test class to test my Controller as follows:</p>
<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(PromoController.class)
public class PromoApplicationTests {
    @Autowired
    protected MockMvc mvc;
    @MockBean PromoService promoService;
   
   
   protected String mapToJson(Object obj) throws Exception {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected &lt;T&gt; T mapFromJson(String json, Class&lt;T&gt; clazz)
      throws JsonParseException, JsonMappingException, IOException {
      
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
   
   @Test
    public void applyPromotionTest_1() throws Exception {
           String uri = &quot;/classPath/methodPath&quot;;
           List&lt;Cart&gt; cartLs = new ArrayList&lt;Cart&gt;();
          // added few objects to the list
           
           String inputJson = mapToJson(cartLs);
           MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
              .contentType(MediaType.APPLICATION_JSON).content(inputJson)).andReturn();
           
           int status = mvcResult.getResponse().getStatus();
           assertEquals(200, status);
           String actual = mvcResult.getResponse().getContentAsString();
           String expected = &quot;{\&quot;key1\&quot;:val1, \&quot;key2\&quot;:\&quot;val 2\&quot;}&quot;;
           assertEquals(expected, actual, true);
            
    }
}
</code></pre>
<p>I have the following Controller and service Class :</p>
<pre><code>@RequestMapping(&quot;/classPath&quot;)
@RestController
public class PromoController {
    @Autowired
    PromoService promoService;
    
    @PostMapping(&quot;/methodPath&quot;)
    public PromoResponse applyPromo(@RequestBody List&lt;Cart&gt; cartObj) {
        PromoResponse p = promoService.myMethod(cartObj);
        return p;
    }
}

@Component
public class PromoServiceImpl implements PromoService{

    @Override
    public PromoResponse myMethod(List&lt;Cart&gt; cartList) {
        // myCode
    }

}
</code></pre>
<p>When I debugged my unit test, p object in the controller was null.
I am getting status as 200 but not the expected JSON response</p>
<p>What am I missing here?</p>
",https://stackoverflow.com/questions/64048326/springboot-unit-test-service-method-is-not-invoked,"['java', 'spring-boot', 'spring-boot-test']",520,True,3,1
Real method getting executed inspite of mocking,"<p>I am new to Java unit testing and started using Mockito. I am using doNothing.... but the real method get always executed. Not sure what I am missing.</p>

<pre><code>public abstract class MyApplication {
     private Square s;
     private Circle c;

     public MyApplication(Square s, Circle c){
       this.s = s;
       this.c = c;
     }    
     public void firstMethod() {
       System.out.println(""Starting first Method"");
       secondMethod();
       System.out.println(""Ending first Method"");
     }

     public void secondMethod() {
       //some business logic here
     }

}

public class SmallApplication extends MyApplication {
     private Square s;
     private Circle c;

     public SmallApplication(Square s, Circle c){
       this.s = s;
       this.c = c;
     }
}

public class MyApplicationTest {

    public void testFirstMethod() {
      Square smock = mock(Square.class);
      Circle cmock = mock(Circle.class);
      SmallApplication app = new SmallApplication(smock, cmock);
      SmallApplication appSpy = spy(app);
      doNothing().when(appSpy).secondMethod();
      appSpy.firstMethod();
   }
}
</code></pre>

<p>I donot want seconMethod's business logic to be executed but with the above code the second method business logic is always executed. Please help out.</p>
",https://stackoverflow.com/questions/61458800/real-method-getting-executed-inspite-of-mocking,['mockito'],55,False,0,0
Testing vue component with dispatching action in created hook,"<p>i have problem in unit testing in vue js. i'm using vue-test-utils and jest. </p>

<p>error:
<a href=""https://i.stack.imgur.com/Femrt.png"" rel=""nofollow noreferrer"">Image error</a></p>

<p>this is my test:</p>

<pre><code>import { mount, createLocalVue } from ""@vue/test-utils"";
import Vuex from ""vuex"";
import Home from ""@/views/Home"";

const localVue = createLocalVue();
localVue.use(Vuex);

describe(""Home.vue"", () =&gt; {
  let store;
  let actions;

  beforeEach(() =&gt; {
    actions = {
      DISPATCH: jest.fn()
    };

    store = new Vuex.Store({
      actions
    });
  });

  it(""should dispatch action when created"", () =&gt; {
    const wrapper = mount(Home, {
      localVue,
      store
    });
    expect(wrapper.DISPATCH).toHaveBeenCalled();
  });
});

</code></pre>

<p>and this is my component:</p>

<pre><code>&lt;script&gt;
import { mapGetters } from ""vuex"";

import { FETCH_MUSICS } from ""@/store/types/action-types"";
import { GET_LOADING } from ""@/store/types/getter-types"";
import { MUSIC } from ""@/store/types/types"";

import Musics from ""@/components/pages/home/Musics"";

export default {
  name: ""Home"",
  components: {
    Musics
  },
  computed: {
    ...mapGetters({
      loading: `${MUSIC}/${GET_LOADING}`
    })
  },
  created() {
    this.$store.dispatch(`${MUSIC}/${FETCH_MUSICS}`);
  }
};
&lt;/script&gt;
</code></pre>

<p>as you see, i use types and i think because of this i get error. how can i solve that?</p>

<p>thanks for helping me :)</p>
",https://stackoverflow.com/questions/62392614/testing-vue-component-with-dispatching-action-in-created-hook,"['vue.js', 'testing', 'jestjs', 'vue-test-utils']",2043,False,0,1
Unit testing axios.mockImplementation calls keeps giving me unchanged state?,"<p>I'm still trying to learn unit testing and I've used a lot of guides, but for some reason in regards to axios testing, I'm messing up. </p>

<p>Note: I have ""jest.mock(""axios"");"" already set at the top of my testpage </p>

<pre><code>getUserInfo = async () =&gt; {
  let authToken =
        ""Bearer "" + Cookies.get(""auth-token"").replace(""__#__"", ""."");

    const instance = await axios.create({
        baseURL: ""http://127.0.0.1:8000/"",
        timeout: 8000,
        headers: {
            ""Content-Type"": ""application/json"",
            ""X-Requested-With"": ""XMLHttpRequest"",
            Authorization: authToken
        }
    });

    instance
        .get(""api/userinfo"")
        .then(json =&gt; {
            this.setState({
                user: json.data
            });
        })
        .catch(error =&gt; console.log(error));
};

componentDidMount() {
    this.getUserInfo();
}
</code></pre>

<p>and my testing is :</p>

<pre><code>  it(""fetches data correctly"", async () =&gt; {  

    const userJSON = {
        data: {
            name: ""John Doe"",
            email: ""johndoe@mail.com"",
            phone_number: ""123-456-7890"",
            profile_url: ""url""
        }
    };


    axios.get.mockImplementationOnce(() =&gt; Promise.resolve({ userJSON }));

    const instance = await renderer.create(&lt;ProfilePage /&gt;).getInstance();
    expect(instance.state.user).toEqual(userJSON)}
</code></pre>

<p>and this is the output of the test which fails: </p>

<pre><code>Expected: {""data"": {""email"": ""johndoe@mail.com"", ""name"": ""John Doe"", ""phone_number"": ""123-456-7890"", ""profile_url"": ""url""}}
Received: []
</code></pre>
",https://stackoverflow.com/questions/61181344/unit-testing-axios-mockimplementation-calls-keeps-giving-me-unchanged-state,"['javascript', 'reactjs', 'unit-testing', 'mocking', 'axios']",301,True,0,1
How to unit test service configuration with NUnit?,"<p>I have the following in my Startup.cs file and want to know if there's any way to unit test using NUnit? </p>

<pre><code>public void ConfigureServices(IServiceCollection services)
{
        services.TryAddSingleton&lt;IUserValidator, UserValidator&gt;();
        services.TryAddSingleton&lt;IPolicyValidator, PolicyValidator&gt;();
        services.TryAddSingleton&lt;IAccountValidator, AccountValidator&gt;();
}
</code></pre>

<p>As a result of no test coverage this file is failing Sonar Cloud code quality gates because it's untested but I am not sure how to go about unit testing this? </p>
",https://stackoverflow.com/questions/61779143/how-to-unit-test-service-configuration-with-nunit,"['c#', '.net-core', 'nunit']",480,False,0,0
How to validate antd form fields using jest/enzyme while simulating submit click,"<p>I am using jest and enzyme for unit testing. I have a login form and now wants to write test cases for it. How can I validate the values I have passed. Suppose I simulate email field with abc@gmail.com. I need to check these values at the time of submitting the form.</p>
",https://stackoverflow.com/questions/63264767/how-to-validate-antd-form-fields-using-jest-enzyme-while-simulating-submit-click,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'antd']",2020,True,0,1
React-native + ts-jest + enzyme hanging after test complete,"<p>I'm creating unit testing for a React native application, and what happens is, after the test initiate , it hangs , without any response from the terminal . I've tried to use <code>--forceExit</code> , <code>--detectOpenHandles</code> to log any problem. but the terminal continues as follow:</p>

<p><a href=""https://i.stack.imgur.com/Py340.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Py340.png"" alt=""jest terminal run""></a>
I've Intellij IDE , and running the same test on it I've this result</p>

<p><a href=""https://i.stack.imgur.com/YEngW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/YEngW.png"" alt=""intellij test""></a></p>

<p>Note that where is written <code>Running Tests...</code> it's shows a loading icon, the test continues running on Intellij even after the test were completed.</p>

<p>here's the code of my testing :</p>

<pre><code>/**
 * @jest-environment jsdom
 */
import React from 'react';
import { mount, ReactWrapper, shallow } from 'enzyme';
import AnotherComponent from 'components/AnotherComponent';
// @ts-ignore
import { mocking } from './helpers/mockedTheme';
import TestComponent from 'components/TestComponent';

export const shallowWithTheme = (children: any) =&gt; (
  // @ts-ignore
  shallow(children, { mocking })
);

describe('Test Components', () =&gt; {
  describe('Test Component', ()=&gt;{
    it('Test shallow with theme', () =&gt; {
      const element = shallowWithTheme(&lt;TestComponent componentProp={""test""}/&gt;);
      //@ts-ignore
      expect(element).toExist();
    });
  });
  describe('Test AnotherComponent', () =&gt;{
    it('AnotherComponent with button', () =&gt; {
      const wrapper = shallowWithTheme(
        &lt;AnotherComponent  icon=""qr-code""
                         title='component title'
                         description='component description'
                         buttonText='go'
      /&gt;);
      // @ts-ignore
      expect(wrapper).toExist();
    });

    it('AnotherComponent without button', () =&gt; {
      const wrapper = shallow(
        &lt;AnotherComponent  icon=""qr-code""
                         title='component title'
                         description='component description'
        /&gt;);
      //@ts-ignore
      expect(wrapper).toExist();
    });
  });
});
</code></pre>

<p>The components <code>AnotherComponent</code> and <code>TestComponent</code> are nested with another styled.components eg,:</p>

<pre><code>\\ TestComponent
import React from 'react';
import { MainContentView } from 'components/TestComponent/TestComponent.styles';
import { throwJSError } from 'reduxRoot/util/error';
import { withTheme } from 'styled-components/native';
import { Text } from 'react-native';

class TestComponent extends React.Component {
  render() {
    try {
      return (
            &lt;MainContentView&gt;
              &lt;Text&gt;Text&lt;/Text&gt;
            &lt;/MainContentView&gt;
      );
    } catch (err) {
      throwJSError(err, 'TestComponent/render');
      return null;
    }
  }
}

export default withTheme(TestComponent);
</code></pre>

<p>The style <code>MainContentView</code> is a styled.component eg.:
<code>export const MainContentView = styled.View` flex: 1; backgroundColor: #FFFFFF;`;</code></p>

<p>here my jest ---debug</p>

<pre><code>{
  ""configs"": [
    {
      ""automock"": false,
      ""browser"": false,
      ""cache"": true,
      ""cacheDirectory"": ""/private/var/folders/rk/rnc3852s3y56rx7bypry2qz92b2nhd/T/jest_j25hjh"",
      ""clearMocks"": false,
      ""coveragePathIgnorePatterns"": [
        ""/node_modules/""
      ],
      ""cwd"": ""&lt;root-to-my-project&gt;"",
      ""dependencyExtractor"": null,
      ""detectLeaks"": false,
      ""detectOpenHandles"": true,
      ""errorOnDeprecated"": false,
      ""filter"": null,
      ""forceCoverageMatch"": [],
      ""globalSetup"": null,
      ""globalTeardown"": null,
      ""globals"": {
        ""ts-jest"": {
          ""babelConfig"": true,
          ""isolatedModules"": true
        }
      },
      ""haste"": {
        ""defaultPlatform"": ""ios"",
        ""platforms"": [
          ""android"",
          ""ios"",
          ""native""
        ],
        ""hasteImplModulePath"": ""&lt;root-to-my-project&gt;/node_modules/react-native/jest/hasteImpl.js"",
        ""providesModuleNodeModules"": [
          ""react-native""
        ]
      },
      ""moduleDirectories"": [
        ""node_modules""
      ],
      ""moduleFileExtensions"": [
        ""js"",
        ""json"",
        ""jsx"",
        ""ts"",
        ""tsx"",
        ""node""
      ],
      ""moduleNameMapper"": [
        [
          ""reduxRoot(.*)$"",
          ""&lt;root-to-my-project&gt;/redux$1""
        ],
        [
          ""screens(.*)$"",
          ""&lt;root-to-my-project&gt;/src/screens$1""
        ],
        [
          ""^React$"",
          ""&lt;root-to-my-project&gt;/node_modules/react/index.js""
        ]
      ],
      ""modulePathIgnorePatterns"": [
        ""&lt;root-to-my-project&gt;/node_modules/react-native/Libraries/react-native/""
      ],
      ""name"": ""a1c9dcb3024a2c47c9517df7e59341e3"",
      ""prettierPath"": ""prettier"",
      ""resetMocks"": false,
      ""resetModules"": false,
      ""resolver"": null,
      ""restoreMocks"": false,
      ""rootDir"": ""&lt;root-to-my-project&gt;"",
      ""roots"": [
        ""&lt;root-to-my-project&gt;""
      ],
      ""runner"": ""jest-runner"",
      ""setupFiles"": [
        ""&lt;root-to-my-project&gt;/node_modules/react-native/jest/setup.js"",
        ""&lt;root-to-my-project&gt;/native/node_modules/react-native-gesture-handler/jestSetup.js""
      ],
      ""setupFilesAfterEnv"": [
        ""&lt;root-to-my-project&gt;/jest.setup.js""
      ],
      ""skipFilter"": false,
      ""snapshotSerializers"": [],
      ""testEnvironment"": ""&lt;root-to-my-project&gt;/node_modules/jest-environment-node/build/index.js"",
      ""testEnvironmentOptions"": {},
      ""testLocationInResults"": false,
      ""testMatch"": [
        ""**/__tests__/*.(ts|tsx|js)""
      ],
      ""testPathIgnorePatterns"": [
        ""/node_modules/""
      ],
      ""testRegex"": [],
      ""testRunner"": ""&lt;root-to-my-project&gt;/node_modules/jest-jasmine2/build/index.js"",
      ""testURL"": ""http://localhost"",
      ""timers"": ""real"",
      ""transform"": [
        [
          ""^.+\\.tsx?$"",
          ""&lt;root-to-my-project&gt;/node_modules/ts-jest/dist/index.js""
        ],
        [
          ""\\.js$"",
          ""&lt;root-to-my-project&gt;/node_modules/react-native/jest/preprocessor.js""
        ],
        [
          ""^.+\\.(js|ts|tsx)$"",
          ""&lt;root-to-my-project&gt;/node_modules/babel-jest/build/index.js""
        ],
        [
          ""^.+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$"",
          ""&lt;root-to-my-project&gt;/node_modules/react-native/jest/assetFileTransformer.js""
        ]
      ],
      ""transformIgnorePatterns"": [
        ""node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community)""
      ],
      ""watchPathIgnorePatterns"": []
    }
  ],
  ""globalConfig"": {
    ""bail"": 0,
    ""changedFilesWithAncestor"": false,
    ""collectCoverage"": false,
    ""collectCoverageFrom"": null,
    ""coverageDirectory"": ""&lt;root-to-my-project&gt;/coverage"",
    ""coverageReporters"": [
      ""json"",
      ""text"",
      ""lcov"",
      ""clover""
    ],
    ""coverageThreshold"": null,
    ""detectLeaks"": false,
    ""detectOpenHandles"": true,
    ""errorOnDeprecated"": false,
    ""expand"": false,
    ""filter"": null,
    ""globalSetup"": null,
    ""globalTeardown"": null,
    ""json"": false,
    ""listTests"": false,
    ""maxConcurrency"": 5,
    ""maxWorkers"": 3,
    ""noStackTrace"": false,
    ""nonFlagArgs"": [],
    ""notify"": false,
    ""notifyMode"": ""failure-change"",
    ""passWithNoTests"": false,
    ""projects"": null,
    ""rootDir"": ""&lt;root-to-my-project&gt;"",
    ""runTestsByPath"": false,
    ""skipFilter"": false,
    ""testFailureExitCode"": 1,
    ""testPathPattern"": """",
    ""testResultsProcessor"": null,
    ""testSequencer"": ""&lt;root-to-my-project&gt;/node_modules/@jest/test-sequencer/build/index.js"",
    ""updateSnapshot"": ""new"",
    ""useStderr"": false,
    ""verbose"": true,
    ""watch"": false,
    ""watchman"": true
  },
  ""version"": ""24.9.0""
}
</code></pre>

<p>And last but not least , my jest.setup.js to mock all I need to run my enviroment:</p>

<pre><code>import { NativeModules } from 'react-native';
import 'jest-styled-components';
import 'react-native';
import 'jest-enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { configure } from 'enzyme';

/**
 * Set up Enzyme to mount to DOM, simulate events,
 * and inspect the DOM in tests.
 */
configure({ adapter: new Adapter() });


/**
 * Set up DOM in node.js environment for Enzyme to mount to
 */
const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('&lt;!doctype html&gt;&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;');
const { window } = jsdom;

function copyProps(src, target) {
  Object.defineProperties(target, {
    ...Object.getOwnPropertyDescriptors(src),
    ...Object.getOwnPropertyDescriptors(target),
  });
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
copyProps(window, global);

jest.mock('react-navigation/src/routers/KeyGenerator', () =&gt; ({
  generateKey: jest.fn(() =&gt; 123),
}));

jest.mock('./node_modules/react-native-reanimated/src/ReanimatedEventEmitter');
jest.mock('./node_modules/react-native-reanimated/src/ReanimatedModule');

jest.mock('react-native-gesture-handler', () =&gt;({
  State: jest.fn(),
  TapGestureHandler: jest.fn()
}));

NativeModules.RNCNetInfo = {
  getCurrentState: jest.fn(() =&gt; Promise.resolve()),
  addListener: jest.fn(),
  removeListeners: jest.fn()
};

jest.mock('react-native-device-info', () =&gt; {
  return {
    getVersion: jest.fn(() =&gt; Promise.resolve('1.0')),
    getApplicationName: jest.fn(() =&gt; Promise.resolve('My App')),
    getModel: jest.fn(() =&gt; Promise.resolve('iPhone 11')),
    hasNotch: jest.fn(),
  };
});

jest.mock('services/theme/scaling', () =&gt; ({
    scale: jest.fn()
  })
);

jest.mock('services/theme/styles', () =&gt; ({
    themeVal: jest.fn()
  })
);


NativeModules.StatusBarManager = {
  HEIGHT : 20,
  getHeight: jest.fn()
};

NativeModules.ParentBridge ={
  partnerId: jest.fn()
};

NativeModules.CTNConfig =  { buildEnvironment: 'Development'};
</code></pre>

<p>So. Has someone knows how to configure properly my code to be able to see my unit testing finishing and not hanging anymore?</p>

<p>ps.: I've note I've recieving a warning message, don't know this is related on the reasons the test is hanging:</p>

<pre><code>    Warning: Async Storage has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '@react-native-community/async-storage' instead of 'react-native'. See https://github.com/react-native-community/react-native-async-storage```
</code></pre>
",https://stackoverflow.com/questions/59738078/react-native-ts-jest-enzyme-hanging-after-test-complete,"['unit-testing', 'react-native', 'jestjs', 'enzyme']",499,False,4,0
Spark scala mocking spark.implicits for unit testing,"<p>When trying to simplify unit testing with Spark and Scala, I am using scala-test and mockito-scala (and mockito sugar). This simply lets you do something like this:</p>
<pre><code>val sparkSessionMock = mock[SparkSession]
</code></pre>
<p>Then you can usually do all the magic with &quot;when&quot; and &quot;verify&quot;.</p>
<p>But if you have some implementations that has the necessary import of</p>
<pre><code>import spark.implicits._
</code></pre>
<p>in its code, then the simplicity of unit testing seems to be gone (or at least I didn't find the most proper way to solve this, yet).</p>
<p>I end up in getting this error:</p>
<pre><code>org.mockito.exceptions.verification.SmartNullPointerException: 
You have a NullPointerException here:
-&gt; at ...
because this method call was *not* stubbed correctly:
-&gt; at scala.Option.orElse(Option.scala:289)
sparkSession.implicits();
</code></pre>
<p>Simply mocking the call on the &quot;implicits&quot; object inside SparkSession won't help due to typing issues:</p>
<pre><code>val implicitsMock = mock[SQLImplicits]
when(sparkSessionMock.implicits).thenReturn(implicitsMock)
</code></pre>
<p>will not let you pass, since it says it will require the type of the object inside your mock:</p>
<pre><code>require: sparkSessionMock.implicits.type
found: implicitsMock.type
</code></pre>
<p>And please don't tell me that I should rather do SparkSession.builder.getOrCreate()... since then this isn't a unit-test anymore but a more heavy weight integration test.</p>
<p>(Edit): here is a complete reproducible example:</p>
<pre><code>import org.apache.spark.sql._
import org.mockito.Mockito.when
import org.scalatest.{ FlatSpec, Matchers }
import org.scalatestplus.mockito.MockitoSugar

case class MyData(key: String, value: String)

class ClassToTest()(implicit spark: SparkSession) {
    import spark.implicits._

    def read(path: String): Dataset[MyData] = 
         spark.read.parquet(path).as[MyData]
}

class SparkMock extends FlatSpec with Matchers with MockitoSugar {

     it should &quot;be able to mock spark.implicits&quot; in {
         implicit val sparkMock: SparkSession = mock[SparkSession]
         val implicitsMock = mock[SQLImplicits]
         when(sparkMock.implicits).thenReturn(implicitsMock)
         val readerMock = mock[DataFrameReader]
         when(sparkMock.read).thenReturn(readerMock)
         val dataFrameMock = mock[DataFrame]
         when(readerMock.parquet(&quot;/some/path&quot;)).thenReturn(dataFrameMock)
         val dataSetMock = mock[Dataset[MyData]]
         implicit val testEncoder: Encoder[MyData] = Encoders.product[MyData]
         when(dataFrameMock.as[MyData]).thenReturn(dataSetMock)

         new ClassToTest().read(&quot;/some/path/&quot;) shouldBe dataSetMock
    }
 }
</code></pre>
",https://stackoverflow.com/questions/64539412/spark-scala-mocking-spark-implicits-for-unit-testing,"['scala', 'unit-testing', 'apache-spark', 'mockito', 'implicit']",2980,True,4,1
How to trigger ngModelChange event in Jasmine unit testing?,"<p>I am using below code to perform unit testing by using Jasmine in Angular application.</p>
<p><strong>test.component.html:</strong></p>
<pre><code>&lt;p-treeTable [value]=&quot;employees&quot; [columns]=&quot;cols&quot; class=&quot;employeestreetable&quot;&gt;
    &lt;ng-template pTemplate=&quot;header&quot; let-columns&gt;
        &lt;tr&gt;
            &lt;th *ngFor=&quot;let col of cols&quot; style=&quot;width:30px&quot;&gt;
                {{col.header}}
            &lt;/th&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
    &lt;ng-template pTemplate=&quot;body&quot; let-rowNode let-rowData=&quot;rowData&quot;  let-columns=&quot;columns&quot;&gt;
        &lt;tr [ttRow]=&quot;rowNode&quot;&gt;
            &lt;td width=&quot;30&quot; class=&quot;text-right&quot; ttEditableColumn&gt; 
              &lt;p-treeTableToggler [rowNode]=&quot;rowNode&quot;&gt;
                    &lt;/p-treeTableToggler&gt;
                &lt;p-treeTableCellEditor&gt;
                    &lt;ng-template pTemplate=&quot;input&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['name']&quot; /&gt;
                    &lt;/ng-template&gt;
                    &lt;ng-template pTemplate=&quot;output&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['name']&quot;&gt;
                     &lt;/ng-template&gt;
                &lt;/p-treeTableCellEditor&gt;
             &lt;/td&gt; 
             &lt;td width=&quot;30&quot; class=&quot;text-right&quot;&gt;
                &lt;p-treeTableCellEditor&gt;
                    &lt;ng-template pTemplate=&quot;input&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['salary']&quot; (ngModelChange)=&quot;calculateTotalSalary(rowNode)&quot; /&gt;
                    &lt;/ng-template&gt;
                    &lt;ng-template pTemplate=&quot;output&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['salary']&quot;&gt;
                     &lt;/ng-template&gt;
                &lt;/p-treeTableCellEditor&gt;
             &lt;/td&gt;
             &lt;td width=&quot;30&quot; class=&quot;text-right&quot; ttEditableColumn&gt;
                &lt;p-treeTableCellEditor&gt;
                    &lt;ng-template pTemplate=&quot;input&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['incentive']&quot;  (ngModelChange)=&quot;calculateTotalSalary(rowNode)&quot; /&gt;
                    &lt;/ng-template&gt;
                    &lt;ng-template pTemplate=&quot;output&quot;&gt;
                        &lt;input type=&quot;text&quot; pInputText [(ngModel)]=&quot;rowData['incentive']&quot;&gt;
                     &lt;/ng-template&gt;
                &lt;/p-treeTableCellEditor&gt;
             &lt;/td&gt;
             &lt;td width=&quot;30&quot; class=&quot;text-right&quot;&gt;
               &lt;span&gt;{{rowData['totalsalary']}}&lt;/span&gt;
              &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
&lt;/p-treeTable&gt; 
</code></pre>
<p><strong>test.component.ts:</strong></p>
<pre><code>import { Component, OnInit, ViewChild } from '@angular/core';
import { TreeNode } from 'primeng/primeng'
import { ChangeDetectorRef } from '@angular/core';
@Component({
  selector: 'test-app',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {
  cols = [
    { field: 'name', header: 'Name' },
    { field: 'salary', header: 'Salary' },
    { field: 'incentive', header: 'Incentive' },
    { field: 'totalsalary', header: 'Total Salary' }
  ];
  employees: TreeNode[] = [
    {
      &quot;data&quot;: {
        &quot;name&quot;: &quot;Alex&quot;,
        &quot;salary&quot;: 10000,
        &quot;incentive&quot;: 5000,
        &quot;totalsalary&quot;: 15000
      },
      &quot;children&quot;: [
        {
          &quot;data&quot;: {
            &quot;name&quot;: &quot;George&quot;,
            &quot;salary&quot;: 8000,
            &quot;incentive&quot;: 2000,
            &quot;totalsalary&quot;: 10000
          },
        }
      ]
    },
    {
      &quot;data&quot;: {
        &quot;name&quot;: &quot;Robert&quot;,
        &quot;salary&quot;: 18000,
        &quot;incentive&quot;: 10000,
        &quot;totalsalary&quot;: 280000
      },
      &quot;children&quot;: [
        {
          &quot;data&quot;: {
            &quot;name&quot;: &quot;John&quot;,
            &quot;salary&quot;: 7000,
            &quot;incentive&quot;: 5000,
            &quot;totalsalary&quot;: 12000
          }
        }
      ]
    }
  ];
  calculateTotalSalary(rownode) {
    rownode.node.data.totalsalary = +rownode.node.data.salary + +rownode.node.data.incentive;
  }
}
</code></pre>
<p><strong>test.component.spec.ts:</strong></p>
<pre><code>import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {
    TestComponent
} from &quot;./test.component&quot;;
import { FormsModule, NgModel } from '@angular/forms';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MessageService } from 'primeng/api';
import { TreeNode } from 'primeng/api';
import { TreeTableModule } from 'primeng/treetable';
import { By } from '@angular/platform-browser';
import { InputTextModule } from 'primeng/inputtext';
describe('TestComponent', () =&gt; {
  let component: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;;
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule,
      FormsModule, TreeTableModule, InputTextModule
      ],
      declarations: [ TestComponent ],
      providers: [ ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  beforeEach(fakeAsync(() =&gt; {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    tick();
  }));
  it('should update total salary amount', fakeAsync(() =&gt; {
    spyOn(component, 'calculateTotalSalary');
    const editableTreeTableEl = fixture.debugElement.query(By.css(&quot;.employeestreetable&quot;));
    let editableColumns = editableTreeTableEl.queryAll(By.css(&quot;.ui-editable-column input&quot;));
    const el = editableColumns[0].nativeElement;
    const ngModel = editableColumns[0].injector.get(NgModel);
    tick();
    ngModel.valueAccessor.writeValue(25000);
    el.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    expect(component.calculateTotalSalary).toHaveBeenCalled(); //failing here
    expect(+el.value).toEqual(25000);
  }));
});
</code></pre>
<p><strong>Demo:</strong>
<a href=""https://stackblitz.com/edit/test-jasmine-karma-t7khzp?file=app%2Ftest.component.html"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/test-jasmine-karma-t7khzp?file=app%2Ftest.component.html</a></p>
<p>I am updating salary amount in above unit test case. How to trigger related ngModelChange event when I update ngModel value from above unit test case?</p>
",https://stackoverflow.com/questions/63908650/how-to-trigger-ngmodelchange-event-in-jasmine-unit-testing,"['angular', 'jasmine', 'karma-jasmine', 'karma-runner']",4540,True,1,1
How to write unit tests for gremlin queries in Java?,"<p>for example connecting to client:</p>
<pre><code>val client = Cluster.open(MapConfiguration(config)).connect()
</code></pre>
<p>and executing the query</p>
<pre><code>client.submitAsync(PreparedStatement.addUser, map).await().all().join()
</code></pre>
<p><code>PreparedStatement.addUser</code> - gremlin string</p>
<p>The question is: how to unit test client queries in Java. I thought of unit testing our queries with <code>inMemoryDB</code>. Can we run <code>inMemoryDB</code> as a client, because by default return <code>traversal()</code> if connecting to memory DB? Or can we execute a gremlin query string on <code>traversal</code>?</p>
",https://stackoverflow.com/questions/64021368/how-to-write-unit-tests-for-gremlin-queries-in-java,"['unit-testing', 'gremlin', 'janusgraph', 'gremlin-server']",1094,True,1,1
Why my mocked service property is undefined in Jasmine unit test?,"<p>Im learning Angular unit testing with Jasmine. I am following <a href=""https://angular.io/guide/testing-services"" rel=""nofollow noreferrer"">documentation`s guide for testing services</a>, but for another service from the tutorial, also very simple.</p>
<p>SUT:</p>
<pre><code>import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { MessageService } from './message.service';

@Injectable({ providedIn: 'root' })
export class HeroService {

  constructor(private messageService: MessageService) { }

  getHeroes(): Observable&lt;Hero[]&gt; {
    // TODO: send the message _after_ fetching the heroes
    this.messageService.add('HeroService: fetched 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));
  }
}
</code></pre>
<p>And injected MessageService:</p>
<pre><code>import { HeroService } from './hero.service';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class MessageService {
  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}
</code></pre>
<p>As per guide, I mocked injected service using <code>createSpyObj</code> and called <code>getHeroes</code> of the SUT:</p>
<pre><code>import { MessageService } from './message.service';
import { HeroService } from './hero.service';

describe('HeroService without Angular testing support', () =&gt; {
  let heroService: HeroService;
  let messageServiceSpy: MessageService;

  it('#getHeroes should add message to MessageService', () =&gt; {
    //prepare
    messageServiceSpy = jasmine.createSpyObj(
      'MessageService',
      ['add'],
      ['messages']
    );
    heroService = new HeroService(messageServiceSpy);
    messageServiceSpy.messages = ['one', 'two'];//only difference with the guide

    //act
    heroService.getHeroes();

    //assert
    expect(messageServiceSpy.messages.length).toBe(3);
    expect(messageServiceSpy.messages[2]).toBe('HeroService: fetched heroes');
  });
});
</code></pre>
<p>Because of some reason, when testing, <code>messageServiceSpy.messages</code> is <code>undefined</code>:</p>
<pre><code>TypeError: Cannot read property 'length' of undefined
</code></pre>
<p>What Im doing wrong?</p>
",https://stackoverflow.com/questions/64061277/why-my-mocked-service-property-is-undefined-in-jasmine-unit-test,"['angular', 'unit-testing', 'mocking', 'jasmine']",1041,True,1,1
How to do a Mockito Unit Testing on ViewModel in Kotlin,"<p>I am so clueless of my submission with is the Mockito Unit Testing for the Live Data from the ViewModels in Kotlin language. Here are some codes. I hope that I could test the live data from inside of the viewmodel using verify on change with observers.</p>

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

val nextMatchList = MutableLiveData&lt;ArrayList&lt;Events&gt;&gt;()

fun setNextMatchList(id: Int) {
    val retrofit = Retrofit.Builder()
        .baseUrl(""https://www.thesportsdb.com/"")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val api = retrofit.create(ApiService::class.java)

    api.getNextMatch(id).enqueue(object : Callback&lt;EventsArray&gt; {
        override fun onResponse(call: Call&lt;EventsArray&gt;, response: Response&lt;EventsArray&gt;) {

            val results = response.body()
            val eventsList: ArrayList&lt;Events&gt;?
            eventsList = results!!.events as ArrayList&lt;Events&gt;?

            nextMatchList.postValue(eventsList)
        }

        override fun onFailure(call: Call&lt;EventsArray&gt;, t: Throwable) {
            Log.d(""ysuf"", ""onFailure "" + t.message)
        }

    })
}

fun getLiveData(): MutableLiveData&lt;ArrayList&lt;Events&gt;&gt; {
    return nextMatchList
 }
}
</code></pre>

<p>Thank you very much for the answer !</p>
",https://stackoverflow.com/questions/59773391/how-to-do-a-mockito-unit-testing-on-viewmodel-in-kotlin,"['unit-testing', 'kotlin', 'mvvm', 'mockito', 'viewmodel']",81,False,1,0
Unable to mark directory as Test Sources in Pycharm for javascript,"<p>I have installed <code>node.js</code> and <code>nodeunit</code> on my computer. Now I am following the instructions from <code>JetBrains</code> on creating unit tests here <a href=""https://www.jetbrains.com/help/pycharm/unit-testing-node-js.html"" rel=""nofollow noreferrer"">https://www.jetbrains.com/help/pycharm/unit-testing-node-js.html</a>:</p>

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

<p>Specifically this step: <code>Mark the _tests_ as a ""test directory""</code> : that option is not available for some reason from the right click/context menu:</p>

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

<p>What is missing so that that option would be available?</p>
",https://stackoverflow.com/questions/59925280/unable-to-mark-directory-as-test-sources-in-pycharm-for-javascript,"['node.js', 'unit-testing', 'pycharm']",115,True,1,1
Unit test for Highcharts tooltip in Angular,"<p>I am using <a href=""https://api.highcharts.com/highcharts/"" rel=""nofollow noreferrer"">Highcharts API</a> in Angular 7+.</p>

<p>Suppose in some component, my chart type is '<strong>area</strong>' and my <strong>tooltip</strong> code is as follows:</p>

<pre class=""lang-js prettyprint-override""><code>tooltip:{
    shared : true,
    outside : true,
    useHTML : true,
    formatter(){
        let str = `&lt;table&gt;`;
        this.points.forEach((point)=&gt;{
            str = str.concat(
                `&lt;tr&gt;
                    &lt;td style=""color: ${point.series.color};font-size: 0.9em""&gt;&lt;/td&gt;
                &lt;/tr&gt;
                `
                );

            str = str.concat('&lt;/table&gt;');
            return str;
        })
    }
}
</code></pre>

<p>Now while unit testing this component, the code coverage was not 100% and in the index.html file it showed the tooltip part is not covered. How to check for the same ?</p>
",https://stackoverflow.com/questions/61163742/unit-test-for-highcharts-tooltip-in-angular,"['angular', 'unit-testing', 'highcharts']",2921,True,1,2
Gradle run flywayMigration during unit tests,"<p>I am working on spring boot/gradle project and for some reason, Gradle run flywayMigrate task during Unit testing, so it failed with.</p>

<pre><code>Error occurred while executing flywayMigrate. Connection refused 
</code></pre>

<p>I run tests with <em>./gradlew clean test</em></p>

<p>My <em>build.gradle</em> file:</p>

<pre><code>plugins {
    id 'org.springframework.boot' version '2.2.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
    id 'nu.studer.jooq' version '4.1'
    id ""org.flywaydb.flyway"" version ""6.2.0""
}

group = 'com.test'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

ext {
    dbUrl = ""jdbc:postgresql://localhost:5432/test""
    dbUsername = 'admin'
    dbPassword = 'admin'
    dbDriver = 'org.postgresql.Driver'
    dbSchema = 'public'
}

repositories {
    mavenCentral()
}


dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-jooq'
    implementation 'io.jsonwebtoken:jjwt:0.9.1'
    implementation 'javax.xml.bind:jaxb-api:2.3.0'
    implementation 'org.flywaydb:flyway-core'
    implementation 'org.postgresql:postgresql:42.2.9'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'org.postgresql:postgresql'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    jooqRuntime 'org.postgresql:postgresql:42.2.9'
    compile 'org.jooq:jooq'
}

test {
    useJUnit()
}

jooq {
    version = '3.11.0'
    edition = 'OSS'
    sample(sourceSets.main) {
        jdbc {
            driver = dbDriver
            url = dbUrl
            user = dbUsername
            password = dbPassword
            schema = dbSchema
        }
        generator {
            database {
                inputSchema = dbSchema
                excludes = 'databasechangelog|databasechangeloglock'
            }
            generate {
                relations = false
                deprecated = false
                records = true
                immutablePojos = false
                fluentSetters = false
                javaTimeTypes = true
            }
            target {
                directory = 'build/generated/sources/jooq'
                packageName = 'com.test.generated.models'
            }
        }
    }
}

flyway {
    url = dbUrl
    user = dbUsername
    password = dbPassword
    schemas = [dbSchema]
    locations = [""filesystem:$project.projectDir/src/main/resources/db/migration""]
}

generateSampleJooqSchemaSource.dependsOn flywayMigrate
</code></pre>

<p>I don't try to run integration tests. Just units, so I don't need db connection there. FlywayMigration work well with <em>gradlew bootRun</em></p>
",https://stackoverflow.com/questions/61465228/gradle-run-flywaymigration-during-unit-tests,"['java', 'spring-boot', 'unit-testing', 'gradle', 'flyway']",1293,True,1,1
Testing react app with jest and enzyme token problem,"<p>I have a react app in which I have added unit testing, but one of my tests fails,</p>
<p>Here is my test file, I want to test action creators <code>getUser</code>.</p>
<p><a href=""https://i.stack.imgur.com/P8YtM.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/P8YtM.png"" alt=""enter image description here"" /></a></p>
<p>When I run <code>npm test</code> I get the following error,</p>
<pre><code>FAIL   UnitTests  resources/js/tests/actions/index.test.js

  ● Test suite failed to run

    TypeError: Cannot read property 'getAttribute' of null

       8 |              'Accept': 'application/json',
       9 |              'Content-Type': 'application/json',
    &gt; 10 |              'X-CSRF-TOKEN': document.querySelector('meta[name=&quot;csrf-token&quot;]').getAttribute('content')
         |                              ^
      11 |      },
      12 | });
      13 | 

      at Object.&lt;anonymous&gt; (utils/api.js:10:19)
      at Object.&lt;anonymous&gt; (store/actions/userActions.js:2:1)
      at Object.&lt;anonymous&gt; (store/actions/index.js:2:1)
      at Object.&lt;anonymous&gt; (tests/actions/index.test.js:3:1)
</code></pre>
<p>What do I need to do to solve this problem? any idea or solution will be appreciated.</p>
",https://stackoverflow.com/questions/64770117/testing-react-app-with-jest-and-enzyme-token-problem,"['javascript', 'reactjs', 'react-redux', 'jestjs', 'enzyme']",781,True,1,2
Unity Testing with PlatformIO on Native Environment - No avr-gcc libraries,"<p>The guide from PlatformIO (I am using VS Code)  for unit testing seems fair enough.
However, when PlatformIO tries to build for unit tests on my local machine (environment <code>native</code>), my files won't compile. The error states that <code>avr/io.h</code> does not exist. The same files compile fine for my other environment (platform <code>atmelavr</code>, framework <code>arduino</code>).</p>

<p>I guess this is due to GCC being used, instead of AVR-GCC (WinAVR).</p>

<p>Has anybody got unit testing to work on VS Code with PlatformIO, using the native environment? 
How do I set extra include paths for a certain platform, thus supplying GCC with the missing stuff?</p>

<p>I tried adding the path with</p>

<pre><code>lib_extra_dirs = ""C:\Users\MYUSER\.arduinocdt\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5\avr\include""
</code></pre>

<p>with and without a trailing <code>\</code>, but it does not seem to work.</p>

<hr>

<p><strong>(Partial) Directory Tree</strong></p>

<pre><code>...\RGBPlay:.
│   platformio.ini
│
├───include
│       tTimer0.h
|
├───src
│       main.cpp
│       tTimer0.cpp
│
└───test
    └───test_tTimer
            test_tTimer_construct.cpp
</code></pre>

<hr>

<p><strong>platformio.ini</strong></p>

<pre><code>[env:ArduinoAsISP]
platform = atmelavr
framework = arduino
board = attiny85
upload_protocol = stk500v1
upload_flags = 
    -P$UPLOAD_PORT
    -b$UPLOAD_SPEED
upload_port = COM3
upload_speed = 19200

[env:native]
platform = native
lib_extra_dirs = ""C:\Users\MYUSER\.arduinocdt\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5\avr\include""
</code></pre>

<p>The last line is an attempt of me to let the GCC compiler reach <code>io.h</code> (which is in the <code>...\avr\include\avr</code> folder).</p>

<hr>

<p><strong>src/main.cpp</strong></p>

<pre><code>1   #include &lt;avr/io.h&gt;
2   ...
</code></pre>

<hr>

<p><strong>Error Message</strong></p>

<p><a href=""https://i.stack.imgur.com/FlEFe.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/FlEFe.png"" alt=""Actual error message, the part discussed here is marked with green.""></a></p>
",https://stackoverflow.com/questions/61404583/unity-testing-with-platformio-on-native-environment-no-avr-gcc-libraries,"['unit-testing', 'include', 'avr', 'include-path', 'platformio']",952,True,0,1
unit testing Android function with handler,"<p>I'm working with unit testing for the first time and I'm lost with some specific cases.</p>

<p>Despite reading a lot I'm confused about how to test a function like this in Android:</p>

<pre><code>void myFunction() {

    MyThread myThread = new MyThread();
    myThread();
}

class MyThread extends Thread {

    public void run() {
        Looper.prepare();
        // Tasks to do in background
        handler.sendEmptyMessage(101);
    }
}

Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 101:
            // Get the results
            // Update UI        
        }
    }
};
</code></pre>

<p>I've read about ""CountDownLatch"" as in this SO answer <a href=""https://stackoverflow.com/a/5722193/1639825"">https://stackoverflow.com/a/5722193/1639825</a> but I don't know how to use this.</p>
",https://stackoverflow.com/questions/62430251/unit-testing-android-function-with-handler,"['android', 'unit-testing', 'android-handler', 'countdownlatch']",189,False,0,1
Unit test to catch incorrect implementation,"<p>The other day I was watching a lecture by Scott Wlaschin on property-based unit tests and I thought it was great. Totally new concept for me, but it was easy to understand. If interested, you can find <a href=""https://www.youtube.com/watch?v=IYzDFHx6QPY&amp;t=1559s"" rel=""nofollow noreferrer"">the lecture on Youtube</a>.</p>
<p>One of the examples Scott went through was the incorrect implementation of a simple addition function and property-based tests that allow to catch it. Standard properties of addition were used - commutative, distributive, etc.</p>
<p>All this worked well, but I was thinking and what if I decided to implement addition in this strange way:</p>
<pre class=""lang-py prettyprint-override""><code>import random
from math import log

def technically_not_a_sum(x, y):
    i = random.randint(1e10, 1e15)
    t = i**x * i**y
    return log(t, i)
</code></pre>
<p>Technically, the addition is not implemented or implemented but in a very horrific and inefficient way. Yet, it passes all property-based tests with no issues.</p>
<pre class=""lang-py prettyprint-override""><code>def test_is_commutative():
    x = round(random.random()*10, 5)
    y = round(random.random()*10, 5)
    
    assert round(technically_not_a_sum(x, y), 5) == round(technically_not_a_sum(y, x), 5)
    
def test_is_associative():
    x = round(random.random()*10, 5)
    y = round(random.random()*10, 5)
    z = round(random.random()*10, 5)
    
    assert round(technically_not_a_sum(x, y) + z, 5) == round(technically_not_a_sum(y, z) + x, 5)
    
def test_is_identity():
    x = round(random.random()*10, 5)
    y = 0
    
    assert round(technically_not_a_sum(x, y), 5) == x
    
def test_is_distributive():
    x = round(random.random()*10, 5)
    y = round(random.random()*10, 5)
    z = round(random.random()*10, 5)

    assert round(technically_not_a_sum(x, y)*z, 5) == round(x*z + y*z, 5)
</code></pre>
<p>Is there any way to catch this particular implementation with unit testing? Or is this not specifically a correct problem for unit testing?</p>
",https://stackoverflow.com/questions/63131996/unit-test-to-catch-incorrect-implementation,"['python', 'unit-testing']",29,False,0,0
Object Returning Null : Thread Execution,"<p>I am trying to return the EmployeeModel object after assigning it in thread scope and running it. The return_Employee Object is returning me Null values even after running. AddEmployee is another method of return type EmployeeModel object.</p>
<p>I actually need thread method to have return type so as to use it in unit testing project.</p>
<pre><code>       public EmployeeModel AddEmployeeUsingThread(int emp_ID, decimal basicPay, decimal deductions, 
       decimal taxablePay, decimal NetPay)
       {

        EmployeeModel return_Employee=null;

        var thread = new Thread(()=&gt;
        {
            return_Employee= AddEmployee(emp_ID, basicPay, deductions, taxablePay, NetPay);
        });
        thread.Start();

        return return_Employee;
    }
</code></pre>
",https://stackoverflow.com/questions/64709276/object-returning-null-thread-execution,"['.net', 'multithreading']",304,False,0,0
Unit test for service with many dependencies Angular,"<p>I'd like to know how to test the following Service, which has two dependency in constructor.</p>

<p>I don't know how to create environment for test, how to implement <strong>MatDiaglog</strong> in a test.</p>

<p>Should I make fake requests for test this functions?
In general, what is good practice in unit testing, what is the scenario?</p>

<pre><code>@Injectable()
export class FacultiesService {
  constructor(
    private apiService: ApiService,
    private dialog: MatDialog) { }


  openAddFacultyDialog(data = null) {
    const dialogRef = this.dialog.open(CreateEditComponent, {
      width: '400px',
      data
    });
    return dialogRef.afterClosed();
}

  createFaculty(faculty: Faculty) {
    return this.apiService.createEntity('Faculty', faculty);

  }
}

 @Injectable({
  providedIn: 'root'
})

export class ApiService {
  constructor(private http: HttpClient) { }

  createEntity(entity: string, payload): Observable&lt;any&gt; {
    return this.http.post(`${this.apiURI}${entity}/insertData`, payload);
  }
</code></pre>
",https://stackoverflow.com/questions/60392354/unit-test-for-service-with-many-dependencies-angular,"['angular', 'unit-testing']",61,True,0,1
"TypeError: (0 , _umi.connect) is not a function while using jest","<p>I am using jest and enzyme for unit testing. But instead of react-redux, I am using umi for centralised state management but yeah behind the scenes it uses redux only. Now when I run test files I am getting this error</p>
<p>TypeError: (0 , _umi.connect) is not a function</p>
<pre><code>  101 | };
  102 | 
&gt; 103 | export default connect(({ login, loading }: ConnectState) =&gt; ({
      |                ^
  104 |   userLogin: login,
  105 |   submitting: loading.effects['login/login'],
  106 | }))(Login);

  at Object.&lt;anonymous&gt; (src/pages/user/login/index.tsx:103:16)
  at Object.&lt;anonymous&gt; (src/pages/user/login/login.test.js:6:1)
</code></pre>
<p>Here is my test file</p>
<pre><code>import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

describe('Login component tests', () =&gt; {
  let wrapper = shallow(
    &lt;LoginContainer.WrappedComponent userLogin={{ status: '', message: '' }} /&gt;,
  );
})
</code></pre>
",https://stackoverflow.com/questions/63597240/typeerror-0-umi-connect-is-not-a-function-while-using-jest,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",1588,True,0,1
Unit Test without Demo Data in odoo,"<p>Can I actually run a unit test without mark 'load demo data' on my database? If yes, what are the consequences? What are the best practises for unit testing? Can you do testing on your actual database? I'm using odoo12 and now working on unit test2 for python codes. Please help me with this matter</p>
",https://stackoverflow.com/questions/65230551/unit-test-without-demo-data-in-odoo,"['python', 'unit-testing', 'odoo', 'odoo-12']",554,True,0,1
Is there any way to dynamically load images from url using Vue?,"<p>I'm using require.context to load the correct image using Vue.js. I'm getting errors from the Unit testing since require.context is not supported. But ... I started thinking that maybe ... the best way to do this import isn't the require.context. Do you guys have any clue what should be the way to import dynamically those images?</p>
<pre><code> const images = require.context('./img/', false, /\.png$/);
 const imageTitleFormated= imageTitle.replace(/\s/g, '');
 return images(`./${imageTitleFormated}.png`);
</code></pre>
",https://stackoverflow.com/questions/63995345/is-there-any-way-to-dynamically-load-images-from-url-using-vue,"['unit-testing', 'vue.js', 'webpack', 'vuejs2']",67,False,0,1
Tests React component with jest and enzyme,"<p>i have components presented below. I am totally new in unit testing. Can anyone give any one give me advice how and what should I test in this component? I was trying to shallow render it, to check is text in h2 is present but i still getting errors.</p>

<pre><code>import React, { useEffect } from 'react';
import { Form, Field } from 'react-final-form';
import { useHistory, Link } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { loginUser, clearErrorMessage } from '../../redux/auth/authActions';
import Input from '../Input/Input';
import ROUTES from '../../routes/routes';
import './LoginForm.scss';

const LoginForm = () =&gt; {
  const dispatch = useDispatch();
  const history = useHistory();

  const { loading, isLogged, errorMessage } = useSelector(state =&gt; state.auth);

  useEffect(() =&gt; {
    if (isLogged) {
      history.push('/');
    }

    return () =&gt; {
      dispatch(clearErrorMessage());
    };
  }, [dispatch, history, isLogged]);

  const handleSubmitLoginForm = values =&gt; {
    if (!loading) {
      dispatch(loginUser(values));
    }
  };

  const validate = ({ password }) =&gt; {
    const errors = {};

    if (!password) {
      errors.password = 'Enter password!';
    }

    return errors;
  };

  return (
    &lt;article className=""login-form-wrapper""&gt;
      &lt;h2&gt;SIGN IN&lt;/h2&gt;
      &lt;Form onSubmit={handleSubmitLoginForm} validate={validate}&gt;
        {({ handleSubmit }) =&gt; (
          &lt;form onSubmit={handleSubmit} autoComplete=""off"" className=""login-form""&gt;
            &lt;div className=""login-form__field""&gt;
              &lt;Field name=""email"" component={Input} type=""email"" label=""E-mail"" /&gt;
            &lt;/div&gt;
            &lt;div className=""login-form__buttons""&gt;
              &lt;button type=""submit"" className={loading ? 'button-disabled' : ''}&gt;
                Sign in
              &lt;/button&gt;
            &lt;/div&gt;
          &lt;/form&gt;
        )}
      &lt;/Form&gt;
    &lt;/article&gt;
  );
};

export default LoginForm;

</code></pre>

<p>I am open for any advices :)</p>
",https://stackoverflow.com/questions/61487908/tests-react-component-with-jest-and-enzyme,"['javascript', 'reactjs', 'jestjs', 'enzyme']",524,False,0,1
How to perform unit testing on highcharts in angular9?,"<p>I am having a component defined in angular9 which uses a highcharts API.
Now i want to perform a unit testing on the highcharts.
For eg:
If the data fetched is correct or not.
The highchart is created or not.
Any idea of how it can be done using Jasmin and  karma.
THanks in advance.</p>
",https://stackoverflow.com/questions/61811977/how-to-perform-unit-testing-on-highcharts-in-angular9,"['angular', 'highcharts', 'karma-jasmine']",1046,False,-1,1
How to write unit test for these type of methods?,"<p>I'm new to unit testing . How to write unit test for these type of methods?</p>

<pre><code> private boolean fn(Vertex vertex) {
        return vertex.id().toString().split("":"").length &gt; 1;
    }

</code></pre>

<p>Here Vertex is the element of gremlin query . 
I have tried to create instance of graph and pass a new Vertex object to the function but not working .
i.e  </p>

<pre><code>Vertex vertex = (Vertex) graphTraversalSource.addV(""Test"").property(id,""Profile:TEST"");
</code></pre>

<p>Can anyone suggest the ways to test these types of method?</p>
",https://stackoverflow.com/questions/61154074/how-to-write-unit-test-for-these-type-of-methods,"['java', 'unit-testing', 'mockito', 'gremlin']",550,True,0,1
How do I mock azure-storage table service functionality with jest?,"<p>I have this function that calls azure table storage:</p>

<pre><code>const azure = require('azure-storage');
...
function getProductMetadata(sku, locale) {
    const retryPolicy = new azure.ExponentialRetryPolicyFilter(0, 200, 200, 600);
    const tableSvc = azure.createTableServiceWithSas(HOST, `?${AUTH}`).withFilter(retryPolicy);
    const payloadFormat = azure.TableUtilities.PayloadFormat.MINIMAL_METADATA;
    const partition = `${sku}-description`;

    return new Promise&lt;PDAPIProduct.Tabledata&gt;((resolve) =&gt; {
        tableSvc.retrieveEntity('ProductMetadata', partition, locale, { payloadFormat }, (error, result, response) =&gt; {
            if (get(response, 'statusCode') === 404) {
                resolve(null);
            } else {
                resolve(response.body);
            }
        });
    });
}
</code></pre>

<p>And this jest test for that function:</p>

<pre><code>const azure = require('azure-storage');
jest.mock('azure-storage');
const tableServiceMock = {
    retrieveEntity: jest.fn,
    withFilter: jest.fn,
}
azure.createTableServiceWithSas.mockImplementationOnce(() =&gt; tableServiceMock);

afterEach(jest.clearAllMocks);

describe('Product module', () =&gt; {
    describe('getProductMetadata', () =&gt; {
        test('getProductMetadata via azure storage SDK', async () =&gt; {
            const retValue = await pdApiProductService.getProductMetadata('213123123', 'en-CA');

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

<p>But when I run, it errors out with this:</p>

<pre><code> TypeError: tableSvc.retrieveEntity is not a function
</code></pre>

<p>What am I doing wrong?</p>

<p>btw, I was basing my test on this article:
<a href=""https://medium.com/@lakshaykaushik2506/azure-functions-unit-testing-mocking-azure-storage-npm-module-with-jest-34316fac6a69"" rel=""nofollow noreferrer"">https://medium.com/@lakshaykaushik2506/azure-functions-unit-testing-mocking-azure-storage-npm-module-with-jest-34316fac6a69</a></p>
",https://stackoverflow.com/questions/62179680/how-do-i-mock-azure-storage-table-service-functionality-with-jest,"['javascript', 'jestjs', 'azure-storage']",1061,False,0,1
How to clone a Javascript class,"<p>During unit testing, I want to Mock class Foo with a class called Bar.
I have to change a propriety in the class Foo for the test.</p>

<p>This is what I tried. 
It should print:</p>

<p>Foo</p>

<p>Bar</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 Foo {
  id = 'foo'
  constructor() {
    console.log(this.id)
  }
}
const Bar = { ...Foo }
Bar.prototype.id = 'Bar'
new Foo()
new Bar()</code></pre>
</div>
</div>
</p>

<p>I get instead: </p>

<pre><code>error: Uncaught TypeError: Cannot set property 'id' of undefined
</code></pre>

<p>I know I can achieve this by creating a new class Bar extends Foo but is there other possible solutions ? </p>
",https://stackoverflow.com/questions/61554238/how-to-clone-a-javascript-class,"['javascript', 'unit-testing', 'class']",70,True,4,2
Unit testing branch coverage(100%) using @testing-library/react (react-testing-library),"<p>How to cover all branches (100%) in unit testing using @testing-library/react (react-testing-library).</p>
<p>Below are some scenarios</p>
<ol>
<li><p>Conditonal Statements</p>
<pre><code>const num = getNum();
if(num%2 === 0){
  statements...
} else {
  statements...
}
</code></pre>
</li>
</ol>
<p>How to cover statements in both if and else branch?</p>
<ol start=""2"">
<li><p>Private methods in component</p>
<pre><code>const onDateSelectorChange = (elem, value) =&gt; {
  statements...
} 
</code></pre>
</li>
</ol>
<p>How to cover statements in private method like above, that are created to pass as props to child and
only triggered from child?</p>
",https://stackoverflow.com/questions/63328947/unit-testing-branch-coverage100-using-testing-library-react-react-testing-l,"['reactjs', 'unit-testing', 'react-testing-library', 'testing-library']",3498,True,1,1
Method was too large error during PowerMockito,"<p>This AWS lambda function java code compiled without any issue. But when execute the unit testing using powerMockito, error starts appearing when we add the Main class to the @PrepareForTest
There are multiple methods getting called  from parent methods.
I tried mocking few methods using PowerMockito. But still getting method size exceed exception.</p>
<p><strong>Java Code</strong></p>
<pre><code>Public class ClassA implements RequestHandler&lt;InputPayLoadPojo, Response&gt; {

        Public Response handleRequest(InputPayLoadPojo, Context) {
                Private ReturnType ChildMethod1()     {
               …..     
               }
                Private ReturnType ChildMethod2 ()    {
                       Private ReturnType SubChildMethod2 (){
                       ……..
                       }
               …..     
               }

                Public ReturnType ChildMethod1 ()     {
               …..     
               }

               .
               .
               .
               .

               Private ReturnType ChildMethod18 ()   {
               …..     
               }


        }

}
</code></pre>
<p><strong>Test class</strong></p>
<pre><code>@RunWith(PowerMockRunner.class)
@PowerMockIgnore({ &quot;javax.net.ssl.*&quot; , &quot;javax.management.*&quot;})
@PrepareForTest({ ClassA.class})
public class SynchronousTest {

        ClassA obj = PowerMockito.spy(new ClassA());
@Test
public void testSynchronousTranslation() {

        doReturn(somevalue).when(obj, “ChildMethod1”, anyObject….);
        doReturn(somevalue).when(obj, “ChildMethod2”, anyObject….);
        doReturn(somevalue).when(obj, “ChildMethod3”, anyObject….);

        obj.handleRequest(someInputPayLoadPojoObject, someContextObject);

}

}
</code></pre>
<p><strong>Getting error:</strong></p>
<pre><code>java.lang.IllegalAccessException: Method was too large and after instrumentation exceeded JVM limit. PowerMock modified the method to allow JVM to load the class. You can use PowerMock API to suppress or mock this method behaviour.
        at com.taas.amazonservices.lambda.TaaSSyncLambdaFunctionHandler.handleRequest(TaaSSyncLambdaFunctionHandler.java)
        at taas.amazonservices.lambda.SynchronousTest.testSynchronousTranslation(SynchronousTest.java:165)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
        at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
        at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
        at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
        at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java: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.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
        at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
        at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
",https://stackoverflow.com/questions/63442873/method-was-too-large-error-during-powermockito,"['java', 'aws-lambda', 'jvm', 'mockito', 'powermockito']",870,False,1,0
Ability to convert a json file to js in Jest,"<p>We are using create-react-app to build our declarative framework. In this framework, we author a json file which gets loaded into a react-component by webpack. We have authored specific loader for that. This works well in the browser. But facing issues with unit testing. Create-react-app uses Jest for unit testing.
What I want to acheive is transform these json files in js or react component, but hitting following limitations</p>
<ol>
<li>If I add custom transform for json, then it does not work due to restriction put up by jest-runtime.
Post transformation, it expects the output to be json only. See Jest-runtime code which restricts</li>
</ol>
<p><a href=""https://i.stack.imgur.com/tPWc7.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tPWc7.png"" alt=""enter image description here"" /></a></p>
<ol start=""2"">
<li>If I rename file extensions to '.vm' then it never picks up my transformer as create-react-app add fileTransformer in following cases. The highlighted transformer gets picked up for all other types mentioned in that regex.</li>
</ol>
<p><a href=""https://i.stack.imgur.com/fSB4V.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fSB4V.png"" alt=""enter image description here"" /></a></p>
<p>Need your guidance to resolve this issue.</p>
",https://stackoverflow.com/questions/62792824/ability-to-convert-a-json-file-to-js-in-jest,"['javascript', 'reactjs', 'jestjs', 'create-react-app', 'react-app-rewired']",724,False,2,1
UnitTesting ViewController that contains Eureka form,"<p>I'm trying to implement unit testing for one of my ViewControllers that contains a massive form generated by Eureka forms for Swift. </p>

<p>The code compiled well, but received two errors when test was executed.</p>

<ol>
<li>Undefined symbol: nominal type descriptor for Eureka.BaseRow</li>
<li>Undefined symbol: Eureka.Form.allRows.getter : [Eureka.BaseRow]</li>
</ol>

<p>The code in my test file</p>

<pre><code>import XCTest
@testable import MyProject

class DataEntryViewControllerTest: XCTestCase {

    var mainvc: MyProject.DataEntryViewController!

    private func setupViewControllers() {
        let storyboard = UIStoryboard(name: ""Main"", bundle: Bundle.main)

        let newObject = ModelManager.createObject()
        self.mainvc = storyboard.instantiateViewController(withIdentifier: ""dataEntryView"") as? DataEntryViewController

        // this .dataEdit is required
        self.mainvc.dataEdit = newObject
        self.mainvc.loadView()
        self.mainvc.viewDidLoad()
    }

    override func setUp() {
        super.setUp()
        self.setupViewControllers()
    }

    override func tearDown() {
        mainvc = nil
        super.tearDown()
    }

    func testViewDidLoad() throws {
        XCTAssertNotNil(self.mainvc, ""Main VC is nil"")
        let form = mainvc.form

        // If i comment away both of these lines, the test would pass. 
        // having Either one of them kills the process
        XCTAssertEqual(form.allRows.first?.tag, """")
        XCTAssertEqual(mainvc.form.rowBy(tag: ""date"")?.baseValue as Date!, Date())
    }

    func testPerformanceExample() throws {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}

</code></pre>

<p>Relavent code from the view controller</p>

<pre><code>import UIKit
import Eureka
import CoreData

class DataEntryViewController: FormViewController, UITextFieldDelegate {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    // compulsory 
    var dataEdit: object!

    @IBOutlet weak var addOrEditButton: UIBarButtonItem!

    override func viewDidLoad() {

        super.viewDidLoad()

        let form = formPrinter()
        form.delegate = self

        // Triggers hide or show form, incase the object is coming in already locked.
        hideOrShowAllForms()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }

    //MARK: - Form printer
    func formPrinter() -&gt; Form {
        form +++ Section(""Date (UTC)"")
            &lt;&lt;&lt; DateRow(""date""){ row in
                row.disabled = Condition(booleanLiteral: self.dataEdit?.isLocked ?? false)
                } .cellSetup { cell, row in
                row.title = ""Date""
                row.value = self.dataEdit == nil ? Date() : self.dataEdit?.date
                row.dateFormatter?.timeZone = TimeZone(secondsFromGMT: 0)
                cell.datePicker.timeZone = TimeZone(secondsFromGMT: 0)
            }
        return form
    }  
 }

</code></pre>
",https://stackoverflow.com/questions/61848946/unittesting-viewcontroller-that-contains-eureka-form,"['ios', 'xcode', 'unit-testing', 'eureka-forms']",294,False,1,1
TkInter file dialog test with PyTest,"<p>I am developing an command line application (using <code>click</code>). Inside my app, I have 1 function that pops-up a <code>tkinter</code> file dialog for user to select file/folder. </p>

<p>Is it possible for me to do a unit testing on that function using <code>pytest</code>? How can I replicate the user file selection in the test function?</p>

<p>Possible related <a href=""https://stackoverflow.com/questions/17114182/unittest-tkinter-file-dialog"">thread</a>, but using <code>unittest</code>.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/62015254/tkinter-file-dialog-test-with-pytest,"['python', 'tkinter', 'pytest']",163,False,1,0
Null Pointer exception on ScalaTest in AkkaHTTP,"<blockquote>
<p>Error given below</p>
</blockquote>
<pre><code>[ERROR] [08/31/2020 20:36:15.529] [ScalaTest-run-running-HomeControllerSpec] [akka.actor.ActorSystemImpl(HomeControllerSpec)] Error during processing of request: 'java.lang.NullPointerException (No error message supplied)'. Completing with 500 Internal Server Error response. To change default exception handling behavior, provide a custom ExceptionHandler.
    java.lang.NullPointerException
        at controller.HomeController$.$anonfun$route$6(HomeController.scala:32)
        at akka.http.scaladsl.server.directives.FutureDirectives.$anonfun$onComplete$2(FutureDirectives.scala:37)
        at akka.http.scaladsl.server.directives.FutureDirectives.$anonfun$onComplete$3(FutureDirectives.scala:37)
        at akka.http.scaladsl.util.FastFuture$.$anonfun$transformWith$1(FastFuture.scala:36)
        at akka.http.scaladsl.util.FastFuture$.strictTransform$1(FastFuture.scala:40)
        at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:44)
        at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:36)
        at akka.http.scaladsl.server.directives.FutureDirectives.$anonfun$onComplete$2(FutureDirectives.scala:37)
        at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$textract$2(BasicDirectives.scala:161)
        at akka.http.scaladsl.server.directives.FutureDirectives.$anonfun$onComplete$3(FutureDirectives.scala:37)
        at akka.http.scaladsl.util.FastFuture$.$anonfun$transformWith$1(FastFuture.scala:36)
        at akka.http.scaladsl.util.FastFuture$.strictTransform$1(FastFuture.scala:40)
        at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:44)
        at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:36)
        at akka.http.scaladsl.server.directives.FutureDirectives.$anonfun$onComplete$2(FutureDirectives.scala:37)
        at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$textract$2(BasicDirectives.scala:161)
        at akka.http.scaladsl.server.directives.FutureDirectives.$anonfun$onComplete$3(FutureDirectives.scala:37)
        at akka.http.scaladsl.util.FastFuture$.$anonfun$transformWith$1(FastFuture.scala:36)
        at akka.http.scaladsl.util.FastFuture$.strictTransform$1(FastFuture.scala:40)
        at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:44)
        at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:36)
        at akka.http.scaladsl.server.directives.FutureDirectives.$anonfun$onComplete$2(FutureDirectives.scala:37)
        at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$textract$2(BasicDirectives.scala:161)
        at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$mapRequestContext$2(BasicDirectives.scala:45)
        at akka.http.scaladsl.server.directives.BasicDirectives.$anonfun$textract$2(BasicDirectives.scala:161)
        at akka.http.scaladsl.server.RouteConcatenation$RouteWithConcatenation.$anonfun$$tilde$2(RouteConcatenation.scala:47)
        at akka.http.scaladsl.util.FastFuture$.strictTransform$1(FastFuture.scala:40)
        at akka.http.scaladsl.util.FastFuture$.transformWith$extension(FastFuture.scala:44)
        at akka.http.scaladsl.util.FastFuture$.flatMap$extension(FastFuture.scala:25)       
&quot;[There was an internal server error.]&quot; did not equal &quot;[Data is Inserted]&quot;
    ScalaTestFailureLocation: HomeControllerSpec at (HomeControllerSpec.scala:20)
    Expected :&quot;[Data is Inserted]&quot;
    Actual   :&quot;[There was an internal server error.]&quot;
    &lt;Click to see difference&gt;
    
org.scalatest.exceptions.TestFailedException: &quot;[There was an internal server error.]&quot; did not equal &quot;[Data is Inserted]&quot;
        at org.scalatest.matchers.MatchersHelper$.indicateFailure(MatchersHelper.scala:344)
        at org.scalatest.matchers.should.Matchers$AnyShouldWrapper.shouldEqual(Matchers.scala:6860)
        at HomeControllerSpec.$anonfun$new$5(HomeControllerSpec.scala:20)
        at scala.util.DynamicVariable.withValue(DynamicVariable.scala:59)
        at akka.http.scaladsl.testkit.RouteTest.$anonfun$check$1(RouteTest.scala:59)
        at ......
</code></pre>
<p>My Code =&gt; ScalaRoutes =&gt;</p>
<pre><code>object HomeController extends App with Directives {

  implicit val system: ActorSystem = ActorSystem()
  implicit val executionContext: ExecutionContextExecutor = system.dispatcher
  val db = Database.forConfig(&quot;mysql&quot;)
  val obj: EmployeeRepImpl = new EmployeeRepImpl(db)

  //def router = route
  def route =
    get {
      concat(
        pathSingleSlash {
          complete {
            &quot;Captain on the bridge!&quot;
          }
        },
        path(&quot;insert&quot;) {
          parameters(&quot;empid&quot;, &quot;name&quot;, &quot;dept&quot;) { (empid, name, dept) =&gt;
            onComplete(obj.add(empid, name, dept)) {
              case Success(value) =&gt; complete(s&quot;Data is Inserted&quot;)
              case Failure(ex) =&gt; complete(InternalServerError, s&quot;An error occurred: &quot;)
            }
          }
        }
      )
    }

  val bindingFuture = Http().newServerAt(&quot;localhost&quot;, 8080).bind(route)
  println(s&quot;Server online at http://localhost:8080/\nPress RETURN to stop...&quot;)
  StdIn.readLine() // let it run until user presses return
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ =&gt; system.terminate())
}
</code></pre>
<blockquote>
<p>EmployeeRep=&gt;</p>
</blockquote>
<pre><code>trait EmployeeRep {
  def add(id: String, name: String, dept: String): Future[Unit]
  }

class EmployeeRepImpl(db: Database) extends EmployeeRep with EmployeeStore {  

  override def add(id: String, name: String, dept: String): Future[Unit] = {
    val freshTestData: DBIOAction[Unit, NoStream, Effect.Write] = DBIO.seq(
      emp ++= Seq(Employee(id, name, dept))
    )
    db.run(
      freshTestData
    )
  }
}
</code></pre>
<blockquote>
<p>HomeControllSpec</p>
</blockquote>
<pre><code>import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import akka.http.scaladsl.model.StatusCodes
import controller.HomeController

class HomeControllerSpec extends AnyWordSpec with Matchers  with ScalatestRouteTest {


  &quot;A Router&quot; should {
    &quot;return Captain on the bridge!&quot; in {
      Get() ~&gt; HomeController.route ~&gt; check {
        status shouldBe StatusCodes.OK
        responseAs[String] shouldBe &quot;Captain on the bridge!&quot;
      }
    }
    &quot;return a 'Data is Inserted' response for GET requests to /Insert&quot; in {
      Get(&quot;/insert?empid=1&amp;name=varsha&amp;dept=de&quot;) ~&gt; HomeController.route ~&gt; check {
        //status shouldBe StatusCodes.OK
        responseAs[String] shouldEqual &quot;Data is Inserted&quot;
      }
    }
  }
}
</code></pre>
<blockquote>
<p>Not able to understand why the internal server error is coming for the 2nd routes /insert tried above code but could not succeed
the /insert URL hits the database and insert the data into the table. but when I tried with unit testing it gave me above error.</p>
</blockquote>
",https://stackoverflow.com/questions/63673900/null-pointer-exception-on-scalatest-in-akkahttp,"['scala', 'scalatest', 'akka-http']",279,False,1,0
"How to mock Message.creator(to, from, smsRequest.getMessage()).create(); method in Twilio","<p>I have used twilio to send sms to my users using Java 8 and Spring. So I want Unit test my code using JUnit5 and Mockito. But the issue is that I am unable to mock this code 
<code>Message.creator(to, from, smsRequest.getMessage()).create();</code></p>

<p>So I would require help in successfully mocking this code for properly Unit testing my function.</p>

<p>Any help is appreciated.</p>
",https://stackoverflow.com/questions/61628434/how-to-mock-message-creatorto-from-smsrequest-getmessage-create-method,"['java', 'unit-testing', 'mocking', 'twilio']",734,False,1,2
Unable to mock a node module using JEST (with Typescript) and React environment,"<p>I made a React hooks library, available on NPM.</p>
<p>For unit testing this lib, I'm using JEST with Typescript.</p>
<p>It has a dependency with another node module <code>@brand/dependencyModule</code>.</p>
<p>This <code>@brand/dependencyModule</code> is doing http request and emits events (with <code>{ EventEmitter } from 'events'</code>) which I need to mock.</p>
<p>I tried to follow the <a href=""https://jestjs.io/docs/en/manual-mocks"" rel=""nofollow noreferrer"">JEST documentation</a> to do manual mock of this lib.</p>
<p>First, let me show you what I tried:</p>
<ol>
<li>Create <code>__mocks__</code> folder at project root level (same level as <code>node_modules</code>)</li>
<li>Create subfolder <code>@brand</code> inside <code>__mocks__</code></li>
<li>Create TS file <code>dependencyModule.ts</code> inside <code>@brand</code> folder</li>
</ol>
<p>Inside <code>__mocks__/@brand/dependencyModule.ts</code>, we have:</p>
<pre class=""lang-js prettyprint-override""><code>'use strict';

import { EventEmitter } from 'events';
import {
    SomeTyping
} from '@brand/dependencyModule';

class MockVisitor extends EventEmitter {
    someAttribute1: string;

    someAttribute2: string;

    someAttribute3: SomeTyping;

    constructor(some) {
        super();
        this.someAttribute1 = some;
        this.someAttribute2 = parameter;
        this.someAttribute3 = mockHttpResponse;

        setTimeout(() =&gt; {
            this.emit('ready');
        }, 100);
    }
}

class MockModule {
    otherAttribute1: string;

    constructor(otherParam) {
        this.otherAttribute1 = otherParam;
    }

    public newVisitor(some, param) {
        return new MockVisitor(some, param);
    }
}

export default jest.fn().mockImplementation(() =&gt; ({
    start: (someStuff) =&gt; {
        return new MockModule(someStuff);
    }
}));

</code></pre>
<p>Now, in my <code>src/**/index.test.ts</code> file, I have:</p>
<pre class=""lang-js prettyprint-override""><code>
describe('trying to mock @brand/dependencyModule', () =&gt; {
    test('it should use the mock version', async () =&gt; {
        let isReady = null;
        const { container } = render(
            &lt;MyHookProvider
                onInitDone={() =&gt; {
                    isReady = true;
                }}
            &gt;
                &lt;div&gt;Hello&lt;/div&gt;
            &lt;/MyHookProvider&gt;
        );

        await waitFor(() =&gt; {
            if (!isReady) {
                throw new Error('not ready');
            }
        });
        expect(isReady).toEqual(true);
    });
});

</code></pre>
<p>Finaly, let's have a look to <code>MyHookProvider.tsx</code> file which uses '@brand/dependencyModule':</p>
<pre class=""lang-js prettyprint-override""><code>import React, { useState, useEffect, SetStateAction, Dispatch, useContext } from 'react';

import dependencyModule from '@brand/dependencyModule';


export const MyHookProvider: React.SFC&lt;/*...*/&gt; = ({
    // ...
    onInitDone,
}: ProviderProps) =&gt; {
    useEffect(() =&gt; {
        const module = dependencyModule.start('hello');
        const visitorInstance = module.newVisitor('stack','overflow');
        
        visitorInstance.on('ready', () =&gt; {
            onInitDone()
        });
    }, [/*...*/]);

    return (
        &lt;MyHook.Provider value={{ ... }}&gt;
                {&quot;I'm ready.&quot;}
        &lt;/MyHook.Provider&gt;
    );
};

MyHookProvider.defaultProps = {
    onInitDone: (): void =&gt; {
        // do nothing
    },
};


</code></pre>
<p>Now the error which I have when run <code>npm run test</code>, I expect jest to detect I have mocked <code>@brand/dependencyModule</code> but when I'm debugging, it's actually running the real lib. I don't what I'm missing to make it work.</p>
<p>Any help ? Thank you !</p>
<p>Here the libs which I'm using for unit testing:</p>
<pre><code>        &quot;@testing-library/jest-dom&quot;: &quot;^5.5.0&quot;,
        &quot;@types/jest&quot;: &quot;^25.2.1&quot;,
        &quot;@types/enzyme&quot;: &quot;^3.10.5&quot;,
        &quot;@types/enzyme-adapter-react-16&quot;: &quot;^1.0.6&quot;,
        &quot;enzyme&quot;: &quot;^3.11.0&quot;,
        &quot;enzyme-adapter-react-16&quot;: &quot;^1.15.2&quot;,
        &quot;enzyme-to-json&quot;: &quot;^3.4.4&quot;,
        &quot;jest&quot;: &quot;^25.4.0&quot;,
        &quot;jest-mock-axios&quot;: &quot;^3.2.0&quot;,
        &quot;ts-jest&quot;: &quot;^25.4.0&quot;,

</code></pre>
<p>jest config setup like this:</p>
<pre><code>    &quot;jest&quot;: {
        &quot;setupFilesAfterEnv&quot;: [
            &quot;./src/setupTests.js&quot;
        ]
    }
</code></pre>
<p>with <code>src/setupTests.js</code> :</p>
<pre><code>import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });
</code></pre>
",https://stackoverflow.com/questions/62830232/unable-to-mock-a-node-module-using-jest-with-typescript-and-react-environment,"['reactjs', 'typescript', 'mocking', 'jestjs', 'ts-jest']",797,False,2,0
mock a toPromise function in jest - got .toPromise is not a function,"<p>I have an httpService from nestjs/common </p>

<p>and I am using like the following:</p>

<pre><code>const response = await this.httpService.post(`${this.api}/${action}`, data).toPromise();
</code></pre>

<p>and in my jest spec file ( unit testing) . i am trying to mock this service </p>

<pre><code>   httpServiceMock = {
      post: jest.fn()
    };

it('should start', async () =&gt; {

    const serviceResult = await service.start(data);

});
</code></pre>

<p>and I have got this error :</p>

<pre><code>TypeError: this.httpService.post(...).toPromise is not a function
</code></pre>

<p>I am also trying to add a promise result like :</p>

<pre><code> const promise = Promise.resolve('result');
 httpServiceMock.post.mockResolvedValue(promise);
</code></pre>

<p>tried also :</p>

<pre><code>it('should start', async () =&gt; {

    const mockObservable = Promise.resolve({
        toPromise: () =&gt; {
          console.log('toPromise called');
        }
      })

    httpServiceMock.post.mockImplementation(() =&gt; mockObservable);

    const serviceResult = await service.start();

});
</code></pre>

<p><strong>My question is how can I mock the promise and return a response or exception</strong></p>
",https://stackoverflow.com/questions/59562092/mock-a-topromise-function-in-jest-got-topromise-is-not-a-function,"['node.js', 'promise', 'jestjs', 'nestjs']",4960,True,4,3
How can I test equality of a pandas series in a dict?,"<p>I've wrapped a pandas series into a dict: <code>dict = {'0': pd.Series(...)}</code>. During unit testing I'd like to assert equality of the series contained in the dict in comparison to an expected pandas series. However plain <code>assert dict == expected_dict</code> does not work due to <code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</code>. For a plain series I usually use <a href=""https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.testing.assert_series_equal.html"" rel=""nofollow noreferrer"">pandas.testing.assert_series_equal</a>. How can I test a pandas series equality which is wrapped into a dict?</p>
",https://stackoverflow.com/questions/62817514/how-can-i-test-equality-of-a-pandas-series-in-a-dict,"['pandas', 'dictionary', 'series']",248,False,1,1
Unit Testing ASP.NET Core AAD Auth,"<p>I'm using Selenium to Unit Test an Azure AD application in ASP.NET Core MVC web app and I am looking for a better method of logging in the test user besides searching the DOM for login input elements. I'm Unit Testing in Azure DevOps so logging in with the browser UI is not an option. Any ideas?</p>
",https://stackoverflow.com/questions/63064896/unit-testing-asp-net-core-aad-auth,"['asp.net-core', 'asp.net-core-mvc', 'azure-active-directory', 'openid-connect']",627,True,1,1
Laravel Unit Testing - Controllers,"<p>I am quite new to Laravel and have been reading the documentation on testing, however I am not sure how I would go about Unit Testing the Controller I have posted below. Any advice on how I would go about this is much appreciated.
The controller below is the CRUD controller I created for Booking Forms. </p>

<pre><code>class BookingFormsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $bookingforms = BookingForm::orderBy('surgeryDate', 'asc')-&gt;paginate(5);
        return view('bookingforms.index')-&gt;with('bookingforms', $bookingforms);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('bookingforms.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $booking)
    {
      $this-&gt;validate($booking, [
      'requestID' =&gt; 'required',
      'patientID' =&gt; 'required',
      'patientForename' =&gt; 'required',
      'patientSurname'=&gt; 'required',
      'patientSex' =&gt; 'required',
      'patientDOB' =&gt; 'required',
      'surgeryType' =&gt; 'required',
      'surgeryDate' =&gt; 'required',
      'performingSurgeon' =&gt; 'required',
      'TheatreRoomID' =&gt; 'required',
      'patientUrgency' =&gt; 'required',
      'patientNotes' =&gt; 'required',
      'bloodGroup' =&gt; 'required'
      ]);

      // Create new Booking Form
      $bookingform = new Bookingform;
      $bookingform-&gt;requestID = $booking-&gt;input('requestID');
      $bookingform-&gt;bookingID = $booking-&gt;input('bookingID');
      $bookingform-&gt;patientID = $booking-&gt;input('patientID');
      $bookingform-&gt;patientForename = $booking-&gt;input('patientForename');
      $bookingform-&gt;patientSurname = $booking-&gt;input('patientSurname');
      $bookingform-&gt;patientSex = $booking-&gt;input('patientSex');
      $bookingform-&gt;patientDOB = $booking-&gt;input('patientDOB');
      $bookingform-&gt;surgeryType = $booking-&gt;input('surgeryType');
      $bookingform-&gt;surgeryDate = $booking-&gt;input('surgeryDate');
      $bookingform-&gt;performingSurgeon = $booking-&gt;input('performingSurgeon');
      $bookingform-&gt;TheatreRoomID = $booking-&gt;input('TheatreRoomID');
      $bookingform-&gt;patientUrgency = $booking-&gt;input('patientUrgency');
      $bookingform-&gt;patientNotes = $booking-&gt;input('patientNotes');
      $bookingform-&gt;bloodGroup = $booking-&gt;input('bloodGroup');
      $bookingform-&gt;user_id = auth()-&gt;user()-&gt;id;

      //Save Booking form

      $bookingform-&gt;save();

      //redirect
      return redirect('/bookingforms')-&gt;with('success', 'Booking Submitted');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($bookingID)
    {
        $bookingform = BookingForm::find($bookingID);
        return view('bookingforms.show')-&gt;with('bookingform', $bookingform);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($bookingID)
    {
        $bookingform = BookingForm::find($bookingID);
        //check for correct user_id
        if(auth()-&gt;user()-&gt;id !==$bookingform-&gt;user_id){
            return redirect('/bookingforms')-&gt;with('danger', 'This is not your booking, please contact the Booker.');
        }
        return view('bookingforms.edit')-&gt;with('bookingform', $bookingform);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $booking, $bookingID)
    {
      $this-&gt;validate($booking, [
      'patientID' =&gt; 'required',
      'patientForename' =&gt; 'required',
      'patientSurname'=&gt; 'required',
      'patientSex' =&gt; 'required',
      'patientDOB' =&gt; 'required',
      'surgeryType' =&gt; 'required',
      'surgeryDate' =&gt; 'required',
      'performingSurgeon' =&gt; 'required',
      'TheatreRoomID' =&gt; 'required',
      'patientUrgency' =&gt; 'required',
      'patientNotes' =&gt; 'required',
      'bloodGroup' =&gt; 'required'
      ]);

      // Create new Booking Form
      $bookingform = Bookingform::find($bookingID);
      $bookingform-&gt;bookingID = $booking-&gt;input('bookingID');
      $bookingform-&gt;patientID = $booking-&gt;input('patientID');
      $bookingform-&gt;patientForename = $booking-&gt;input('patientForename');
      $bookingform-&gt;patientSurname = $booking-&gt;input('patientSurname');
      $bookingform-&gt;patientSex = $booking-&gt;input('patientSex');
      $bookingform-&gt;patientDOB = $booking-&gt;input('patientDOB');
      $bookingform-&gt;surgeryType = $booking-&gt;input('surgeryType');
      $bookingform-&gt;surgeryDate = $booking-&gt;input('surgeryDate');
      $bookingform-&gt;performingSurgeon = $booking-&gt;input('performingSurgeon');
      $bookingform-&gt;TheatreRoomID = $booking-&gt;input('TheatreRoomID');
      $bookingform-&gt;patientUrgency = $booking-&gt;input('patientUrgency');
      $bookingform-&gt;patientNotes = $booking-&gt;input('patientNotes');
      $bookingform-&gt;bloodGroup = $booking-&gt;input('bloodGroup');
      $bookingform-&gt;user_id = auth()-&gt;user()-&gt;id;

      //Save Booking form

      $bookingform-&gt;save();

      //redirect
      return redirect('/bookingforms')-&gt;with('success', 'Booking Updated');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($bookingID)
    {
        $bookingform = Bookingform::find($bookingID);
        if(auth()-&gt;user()-&gt;id !==$bookingform-&gt;user_id){
            return redirect('/bookingforms')-&gt;with('danger', 'This is not your booking, please contact the Booker.');
        }
        $bookingform-&gt;delete();
        return redirect('/bookingforms')-&gt;with('success', 'Booking Removed');
    }
</code></pre>
",https://stackoverflow.com/questions/61480974/laravel-unit-testing-controllers,"['laravel', 'unit-testing', 'phpunit']",127,True,1,2
Unit testing a method which calls a method returning a page of an entitiy,"<p>I would like to test the following method, for the case when I know the underlying call to findAllByMerchantId() method returns a fixed number of results (a page with fixed number of entities). </p>

<pre><code>public ListBeneficiaryResponseDTO getBeneficiariesOfMerchant(Long merchantId, Integer page, Integer pageSize,
                                                             String sortDirection, String sortField) {

    // default we are setting to added on desc sort
    Sort sort = Sort.by(Sort.Direction.DESC,""addedOn"");
    if(sortField != null &amp;&amp; sortDirection != null) {
        sort = Sort.by(Sort.Direction.fromString(sortDirection),sortField);
    }

    Pageable pageRequest = PageRequest.of(page-1, pageSize, sort);
    Page&lt;Beneficiary&gt; pageOfBeneficiaries = beneficiaryRepository.findAllByMerchantId(merchantId, pageRequest);

    List&lt;BeneficiaryResponseDTO&gt; benResonseDtoList = new ArrayList&lt;BeneficiaryResponseDTO&gt;();

    for( Beneficiary ben: pageOfBeneficiaries.getContent()) {
        benResonseDtoList.add(this.getBeneficiaryResponseDTO(ben));
    }
    ListBeneficiaryResponseDTO formattedListBen = new ListBeneficiaryResponseDTO(pageOfBeneficiaries.getTotalPages(),pageOfBeneficiaries.getTotalElements(),pageOfBeneficiaries.getNumber(),benResonseDtoList);
    return formattedListBen;
}
</code></pre>

<p>How do I mock the response of findAllByMerchantId() call, to return a fixed number of results in a page?  </p>

<p>P.S. Beginner at unit testing..</p>
",https://stackoverflow.com/questions/61630500/unit-testing-a-method-which-calls-a-method-returning-a-page-of-an-entitiy,"['java', 'unit-testing', 'mockito']",66,True,1,2
Cannot set property &#39;http&#39; of undefined - Angular Unit testing,"<p>I am fairly new to unit testing. I am building an Angular component and my test suite is Jasmine/Karma.</p>

<p>My first test is complaining about two issues and I'm only trying to test an initialised variable value:</p>

<pre><code>TypeError: Cannot set property 'http' of undefined

TypeError: Cannot read property 'isView' of undefined
</code></pre>

<p>The code is pretty simple so wondering why I'm getting these errors?</p>

<p><strong>myComponent.ts</strong></p>

<pre><code>sView = false;
</code></pre>

<p><strong>myComponent.spec.ts</strong></p>

<pre><code>describe('myComponent', () =&gt; {
    let component: myComponent;
    let fixture: ComponentFixture&lt;myComponent&gt;;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            schemas: [NO_ERRORS_SCHEMA],
            declarations: [myComponent],
            imports: [HttpClientTestingModule],
            providers: [
                {
                    provide: myService,
                    useFactory: myServiceMock
                }
            ]
        });
        fixture = TestBed.createComponent(myComponent);
        component = fixture.componentInstance;
    });


    it('isView defaults to: false', () =&gt; {
        expect(component.isView).toEqual(false);
    });

});
</code></pre>

<p>What is going on here?</p>
",https://stackoverflow.com/questions/60974768/cannot-set-property-http-of-undefined-angular-unit-testing,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",658,True,0,1
Dart Future catchError not called in unit test,"<p>I am calling Future like this:</p>
<pre><code>   //main_bloc.dart
   ...
    getData() {
     print(&quot;getting data&quot;);

     repository.getDataFromServer().then((result) {
          _handleResult(result);
      }).catchError((e) {
          _handleError(e);
      });
   }
</code></pre>
<p>In runtime, when there is exception from the repository, it will be catched in the catchError and forward properly.</p>
<p>However, when i do unit testing to that part of code like this:</p>
<pre><code>//prepare
when(mockRepository.getDataFromServer()).thenThrow(PlatformException(code: &quot;400&quot;, message: &quot;Error&quot;, details: &quot;&quot;));

//act

bloc.getData();
await untilCalled(mockRepository.getDataFromServer());

//assert

verify(mockRepository.getDataFromServer());
</code></pre>
<p>The <code>catchError</code> method not called and the test is failed due to unHandled exception.</p>
<p>What i am doing wrong?</p>
",https://stackoverflow.com/questions/63493407/dart-future-catcherror-not-called-in-unit-test,"['unit-testing', 'flutter', 'dart', 'future', 'flutter-test']",608,True,0,1
cannot read property setNumber of undefined getting in Unit testing error,"<p>I am trying to unit testing my code where I am getting the below error</p>
<blockquote>
<p>TypeError: Cannot read property 'setNumber' of undefined</p>
</blockquote>
<p>this is my service method for that</p>
<pre><code> setNumber(number) {
   this.number = number;
 }
</code></pre>
<p>This code is there in ts</p>
<pre><code>this.dataService.setNumber(null);
</code></pre>
<p>This is my spec code.</p>
<pre><code>  beforeEach(async(() =&gt; {
   const spyDataService = jasmine.createSpyObj('DataService', ['setNumber'])
  TestBed.configureTestingModule({
  imports: [HttpClientTestingModule, MatDialogModule, BrowserAnimationsModule, RouterTestingModule, MatMenuModule, MatFormFieldModule, MatInputModule, MatPaginatorModule, MatTableModule, MatSortModule, MatIconModule, MatCardModule,],
  declarations: [DashboardComponent],
  providers: [

    { provide: DataService, useValue: spyDataService },
    { provide: MAT_DIALOG_DATA, useValue: {} },
    { provide: MatDialogRef, useValue: {} },
    { provide: LayoutUtilsService, useValue: {} }

  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
  .compileComponents();
</code></pre>
<p>}));</p>
<pre><code>  it('should be create data service', () =&gt; {
   expect(service.setNumber).toHaveBeenCalledWith(null);
 });
</code></pre>
<p>What is wrong here why I am getting this error</p>
<blockquote>
<p>TypeError: Cannot read property 'setNumber' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/63971355/cannot-read-property-setnumber-of-undefined-getting-in-unit-testing-error,"['angular', 'jasmine', 'karma-jasmine']",91,True,0,1
How to unit test a catch block which does not throw any exception,"<p>Here is my code.</p>
<pre><code>    @Override
    public KinesisEvent handleRequest(@NonNull KinesisEvent kinesisEvent, @NonNull Context context) {
        KinesisEvent kinesisEventReturn = kinesisEvent.clone();
        final List&lt;KinesisEvent.KinesisEventRecord&gt; transformedRecords = kinesisEventReturn.getRecords().stream().map(
                record -&gt; {
                    try {
                        return decryptLog(record);
                    } catch (IOException e) {
                        log.error(&quot;Decryption did not work. See exception: &quot;, e);
                    }
                    return record;
                }).collect(Collectors.toList());
        kinesisEventReturn.setRecords(transformedRecords);
        return kinesisEventReturn;
    }
</code></pre>
<p>If you see, I have catch block which catches exception but not throws the exception. I wanted to test the catch block in unit testing. But all the example i find is to test whether an exception is thrown or not.</p>
<p>Please help if there any work around with that.</p>
<p>Thanks
Dhrubo</p>
",https://stackoverflow.com/questions/62826266/how-to-unit-test-a-catch-block-which-does-not-throw-any-exception,"['java', 'unit-testing', 'junit', 'junit4', 'spock']",470,True,0,1
Node Assertion Testing,"<p>Does anyone have good reference material for assertion testing in node? I wrote some simple programs and I want to write unit test with the inbuilt node modules but can't seem to find any proper reference material. A simple tutorial will also suffice. I am familiar with unit testing in python catching up shouldn't be a problem.</p>
",https://stackoverflow.com/questions/60215422/node-assertion-testing,"['javascript', 'node.js', 'unit-testing', 'tdd']",25,False,-1,1
Sinon Class Constructor,"<p>I have an Animal class as follows</p>

<blockquote>
  <p>Animal.js</p>
</blockquote>

<pre><code>export default class Animal {
  constructor(type) {
    this.type = type
  }
  getAnimalSound(animal) {
    if (animal &amp;&amp; animal.type == 'dog') return 'woof'
    if (animal &amp;&amp; animal.type == 'cat') return 'meow'
  }
}
</code></pre>

<p>I make a zoo module which has a method for getAnimalSound() as follows</p>

<blockquote>
  <p>zoo.js</p>
</blockquote>

<pre><code>import Animal from './Animal'

export default function getAnimalSound(type) {
  let animal = new Animal(type)
  let animalSound = animal.getAnimalSound(animal)
  return animalSound
}
</code></pre>

<p>Now how do i make unit testing for zoo module?</p>

<blockquote>
  <p>zoo.test.js</p>
</blockquote>

<pre><code>import sinon from 'sinon'

import Animal from './Animal'
import getAnimalSound from './zoo'

let animalStub = sinon.createStubInstance(Animal)
let a = animalStub.getAnimalSound.returns('woof')
let sound = getAnimalSound('cat')
console.log(sound)
</code></pre>

<p>So the problem is that the 'new' has no effect by the way i have stubbed in test.js
Can i achieve this?</p>

<p>Regards
Bobu P</p>
",https://stackoverflow.com/questions/61716637/sinon-class-constructor,"['node.js', 'unit-testing', 'sinon', 'stub']",147,True,0,1
Unit testing requires many interfaces?,"<p>I'm currently working on my first project that uses TDD and unit testing. I'm writing in C++ with <strong>googletest</strong> and <strong>googlemock</strong> libraries. The project requires many small classes with particular functionalities. I mostly use dependency injection in constructors. According to this:</p>
<p><a href=""https://stackoverflow.com/questions/38181/when-should-i-mock"">When should I mock?</a> and
<a href=""https://stackoverflow.com/questions/56078171/when-to-use-mock-objects-in-unit-tests/56078734"">When to use mock objects in unit tests</a></p>
<p>dependency injected into constructor is good candidate for mocking in unit testing. There are two ways to do this in C++:</p>
<ol>
<li>Creating interface (pure virtual class). Production class and mock class derives from it.</li>
<li>Create virtual member functions inside Production class. Mock class derives from Production class. There is a problem when Production class does not define default constructor. Mock class has to call Base class constructor explicitly (personally it is not the stuff that mock object should do).</li>
</ol>
<p>How do you handle this kind of situation? Do you prefer many interfaces (N classes requires N interfaces) or deriving from Base class?</p>
",https://stackoverflow.com/questions/62829366/unit-testing-requires-many-interfaces,"['java', 'c++', 'unit-testing', 'googletest', 'googlemock']",231,True,1,1
Jest/Enzyme testing Form component,"<p>I am testing the form component on my react app.
I am getting a similar error as the unresolved post here (<a href=""https://stackoverflow.com/questions/62088492/testing-form-input-in-jest-and-enzyme"">Testing form input in jest and enzyme</a>).</p>
<p>I tried 2 different methods for form.test.js below, both aren't giving me passing tests.</p>
<pre><code>//simple form component

import React from &quot;react&quot;;
import Checkbox from &quot;../checkbox/checkbox.component&quot;;
import { withRouter } from 'react-router-dom';

class Form extends React.Component {
    constructor(props){
        super(props);

        this.state={
            fullName:&quot;&quot;,
            email:&quot;&quot;
            }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);

    }

    handleChange(event){
        this.setState({[event.target.name]: event.target.value});
    }


    handleSubmit = async event =&gt; {
        event.preventDefault();
    
        try {
          const requestData = {
            method: 'POST',
            headers:{
               'Content-Type': 'application/json'
            },
            body: JSON.stringify(this.state)
          };
          const response = await fetch('http://localhost:5000/results', requestData);
          this.props.history.push('/thankyou');
        
         } 
         catch (error) {
            console.log(error);
         }
    }

    render(){
        return(
          &lt;div&gt;
             &lt;form onSubmit={this.handleSubmit}&gt;
                 &lt;label&gt;
                    Full Name
                &lt;/label&gt;
                &lt;input
                    type=&quot;text&quot;
                    value={this.state.fullName}
                    onChange={this.handleChange}
                    name=&quot;fullName&quot;
                    required
                    /&gt;
            
                &lt;br&gt;&lt;/br&gt;
                &lt;label&gt;
                    Email
                &lt;/label&gt;
                    &lt;input
                        type=&quot;email&quot;
                        value={this.state.email}
                        onChange={this.handleChange}
                        name=&quot;email&quot;
                        required
                    /&gt;
                &lt;br&gt;&lt;/br&gt;
                &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;/&gt;
            
             &lt;/form&gt;     
            &lt;/div&gt;
        );
    }
}

export default withRouter(Form);
</code></pre>
<p>Method #1:</p>
<pre><code>Expected: &quot;Hello World&quot;
Received: &quot;&quot;
</code></pre>
<pre><code>//form.test.js



import React from 'react';
import Form from './form.component';
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom'; 

describe ('Form', () =&gt; {
    let wrapper;

    beforeEach(() =&gt; {
        wrapper = mount(
        &lt;MemoryRouter&gt;
            &lt;Form/&gt;
        &lt;/MemoryRouter&gt;
        )
    });


    it('should capture fullname correctly onChange', () =&gt; {

        const input = wrapper.find('input').at(0);
        input.simulate('change', {
                    target: { value : 'Hello World'}
                });
        expect(input.instance().value).toEqual(&quot;Hello World&quot;)

})

});
</code></pre>
<p>Method #2:
Resource - <a href=""https://www.mydatahack.com/unit-testing-react-form-with-jest-and-enzyme/"" rel=""nofollow noreferrer"">https://www.mydatahack.com/unit-testing-react-form-with-jest-and-enzyme/</a></p>
<pre><code>TypeError: Cannot read property 'fullName' of null
</code></pre>
<pre><code>//form.test.js

import React from 'react';
import Form from './form.component';
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom'; 

describe ('Form', () =&gt; {
    let wrapper;

    beforeEach(() =&gt; {
        wrapper = mount(
        &lt;MemoryRouter&gt;
            &lt;Form/&gt;
        &lt;/MemoryRouter&gt;
        )
    });


    it('should capture fullname correctly onChange', () =&gt; {

        const input = wrapper.find('input').at(0);
        input.instance().value = &quot;Hello World&quot;;
        input.simulate('change');
        expect(wrapper.state().fullName).toEqual('Hello World');

})

});
</code></pre>
",https://stackoverflow.com/questions/64001162/jest-enzyme-testing-form-component,"['javascript', 'reactjs', 'jestjs', 'enzyme']",921,True,0,1
Firebase function test initialisation fails,"<p>Trying to test my Firebase cloud functions. I have followed the documentation and I get the following error when running the tests. I have tried generating different keys, I get to the service key window through Firebase so it is the correct project. The error occurs when I run the tests: <code>npm test</code></p>
<pre><code>Error: Options object {&quot;_fieldsProto&quot;:{&quot;foo&quot;:{&quot;stringValue&quot;:&quot;bar&quot;}},&quot;_ref&quot;:{&quot;_firestore&quot;:{&quot;_settings&quot;:{&quot;credentials&quot;:{&quot;private_key&quot;:&quot;KEY&quot;,&quot;client_email&quot;:&quot;project@appspot.gserviceaccount.com&quot;},&quot;projectId&quot;:&quot;project&quot;,&quot;firebaseVersion&quot;:&quot;8.13.0&quot;,&quot;libName&quot;:&quot;gccl&quot;,&quot;libVersion&quot;:&quot;3.8.6 fire/8.13.0&quot;},&quot;_settingsFrozen&quot;:false,&quot;_serializer&quot;:{&quot;allowUndefined&quot;:false},&quot;_projectId&quot;:&quot;project&quot;,&quot;registeredListenersCount&quot;:0,&quot;_lastSuccessfulRequest&quot;:0,&quot;_backoffSettings&quot;:{&quot;initialDelayMs&quot;:100,&quot;maxDelayMs&quot;:60000,&quot;backoffFactor&quot;:1.3},&quot;_preferTransactions&quot;:false,&quot;_clientPool&quot;:{&quot;concurrentOperationLimit&quot;:100,&quot;maxIdleClients&quot;:1,&quot;activeClients&quot;:{},&quot;terminated&quot;:false,&quot;terminateDeferred&quot;:{&quot;promise&quot;:{}}}},&quot;_path&quot;:{&quot;segments&quot;:[&quot;document&quot;,&quot;path&quot;],&quot;projectId&quot;:&quot;project&quot;,&quot;databaseId&quot;:&quot;(default)&quot;},&quot;_converter&quot;:{}},&quot;_serializer&quot;:{&quot;allowUndefined&quot;:false},&quot;_readTime&quot;:{&quot;_seconds&quot;:1602169684,&quot;_nanoseconds&quot;:285000000},&quot;_createTime&quot;:{&quot;_seconds&quot;:1602169684,&quot;_nanoseconds&quot;:285000000},&quot;_updateTime&quot;:{&quot;_seconds&quot;:1602169684,&quot;_nanoseconds&quot;:285000000}} has invalid key &quot;_fieldsProto&quot;
    at /home//Desktop/Work/test-app/app/functions/node_modules/firebase-functions-test/lib/main.js:99:19
    at Array.forEach (&lt;anonymous&gt;)
    at _checkOptionValidity (/home//Desktop/Work/test-app/app/functions/node_modules/firebase-functions-test/lib/main.js:97:26)
    at scheduledWrapped (/home//Desktop/Work/test-app/app/functions/node_modules/firebase-functions-test/lib/main.js:36:13)
    at Object.&lt;anonymous&gt; (/home//Desktop/Work/test-app/app/functions/index.test.js:98:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:791:14)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.exports.requireOrImport (/home//Desktop/Work/test-app/app/functions/node_modules/mocha/lib/esm-utils.js:20:12)
    at Object.exports.loadFilesAsync (/home//Desktop/Work/test-app/app/functions/node_modules/mocha/lib/esm-utils.js:33:34)
    at Mocha.loadFilesAsync (/home//Desktop/Work/test-app/app/functions/node_modules/mocha/lib/mocha.js:427:19)
    at singleRun (/home//Desktop/Work/test-app/app/functions/node_modules/mocha/lib/cli/run-helpers.js:156:15)
    at exports.runMocha (/home//Desktop/Work/test-app/app/functions/node_modules/mocha/lib/cli/run-helpers.js:225:10)
    at Object.exports.handler (/home//Desktop/Work/test-app/app/functions/node_modules/mocha/lib/cli/run.js:366:11)
    at /home//Desktop/Work/test-app/app/functions/node_modules/yargs/lib/command.js:241:49


const test = require('firebase-functions-test')({
     databaseURL: &quot;####&quot;,
     storageBucket: &quot;####&quot;,
     projectId: &quot;#####&quot;,   }, './key.json');
 
 
const myFunctions = require('./index.js');
 
const wrapped = test.wrap(myFunctions.testFunction);
const snap = test.firestore.makeDocumentSnapshot({foo: 'bar'}, 'document/path'); 
wrapped(snap); 
test.cleanup();
</code></pre>
<p>Followed this documentation: <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a></p>
<p>My package.json:</p>
<pre><code>{
  &quot;name&quot;: &quot;functions&quot;,
  &quot;description&quot;: &quot;Cloud Functions for Firebase&quot;,
  &quot;scripts&quot;: {
    &quot;serve&quot;: &quot;firebase emulators:start --only functions&quot;,
    &quot;shell&quot;: &quot;firebase functions:shell&quot;,
    &quot;start&quot;: &quot;npm run shell&quot;,
    &quot;deploy&quot;: &quot;firebase deploy --only functions&quot;,
    &quot;logs&quot;: &quot;firebase functions:log&quot;,
    &quot;test&quot;: &quot;mocha --reporter spec index.test.js&quot;
  },
  &quot;engines&quot;: {
    &quot;node&quot;: &quot;10&quot;
  },
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;dependencies&quot;: {
    &quot;firebase-admin&quot;: &quot;^8.10.0&quot;,
    &quot;firebase-functions&quot;: &quot;^3.6.1&quot;,
    &quot;reportdatasummary&quot;: &quot;file:reportdatasummary&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;firebase-functions-test&quot;: &quot;^0.2.0&quot;,
    &quot;mocha&quot;: &quot;^8.1.3&quot;,
    &quot;reportdatasummary&quot;: &quot;file:reportdatasummary&quot;
  },
  &quot;private&quot;: true
}
</code></pre>
",https://stackoverflow.com/questions/64260624/firebase-function-test-initialisation-fails,"['javascript', 'node.js', 'google-cloud-functions']",191,True,3,1
Create React App test coverage report doesn&#39;t cover all files inside /src,"<p>Application is created with <code>npx create-react-app my-app</code>. Running coverage report with <code>npm test -- --coverage</code> <strong>doesn't cover</strong> all files inside <code>/src</code> folder when checked with html file generated by istanbul, ie., <em>project > coverage > lcov-report > index.html</em> but with <code>npm test -- --coverage --watchAll=false</code> <strong>does cover</strong> all files inside <code>/src</code> folder but <strong>fails</strong> component render test with following error:</p>

<pre><code>Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
</code></pre>

<p>Following are the project details:</p>

<p>Login.js</p>

<pre><code>import React from ""react"";
import { withRouter } from ""react-router"";
export class Login extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      &lt;div className=""page-login bg-img""&gt;
           ...
      &lt;/div&gt;
      );
  }
}

const NewLogin = withRouter(Login);
export default NewLogin;
</code></pre>

<p>Login.test.js</p>

<pre><code>import { render } from ""enzyme"";
import {Login} from ""./components/Login""
describe(`Login page`, () =&gt; {
  it(`Login renders`, () =&gt; {
    render(&lt;Login /&gt;);
  });
});
</code></pre>

<p>Package.json</p>

<pre><code>""react"": ""^16.13.1"",
""react-scripts"": ""^3.4.1"",
""enzyme"": ""^3.11.0"",
""enzyme-adapter-react-16"": ""^1.15.2"",
</code></pre>

<p>Please help, I'm new to react unit testing. Thanks in advance. </p>
",https://stackoverflow.com/questions/61507975/create-react-app-test-coverage-report-doesnt-cover-all-files-inside-src,"['reactjs', 'jestjs', 'enzyme', 'create-react-app', 'react-scripts']",1014,False,3,0
Unit Testing in Python Djnago,"<p>I am using</p>
<p>Django==3.0.3</p>
<p>djangorestframework==3.11.0</p>
<p>python ==3.6.8</p>
<p>I want to write unit testing for API and no need to use any database(no need of mock database)
that mean I want  to mock the database call and write unit test cases</p>
<p>how can i write which property is used for this</p>
<p>Showing my api</p>
<pre><code>@api_view(['POST'])
@permission_classes([IsAuthenticated])
def employee_entry(request):
    try:
        login = User.objects.get(pk=request.user.id)
        validationmsg = ''
        emp_data = request.data
        if not emp_data:
            validationmsg = validation[&quot;FDP15&quot;]
        elif emp_data[&quot;EmployeeName&quot;] is None or emp_data[&quot;EmployeeName&quot;] == '':
            validationmsg = validation[&quot;FDP1&quot;]
        elif emp_data[&quot;EmployeeCode&quot;] is None or emp_data[&quot;EmployeeCode&quot;] == '':
            validationmsg = validation[&quot;FDP2&quot;]
        elif Employee.objects.filter(EmployeeCode=emp_data[&quot;EmployeeCode&quot;]).count() &gt; 0:
            validationmsg = validation[&quot;FDP3&quot;]
        if validationmsg != '':
            return Response({msg: validationmsg}, status=status.HTTP_400_BAD_REQUEST)
        employee = Employee(
            EmployeeName=emp_data[&quot;EmployeeName&quot;],
            EmployeeCode=emp_data[&quot;EmployeeCode&quot;],
            Security=emp_data[&quot;Security&quot;],
            CreatedDate=date.today(),
            CreatedUser=login,
        )
        employee.save()
        if emp_data[&quot;Security&quot;] == 1:
            device = Device.objects.filter(~Q(DeviceStatus=static_values[&quot;const0&quot;]))
            employee.Device.set(device)
        elif emp_data[&quot;Security&quot;] == 0:
            device = Device.objects.filter(~Q(DeviceStatus=static_values[&quot;const0&quot;]), DefaultAccess=True)
            employee.Device.set(device)
        return Response({&quot;EmployeeId&quot;: employee.EmployeeId}, status=status.HTTP_200_OK)
    except(KeyError, TypeError, ValueError) as ex:
        logging.getLogger(&quot;error_logger&quot;).exception(repr(ex))
        return Response({msg: validation[&quot;FDP21&quot;]}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as ex:
        logging.getLogger(&quot;error_logger&quot;).exception(repr(ex))
        return Response({msg: validation[&quot;FDP23&quot;]}, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
",https://stackoverflow.com/questions/64763679/unit-testing-in-python-djnago,"['django', 'unit-testing', 'python-unittest', 'django-unittest', 'python-unittest.mock']",46,False,0,0
Any useful alternative to foo.go + foo_test.go,"<p>For unit testing a Go code base, is there any reasonable alternative to the <code>foo.go</code> and <code>foo_test.go</code> pattern? The only ""concern"" is having all those extra files in the same place on the filesystem. It might be nice to put the test files in a central place, but that might not work due to the way Go packages work.</p>
",https://stackoverflow.com/questions/59792942/any-useful-alternative-to-foo-go-foo-test-go,"['go', 'testing']",141,True,-2,1
python - assert complex almost equal,"<p>I am aware that there is <code>numpy.testing.assert_almost_equal</code>, but that only works for float and not complex. With that said, I can actually declare my own function that does this:</p>

<pre class=""lang-py prettyprint-override""><code>def assert_complex_almost_equal(complex_number, ground_truth, **kwargs):
    assert numpy.testing.assert_almost_equal(complex_number.real, ground_truth.real, **kwargs)
    and numpy.testing.assert_almost_equal(complex_number.imag, ground_truth.imag, **kwargs)
</code></pre>

<p>I'd just like to confirm if there is no built-in or <code>numpy</code> function that does this in the current version?</p>

<p>In case needed I use <code>pytest</code> for unit testing.</p>
",https://stackoverflow.com/questions/62296674/python-assert-complex-almost-equal,"['python', 'numpy', 'unit-testing', 'complex-numbers']",445,False,0,0
Mocked Object not returning expected value,"<p>I'm unit testing my dao. I create a list, I add an object to my list and I tell mockito when my method is called, to return my list with a single object. However, when I look at what's returned from my dao method, it's an empty list. I'm not sure what I'm missing.</p>
<pre><code>@InjectMocks
private Dao dao;

@Mock
private JdbcTemplate jdbcTemp;

@Test
public void testGetData() {
    List&lt;MyObj&gt; list = new ArrayList&lt;&gt;();
    MyObj myObj = new MyObj();
    myObj.setMethod(&quot;method val&quot;);
    list.add(myobj);

    Mockito.when(jdbcTemp.query(anyString(), Mockito.any(PreparedStatementSetter.class),
            Mockito.any(Dao.MyRowMapper.class))).thenReturn(list);

    List&lt;MyObj&gt; res = dao.getData(param1, param2); // this is empty, instead of having a value of 1

    Assertions.assertThat(res).isNotNull();
}
</code></pre>
<p>My Dao class:</p>
<pre><code>public List&lt;MyObj&gt; getData(String arg1, String arg2) {
    List&lt;MyObj&gt; list = new ArrayList&lt;MyObj&gt;();

    try {

        list.addAll(jdbcTemp.query(query, new PreparedStatementSetter() {
            public void setValues(PreparedStatement pstmt) throws SQLException {
                pstmt.setString(PARAM_ONE, arg1);
                pstmt.setString(PARAM_TWO, arg2);
            }
        }, new MyRowMapper()));
    } catch (Exception exp) {
        
    }
    
    return list;
}
</code></pre>
",https://stackoverflow.com/questions/63727555/mocked-object-not-returning-expected-value,"['java', 'mockito']",211,True,0,1
Can not instantiate proxy of class error when writing unit test,"<p>I have the following classes:</p>
<pre><code>   public ExtractUkFileFunction (UkExtractFileHandler fileHandler)
        {
            _fileHandler = fileHandler;
        }
</code></pre>
<p>and</p>
<pre><code>public class UkExtractFileHandler : ExtractFileHandler&lt;UkExtractFileHandler.FileMapper&gt;
{
    public UkExtractFileHandler(ILoggerFactory loggerFactory, IRecordParser recordParser, IUnzipper unzipper, IFileStore fileStore, ILocationService locationService) 
        : base(recordParser, unzipper, fileStore, locationService)
    {
        Logger = loggerFactory.Create&lt;ExtractFileHandler&gt;();
    }
</code></pre>
<p>As a starting point for my unit tests I just want to build this class/check that it can be built. I've tried the following:</p>
<pre><code> [Test]
    public void Construct_ExtractUkFileFunction_ExpectSuccess()
    {
        var mockLoggerFactory = new Mock&lt;ILoggerFactory&gt;();
        var mockRecordParser = new Mock&lt;IRecordParser&gt;();
        var mockUnzipper = new Mock&lt;IUnzipper&gt;();
        var mockFileStore = new Mock&lt;IFileStore&gt;();
        var mockLocationService = new Mock&lt;ILocationService&gt;();
        
        var mockFileHandler = new Mock&lt;ExtractFileHandler&gt;
            (mockLoggerFactory.Object, mockRecordParser.Object, mockUnzipper.Object, mockFileStore.Object, mockLocationService.Object);
        var extractUkFileFunction = new ExtractUkFileFunction(mockFileHandler.Object);

        Assert.IsNotNull(extractUkFileFunction ); 
    }
</code></pre>
<p>However I receive the error:</p>
<pre><code>Can not instantiate proxy of class: Core.Handlers.UkExtractFileHandler.
    Could not find a constructor that would match given arguments:
    Castle.Proxies.ILoggerFactoryProxy
    Castle.Proxies.IRecordParserProxy
    Castle.Proxies.IUnzipperProxy
    Castle.Proxies.IFileStoreProxy
    Castle.Proxies.ILocationServiceProxy
</code></pre>
<p>I do not have lots of experience with C# unit testing or Moq, so any advice would be appreciated. Thanks!</p>
",https://stackoverflow.com/questions/62776631/can-not-instantiate-proxy-of-class-error-when-writing-unit-test,"['c#', 'unit-testing', 'moq']",1529,True,0,1
Firebase sinon / chai unit testing in nodeJS,"<p>Trying to get offline unit testing working for my Firebase project.  I can't seem to figure out why the following test isn't running and logging console.log('b') &amp; ('c').  I assume I've stubbed it incorrectly but can't figure it out.  By the test output and console.log it only returns 'a' and then also returns true.</p>

<p>Help appreciated.</p>

<pre><code>index.js

function createFreeAgents(admin) {
    admin.database().ref('/CONFIG').update({ 
        ""agencyActive"" : false,
        ""listCount"" : true
    });
    **console.log('a')**
    admin.database().ref('/FREEAGENTPICK').once('value', snap =&gt; {
        **console.log('b')**
        snap.forEach(team =&gt; {
            **console.log('c')**
            let newAgentObject = {
                ""rookie"": 2,
                ""senior"": 4,
            }

            admin.database().ref('/FREEAGENTPICK/' + team.key).update(newAgentObject);
        })
    })

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

<pre><code>const chai = require('chai');
const expect = chai.expect;
const assert = chai.assert;

const sinon = require('sinon');
const admin = require('firebase-admin');
const test = require('firebase-functions-test')();
const functions = require('../index');

describe('it should update a players score', () =&gt; {
    let adminInitStub, adminDatabaseStub;

    beforeEach(() =&gt; {            
        adminInitStub = sinon.stub(admin, 'initializeApp');
        adminDatabaseStub = sinon.stub(admin, 'database');
    });

    afterEach(() =&gt; {
        adminInitStub.restore();
        test.cleanup();
    });

    describe('run createFreeAgent()', () =&gt; {  
        it('should run createFreeAgents() and return true', () =&gt; {  
            // Stubs
            databaseStub = sinon.stub();
            refStub = sinon.stub();
            updateStub = sinon.stub();

            // Values
            configUpdate = { 
                ""agencyActive"" : false,
                ""listCount"" : true
            };

            // DBMocks
            adminDatabaseStub = Object.defineProperty(admin, 'database', { get: () =&gt; databaseStub });
            databaseStub.returns({ ref: refStub }); 

            refStub
                .withArgs('/CONFIG')
                .onFirstCall()
                .returns({ update: updateStub })
                .withArgs('/FREEAGENTPICK')
                .onFirstCall()
                .returns({ once: updateStub })

            updateStub
                .onFirstCall()
                .returns(configUpdate)
                .onSecondCall()
                .returns(snapFreeAgent)

            assert.deepEqual(updateStub('/CONFIG'), configUpdate);

            result = functions.createFreeAgents(adminDatabaseStub);
            expect(result).to.equal(true);

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

<pre><code>test output

  it should update a players score
    run createFreeAgent()
a
      √ should run createFreeAgents() and return true


  1 passing (13ms)

</code></pre>
",https://stackoverflow.com/questions/62481203/firebase-sinon-chai-unit-testing-in-nodejs,"['firebase', 'unit-testing', 'firebase-realtime-database', 'chai', 'sinon']",96,False,0,1
How do you write object literal line coverage in Typescript Mocha unit-test?,"<p><strong>Lead:</strong>
New to working with typescript and writing unit tests using <em>Mocha</em> and <em>Chai</em>.</p>
<p><strong>Question</strong>
Any tips on how I can go about getting 100% line coverage in unit tests with an object literal that isn’t in a class?  Trying to avoid going static if at all possible, but unit testing still has to hit 100% to pass.</p>
<pre class=""lang-js prettyprint-override""><code>// constants.ts
export default {
    path: “./example”,
    name: “Example Name”
}
</code></pre>
<pre class=""lang-js prettyprint-override""><code>// constants.spec.ts
// How do I unit test ‘export default’ for 100% line coverage?
// I have tried

import chai from &quot;chai&quot;;
import * as constants from “./constants.ts”;

describe(“constants”, () =&gt; {
    it(“Constants literals should have a length of 2“, () =&gt; {
        chai.expect(constants.default.length).equal(2); 
    });
});

// The mocha test succeeds, but the line still says it hasn’t been tested.
</code></pre>
",https://stackoverflow.com/questions/64084759/how-do-you-write-object-literal-line-coverage-in-typescript-mocha-unit-test,"['node.js', 'typescript', 'unit-testing', 'mocha.js', 'chai']",177,True,0,1
Babel not recognizing TypeScript syntax when running test using jest on TypeScript file,"<pre><code>&quot;dependencies&quot;: {
    &quot;@types/node&quot;: &quot;^14.14.13&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/preset-typescript&quot;: &quot;^7.12.7&quot;,
    &quot;@types/jest&quot;: &quot;^26.0.19&quot;,
    &quot;jest&quot;: &quot;^26.6.3&quot;,
    &quot;ts-jest&quot;: &quot;^26.4.4&quot;,
    &quot;typescript&quot;: &quot;^4.1.3&quot;
  },
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;jest&quot;
  }
</code></pre>
<p>Above is my current package.json file. I'm trying to run test on single file. Right from the beginning of my function, it points at semicolon then I get bunch of babel parser errors. I npm installed all the related dependencies for unit testing on typescript. Am I missing more dependencies to install or is it more of configuration error?</p>
<pre><code>const getTwoSum = (file: string[]) 
</code></pre>
<pre><code>    at Parser._raise (node_modules/@babel/parser/src/parser/error.js:60:45)
          at Parser.raiseWithData (node_modules/@babel/parser/src/parser/error.js:55:17)
          at Parser.raise (node_modules/@babel/parser/src/parser/error.js:39:17)
          at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:139:16)
          at Parser.expect (node_modules/@babel/parser/src/parser/util.js:116:28)
          at Parser.parseParenAndDistinguishExpression (node_modules/@babel/parser/src/parser/expression.js:1364:14)
          at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1035:21)
          at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:565:23)
          at Parser.parseUpdate (node_modules/@babel/parser/src/parser/expression.js:545:21)
          at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:529:17)
</code></pre>
",https://stackoverflow.com/questions/65299930/babel-not-recognizing-typescript-syntax-when-running-test-using-jest-on-typescri,"['javascript', 'typescript', 'unit-testing', 'jestjs', 'babeljs']",419,False,0,0
How to get click or class to work in Jest unit test,"<p>I am learning Jest for unit testing and I seem to be hitting a hurdle.</p>

<p>I am trying to check that when my menu <code>a</code> is clicked, that the 'active' <code>class</code> is applied.</p>

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

<p><strong>HTML</strong></p>

<pre><code> &lt;div class=""form-group""&gt;
        &lt;div class=""col-12""&gt;
          &lt;ul class=""nav nav-tabs"" id=""myTab"" role=""tablist""&gt;
            &lt;li class=""nav-item""&gt;
              &lt;a id=""activeBlogs-tab"" class=""nav-link active"" data-toggle=""tab"" href=""#activeBlogs"" role=""tab""
                  aria-controls=""activeBlogs"" aria-selected=""true"" style=""border-right: 1px solid lightgray""&gt;
                Active blogs
              &lt;/a&gt;
            &lt;/li&gt;
            &lt;li class=""nav-item""&gt;
              &lt;a id=""closedBlogs-tab"" class=""nav-link"" data-toggle=""tab"" href=""#closedBlogs"" role=""tab"" aria-selected=""false""
                  aria-controls=""closedBlogs""&gt;
                Closed blogs
              &lt;/a&gt;
            &lt;/li&gt;
            &lt;li id=""addTab"" class=""nav-item ml-auto""&gt;
              &lt;router-link to=""/add"" class=""nav-link bg-info text-white"" exact&gt;Add a new blog&lt;/router-link&gt;
            &lt;/li&gt;
          &lt;/ul&gt;
        &lt;/div&gt;
      &lt;/div&gt;
</code></pre>

<p><strong>Test</strong></p>

<pre><code>it('Checks ""ClosedBlogs"" component displayed when clicking ""Closed Blogs tab""', () =&gt; {
    //wrapper.find('#closedBlogs-tab').trigger('click')


    // const mockCallBack = jest.fn();

    // const closedMenuClick = shallow((&lt;a onClick={mockCallBack}&gt;Closed blogs&lt;/a&gt;));
    // closedMenuClick.find('#closedBlogs-tab').simulate('click');

    //wrapper.find('#closedBlogs-tab').simulate('click');

    const fourthStar = wrapper.find('#closedBlogs-tab')
    fourthStar.trigger('click')
    expect(fourthStar.classes()).toBe(""nav-link active"")

    // expect(wrapper.find('#activeBlogs-tab').attributes().class).toBe(""nav-link"")
    // expect(wrapper.find('#activeBlogs').attributes().class).toBe(""tab-pane fade"")

    // expect(wrapper.find('#closedBlogs-tab').attributes().class).toBe(""nav-link active"")
    // expect(wrapper.find('#closedBlogs').attributes().class).toBe(""tab-pane fade active"")
})
</code></pre>

<p>All commented out code is what I have tried but they all error with various errors as shown below</p>

<pre><code> Expected: ""tab-pane fade active""
    Received: ""tab-pane fade show active""

      77 | 
      78 |         expect(wrapper.find('#activeBlogs-tab').attributes().class).toBe(""nav-link active"")
    &gt; 79 |         expect(wrapper.find('#activeBlogs').attributes().class).toBe(""tab-pane fade active"")
         |                                                                 ^
      80 |     })
</code></pre>



<pre><code>Expected: ""nav-link active""
Received: ""nav-link""

  65 |         // expect(wrapper.find('#activeBlogs').attributes().class).toBe(""tab-pane fade"")
  66 | 
&gt; 67 |         expect(wrapper.find('#closedBlogs-tab').attributes().class).toBe(""nav-link active"")
     |                                                                     ^
  68 |         expect(wrapper.find('#closedBlogs').attributes().class).toBe(""tab-pane fade active"")
  69 |     })
</code></pre>



<pre><code>Expected: ""nav-link active""
Received: [""nav-link""]

  59 |         fourthStar.trigger('click')
  60 |         //expect(fourthStar.classes()).toContain('active')
&gt; 61 |         expect(fourthStar.classes()).toBe(""nav-link active"")
     |                                      ^
  62 | 
  63 |         // expect(wrapper.find('#activeBlogs-tab').attributes().class).toBe(""nav-link"")
  64 |         // expect(wrapper.find('#activeBlogs').attributes().class).toBe(""tab-pane fade"")
</code></pre>



<pre><code>Expected value: ""active""
Received array: [""nav-link""]

  58 |         const fourthStar = wrapper.find('#closedBlogs-tab')
  59 |         fourthStar.trigger('click')
&gt; 60 |         expect(fourthStar.classes()).toContain('active')
     |                                      ^
  61 | 
  62 |         // expect(wrapper.find('#activeBlogs-tab').attributes().class).toBe(""nav-link"")
  63 |         // expect(wrapper.find('#activeBlogs').attributes().class).toBe(""tab-pane fade"")
</code></pre>
",https://stackoverflow.com/questions/60598336/how-to-get-click-or-class-to-work-in-jest-unit-test,"['unit-testing', 'jestjs', 'vue-test-utils']",1073,False,0,1
Service Layer Unit testing with Sinon.js - Error &quot;x&quot; is not a constructor,"<p>I have followed the medium guide :
<a href=""https://medium.com/@tehvicke/integration-and-unit-testing-with-jest-in-nodejs-and-mongoose-bd41c61c9fbc"" rel=""nofollow noreferrer"">https://medium.com/@tehvicke/integration-and-unit-testing-with-jest-in-nodejs-and-mongoose-bd41c61c9fbc</a> trying to develop a test suite. My code is exactly like his but I am having the <strong>TypeError: Tournament is not a constructor</strong></p>

<p>I put some code, so you can see what I am trying to do.</p>

<p><strong>TournamentService.js</strong></p>

<pre><code>const createTournament = (Tournament) =&gt; (tournamentObj) =&gt; {
  const {name, creator} = tournamentObj;
  const newTournament = new Tournament({name, creator});
  return newTournament.save();
};
</code></pre>

<p><strong>TournamentService.test.js</strong></p>

<pre><code>const TournamentService = require(""../TournamentService"");
const sinon = require(""sinon"");

describe(""create Tournament test"", () =&gt; {
  it(""creates a tournament"", () =&gt; {
    const save = sinon.spy();
    console.log(""save "", save);
    let name;
    let creator;

    const MockTournamentModel = (tournamentObject) =&gt; {
      name = tournamentObject.name;
      creator = tournamentObject.creator;
      return {
        ...tournamentObject,
        save,
      };
    };

    const tournamentService = TournamentService(MockTournamentModel);
    const fintoElemento = {
      name: ""Test tournament"",
      creator: ""jest"",
    };

    tournamentService.createTournament(fintoElemento);
    const expected = true;
    const actual = save.calledOnce;

    expect(actual).toEqual(expected);
    expect(name).toEqual(""Test tournament"");
  });
});
</code></pre>
",https://stackoverflow.com/questions/61953371/service-layer-unit-testing-with-sinon-js-error-x-is-not-a-constructor,"['javascript', 'node.js', 'mongoose', 'jestjs', 'sinon']",233,True,0,1
How to run mocha and node together,"<p>I'm working on mocha to do unit testing for my API's, My requirement is to run mocha first and if mocha gets success it should node next in a single command.</p>
<p>Now we are using <strong>npm test</strong> to run mocha and <strong>node server</strong> to start the server separately. But it should happen in a single command</p>
",https://stackoverflow.com/questions/65473876/how-to-run-mocha-and-node-together,"['node.js', 'mocha.js', 'chai']",56,False,0,0
How to unit test OidcSecurityService.Auth() with jasmine?,"<p>I am using Jasmine for unit testing. And I am using OidcSecurityService. So I made a mock for it, like this:</p>
<pre><code>export class OidcSecurityServiceStub{
  getToken(){
     return 'some_token_eVbnasdQ324';
  }
}

</code></pre>
<p>and I have this component:</p>
<pre><code>export class AutoLoginComponent implements OnInit {
  lang: any;

  constructor(public oidcSecurityService: OidcSecurityService) {}

  /**
   * responsible that user will be redirected to login screen.
   */
  ngOnInit() {
      this.oidcSecurityService.checkAuth().subscribe(() =&gt; this.oidcSecurityService.authorize());
  }

}

</code></pre>
<p>and this how the spec looks like now:</p>
<pre><code>describe('AutoLoginComponent', () =&gt; {
  let component: AutoLoginComponent;
  let fixture: ComponentFixture&lt;AutoLoginComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ AutoLoginComponent ],
      providers:    [ {provide: OidcSecurityService, useClass: OidcSecurityServiceStub} ]
    })
    .compileComponents();
  }));

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

  it('should create autologin component ',  () =&gt; {

    const fixture  = TestBed.createComponent(AutoLoginComponent);
    expect(component).toBeTruthy();
  });
});

</code></pre>
<p>But I get this error:</p>
<pre><code>NullInjectorError: R3InjectorError(DynamicTestModule)[OidcSecurityService -&gt; OidcSecurityService]: 
  NullInjectorError: No provider for OidcSecurityService!
</code></pre>
<p>So what I have to change?</p>
<p>Thank you</p>
<p>So I made this change:</p>
<pre><code>import { AuthOptions } from 'angular-auth-oidc-client/lib/login/auth-options';
import { of } from 'rxjs';

export class OidcSecurityServiceStub {
  getToken() {
    return 'some_token_eVbnasdQ324';
  }

  checkAuth(url: string) {
    return of(url);
  }

  authorize(authOptions?: AuthOptions){
    return authOptions.urlHandler('http://localhost');
  }
}
</code></pre>
<p>but then I get this error:</p>
<pre><code>AfterAll TypeError: Cannot read property 'urlHandler' of undefined
</code></pre>
",https://stackoverflow.com/questions/64355586/how-to-unit-test-oidcsecurityservice-auth-with-jasmine,"['angular', 'typescript', 'jasmine', 'istanbul', 'angular-auth-oidc-client']",1099,True,-1,1
How to Run Selenium Tests in Jenkins For C#,"<p>Can someone please help me with easy steps on how to run the selenium WebDriver scripts (written in C# in Visual Studio Communities unit testing) in Jenkins and get results?</p>

<p>I went through some youtube videos, but could not get correct/exact steps that works for me. So, want to start afresh with someone's help.</p>

<p>Regards,
Alok</p>
",https://stackoverflow.com/questions/60057855/how-to-run-selenium-tests-in-jenkins-for-c,"['jenkins', 'selenium-webdriver']",284,True,-1,1
How would I unit test this function that takes request as a param?,"<p>Hello I am brand new to unit testing and I just cant wrap my head around it. This is the simplest function I need to test and I am clueless as how to even do that. I know I need to pass a mock request object I think but beyond that I'm pretty lost. Could use some guidance. </p>

<pre><code>def get_all_zones(request):
    user = request.user
    all_site = get_objects_for_user(user, 'sitehotspot_portal', klass=SiteHotspot).values_list('uid', 'name')
    all_site = [list(i) for i in all_site]
    all_area = get_objects_for_user(user, 'areashotspot_portal', klass=AreasHotspot).values_list('uid', 'name')
    all_area = [list(i) for i in all_area]
    all_sphere = get_objects_for_user(user, 'spherehotspot_portal', klass=SphereHotspot).values_list('uid', 'name')
    all_sphere = [list(i) for i in all_sphere]
    all_zones = all_area + all_site + all_sphere

    return(all_zones)```
</code></pre>
",https://stackoverflow.com/questions/60212612/how-would-i-unit-test-this-function-that-takes-request-as-a-param,"['django', 'unit-testing']",115,False,-1,2
Cannot find module &#39;@app/core&#39; - alias with jest and nodejs,"<p>I am trying to run jest from a runner with nestjs and node.js and got the following error
and did not manage to run a test with a custom alias</p>
<pre><code>        { Error: Cannot find module '@app/core'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Module.load (internal/modules/cjs/loader.js:653:32) code: 'MODULE_NOT_FOUND' }
</code></pre>
<p>my jest-e2e.json that the jest run is configured as follows:</p>
<pre><code>{
  &quot;moduleFileExtensions&quot;: [&quot;js&quot;, &quot;json&quot;, &quot;ts&quot;],
  &quot;rootDir&quot;: &quot;..&quot;, // also tried '.'
  &quot;moduleNameMapper&quot;: {
    &quot;@app/(.*)&quot;: &quot;&lt;rootDir&gt;/src/$1&quot;
  },
  &quot;testEnvironment&quot;: &quot;node&quot;,
  &quot;testRegex&quot;: &quot;.e2e-spec.ts$&quot;,
  &quot;transform&quot;: {
    &quot;^.+\\.(t|j)s$&quot;: &quot;ts-jest&quot;
  }
}
</code></pre>
<p>app/core is defined in the tsconfig.json as follows:</p>
<pre><code>    &quot;paths&quot;: {
      &quot;*&quot;: [&quot;types/*&quot;],
      &quot;@app/*&quot;: [&quot;*&quot;]
    }
</code></pre>
<p>and working well in unit testing with jest:</p>
<pre><code>  &quot;jest&quot;: {
    &quot;moduleFileExtensions&quot;: [
      &quot;js&quot;,
      &quot;json&quot;,
      &quot;ts&quot;
    ],
    &quot;rootDir&quot;: &quot;src&quot;,
    &quot;moduleNameMapper&quot;: {
      &quot;@app/(.*)&quot;: &quot;&lt;rootDir&gt;/$1&quot;
    },
    &quot;testRegex&quot;: &quot;.spec.ts$&quot;,
    &quot;transform&quot;: {
      &quot;^.+\\.(t|j)s$&quot;: &quot;ts-jest&quot;
    },
    &quot;collectCoverageFrom&quot;: [
      &quot;**/*.(t|j)s&quot;
    ],
    &quot;coverageDirectory&quot;: &quot;../coverage&quot;,
    &quot;testEnvironment&quot;: &quot;node&quot;
  }
</code></pre>
<pre><code></code></pre>
",https://stackoverflow.com/questions/64516826/cannot-find-module-app-core-alias-with-jest-and-nodejs,"['node.js', 'webpack', 'jestjs', 'alias', 'nestjs']",806,False,0,0
Call function inside of another function,"<p>Using the factory pattern, i wrote snippets of code that use firebase cloud functions :</p>

<pre><code>//Notice that when instantiated it does calculations and returns a value
function sumAndMultiply(int number) {
    function sum(i) {
        return i + 1;
    }
    function multiply(i) {
        return i * 3;
    }

    const x = sum(number);
    const y = multiply(x);
    return y;
}
</code></pre>

<p>everting working fine, but, what i can make if i need to unit test <code>multiply()</code> or <code>sum()</code> function?</p>

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

    it('test sum function', () =&gt; {

        //How i can call sum function without call sumAndMultiply?
        let result = sum(3);
        expect(result == 4);
    });

    it('test multiply function', () =&gt; {

        //How i can call multiply function without call sumAndMultiply?
        let result = multiply(3);
        expect(result == 9);
    });
});
</code></pre>

<p>As I'm talking about unit testing, one idea is to avoid editing the code used for production, but changes that make the code more readable or better are accepted</p>
",https://stackoverflow.com/questions/61788335/call-function-inside-of-another-function,"['javascript', 'unit-testing', 'jestjs']",128,True,0,1
FormData is not defined in React Jest,"<p>I am writing a unit testing code for the React project. I am trying to test one function</p>

<pre><code>//function aa
export const login = (values) =&gt; async =&gt; (dispatch) =&gt; {
  let bodyFormData = new FormData();

  bodyFormData.append('username', values.login);
  bodyFormData.append('password', values.password);
  return await axios({
   method: 'post',
   url: url,
   data: bodyFormData
  }
}

//aa test
it(""Login Action"", async () =&gt; {
  afterEach(() =&gt; {
    store.clearActions();
  });
  const values = {
    login: ""aaaaa"",
    password: ""bbbbb""
  };
  const expectedResult = { type: ""LOGIN_PASS"" };

  const result = await store.dispatch(login(values));
  expect(result).toEqual(expectedResult);
});
</code></pre>

<p>In the browser, this works ok. but when testing I get below error</p>

<p><strong>ReferenceError: FormData is not defined</strong></p>

<p>I tried to use this module but no luck...
<a href=""https://www.npmjs.com/package/form-data"" rel=""noreferrer"">https://www.npmjs.com/package/form-data</a></p>

<p>I do not want to just test axios, I need to test full function.</p>
",https://stackoverflow.com/questions/59726506/formdata-is-not-defined-in-react-jest,"['reactjs', 'unit-testing', 'jestjs']",15026,True,6,3
Spring Dependency Injection - Private fields - Anti Pattern? Why does it even work?,"<p>I am generally a c# developer but working on Java now and then I see a lot of dependency injection using Spring on <em>private</em> properties, with no public way of setting the value.  I was surprised this actually works, but I guess it’s possible via reflection?</p>
<p>Surely this is terrible practice?!  I can't see how anyone unit testing or inspecting the class would possibly know that a private member needs to be set from some external framework.</p>
<p>How would you even set the property when you are unit testing?  Or just using the class stand alone?</p>
<p>I guess you have to use spring in your unit tests which seems really overkill. Surely you should be able to unit test without your IOC container?   The class becomes completely dependent on spring...</p>
<p>Have I missed anything here?</p>
<p>Should dependency injection not always involve a public setter of some kind, and preferably use the constructor if possible?  Or is there something about Java I am missing...?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/63600604/spring-dependency-injection-private-fields-anti-pattern-why-does-it-even-wo,"['java', 'spring', 'dependency-injection', 'inversion-of-control', 'ioc-container']",1105,True,0,3
Jest throws error about missing global function (vue.prototype),"<p>I'm trying to set up unit testing for my Vue application.</p>
<p>I'm using Jest. I have mounted a component and I want to run tests on it. This component uses a global function (Vue.prototype), called aao, which fails to run in my tests.</p>
<p>Error message:</p>
<pre><code>console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
[Vue warn]: Error in beforeMount hook: &quot;TypeError: this.$aao is not a function&quot;

found in

---&gt; &lt;MyProfile&gt;
       &lt;Root&gt;
</code></pre>
<p>example.spec.ts:</p>
<pre><code>import editUser from '@/components/forms/editUser.vue';
import TestComponent from '@/pages/user/UserMyProfile.vue';
import { shallowMount } from '@vue/test-utils';
import { expect } from 'chai';
import 'jest';

describe('AppLoadingScreen', () =&gt; {
    let component;

    beforeEach(() =&gt; {
        component = shallowMount(TestComponent);
    });

    it('should render Spinner on mount', () =&gt; {
        expect(component.find(editUser).exists()).to.be.true;
    });
});
</code></pre>
<p>AAO function:</p>
<pre><code>export function dbRequest(
    method: 'get' | 'put' | 'post' | 'delete',
    endpoint: string,
    data: any,
    headers?: any,
    responseType?: 'blob' | 'json'
) {
    return new Promise&lt;any&gt;((resolve, reject) =&gt; {
        ...
    });
}
Vue.prototype.$aao = dbRequest;
</code></pre>
<p>How can I make sure that the test utils knows about this.$aao?</p>
",https://stackoverflow.com/questions/63391695/jest-throws-error-about-missing-global-function-vue-prototype,"['javascript', 'vue.js', 'jestjs']",1238,True,2,1
Best practices for Unit testing with Catch2 in Visual Studio,"<p>I'm new to unit testing in C++ and want to get some advice on this.
I use Visual Studio 2019 for development and I chose Catch2 as my testing library, I also got the Test Adapter for Catch2 installed.</p>

<p>I read docs for both Catch2 and Test Adapter for Catch2 on GitHub, but I still cannot figure out a proper way to use unit test in Visual Studio.</p>

<p>Let's assume that I already have a project with some classes in it and I want to test those classes.
Should I put files with test code in the same project or should I create new test projects within the solution?</p>

<p>When I try the first approach, Test Explorer doesn't discover tests unless I comment out the main() function of the project.
With second approach, I get a bunch of unresolved external symbol errors for my classes' methods, although I set correct relative paths to header files and referenced the main project from the test project:</p>

<pre><code>LNK2019 unresolved external symbol ""public: bool __thiscall MyClass::Check(int,int)"" (?Check@MyClass@@QAE_NHH@Z) referenced in function ""void __cdecl ____C_A_T_C_H____T_E_S_T____0(void)"" (?____C_A_T_C_H____T_E_S_T____0@@YAXXZ)
</code></pre>

<p>I would appreciate if someone show me a correct way to do unit testing with Catch2 in VS.</p>
",https://stackoverflow.com/questions/59645381/best-practices-for-unit-testing-with-catch2-in-visual-studio,"['unit-testing', 'visual-c++', 'catch-unit-test', 'catch2']",9443,True,6,1
Referencing a .Net Core 3.1 project from a .Net Standard Class Library,"<p>So I have a <code>.NET Core 3.1</code> project. I am trying to create a unit testing project to go along with it. I have created a <code>.NET Standard 2.1 Class Library</code> for this purpose. I'm then trying to add a reference to the main project, in order to be able to reference code from there. This isn't working, as I get the following compilation errors:</p>

<blockquote>
  <p>'..\MyProj\MyProj.csproj' targets 'netcoreapp3.1'. It cannot be
  referenced by a project that targets '.NETStandard,Version=v2.1'.
  Project MyProj is not compatible with netstandard2.1
  (.NETStandard,Version=v2.1). Project MyProj supports: netcoreapp3.1
  (.NETCoreApp,Version=v3.1)    Test (test\Test)</p>
</blockquote>

<p>So this does make sense to me, as I understand why <code>.NET Core</code> wouldn't be able to reference a <code>.NET Standard</code> project.<br> But then how can I create a Unit Testing project? Is it possible to create a <code>.NET Core 3.1 Class Library</code>? From everything I have read, it seems like that doesn't exist. </p>

<p>How can I set up a unit test project that references the main project?</p>
",https://stackoverflow.com/questions/59670181/referencing-a-net-core-3-1-project-from-a-net-standard-class-library,"['c#', '.net', 'unit-testing', '.net-core', '.net-standard']",9441,True,0,2
What can I do to prevent the method from being called when creating Unit Test?,"<p>I want to emphasize that I am fairly new to creating Unit Test but I've been searching far and wide through google and documentation but I can't find a solution or alternative. So currently I am trying to create Unit test for a microservice my team mate and I are working on. The class constructor is structured as follows</p>

<pre><code> public Constructor(IOptions&lt;AMQ_Config&gt; amqConfig, IConfiguration configuration)
        {
            this.amqConfig = amqConfig.Value;
            this.amqConfig.UserName = configuration[""AMQ:UserName""];
            this.amqConfig.Password = configuration[""AMQ:Password""];
            //this.errorTypeConfig = errorTypeConfig.Value;
            this.configuration = configuration;
            AMQSubscriber();
        }
</code></pre>

<p>When I create a new instance of the constructor in the Unit Test it will always call and iterate through the <code>AMQSubscriber();</code> method. Naively I just made a duplicate constructor that excludes the method and adds another parameter:</p>

<pre><code>public UnitTestConstructor(IOptions&lt;AMQ_Config&gt; amqConfig, IConfiguration configuration, IConnection connection)
        {
            this.amqConfig = amqConfig.Value;
            this.amqConfig.UserName = configuration[""AMQ:UserName""];
            this.amqConfig.Password = configuration[""AMQ:Password""];
            //this.errorTypeConfig = errorTypeConfig.Value;
            this.configuration = configuration;
            this.connection = connection;
        }
</code></pre>

<p>but this was done for unit testing purposes only. I've read around about how its not a good idea to do this because it defeats the purpose of Unit testing but I can't think how to isolate this since most of the methods require or depend on the parameters: <code>IOptions&lt;AMQ_Config&gt; amqConfig, IConfiguration configuration</code>  and our microservice is architectured for Apache NMS AMQ for sending, processing and receiving messages. </p>
",https://stackoverflow.com/questions/60748618/what-can-i-do-to-prevent-the-method-from-being-called-when-creating-unit-test,"['c#', 'unit-testing', 'nms']",400,True,0,1
Vue-Jest (Jest Unit Test) : SyntaxError : Cannot use import statement outside a module,"<p>I am new to Vue Unit Testing and i keep getting the same Error after trying my first test.It seems to work for the first 2 import statements , but not for the epis-spinners one .I tried everything and looked up a lot over the forums and Github , but i couldnt find a solution. everything i try doesnt seem to work. I need help please !</p>

<p>Thanks :)</p>

<p><strong>Error</strong></p>

<pre><code> PASS  test/jesttest.spec.js (5.243s)
  ● Console

    console.log test/jesttest.spec.js:18
      red

 FAIL  test/ExitUserCompany.spec.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 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:

    C:\9raya\anforderungsportal\anforderungsportal\frontend\node_modules\epic-spinners\src\lib.js:1
    ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import HollowDotsSpinner from './components/lib/HollowDotsSpinner.vue';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      73 | import {CompanyService} from ""@/common/api/company.service"";
      74 | import {AssetDBDataService} from ""@/common/api/assetDBData.service"";
    &gt; 75 | import { SelfBuildingSquareSpinner } from 'epic-spinners'
         | ^
      76 | 
      77 |   moment.locale('de');
      78 | 

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1059:14)
      at src/layouts/MainLayout.vue:75:1
      at Object.&lt;anonymous&gt; (src/layouts/MainLayout.vue:290:3)

Test Suites: 1 failed, 1 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        22.188s
</code></pre>

<p><strong>package.json (with Jest config)</strong></p>

<pre><code>{
  ""scripts"": {
    ""serve"": ""vue-cli-service serve --host localhost"",
    ""build"": ""vue-cli-service build"",
    ""lint"": ""vue-cli-service lint"",
    ""test"": ""jest""
  },
  ""dependencies"": {
    ""@babel/polyfill"": ""^7.2.5"",
    ""@babel/runtime"": ""^7.3.1"",
    ""axios"": ""^0.18.0"",
    ""bulma"": ""^0.7.5"",
    ""deep-object-diff"": ""^1.1.0"",
    ""epic-spinners"": ""^1.1.0"",
    ""etcdjs"": ""^2.4.2"",
    ""etcdjs-promise"": ""^1.0.0"",
    ""js-base64"": ""^2.5.1"",
    ""js-file-download"": ""^0.4.9"",
    ""keycloak-js"": ""^4.0.0"",
    ""luxon"": ""^1.17.1"",
    ""moment"": ""^2.24.0"",
    ""register-service-worker"": ""^1.5.2"",
    ""url-loader"": ""^1.0.1"",
    ""vee-validate"": ""^2.2.12"",
    ""vue"": ""2.6.5"",
    ""vue-axios"": ""^2.1.4"",
    ""vue-cookies"": ""^1.6.1"",
    ""vue-datetime"": ""^1.0.0-beta.10"",
    ""vue-router"": ""^3.0.1"",
    ""vue-select"": ""^3.1.0"",
    ""vuedraggable"": ""^2.23.0"",
    ""vuex"": ""^3.1.0"",
    ""vuex-router-sync"": ""^5.0.0""
  },
  ""devDependencies"": {
    ""@babel/plugin-transform-runtime"": ""^7.2.0"",
    ""@vue/cli-plugin-babel"": ""^3.3.0"",
    ""@vue/cli-plugin-eslint"": ""^3.3.0"",
    ""@vue/cli-plugin-pwa"": ""^3.3.0"",
    ""@vue/cli-service"": ""^3.3.0"",
    ""@vue/test-utils"": ""^1.0.0-beta.31"",
    ""ant-design-vue"": ""^1.4.5"",
    ""babel-core"": ""^7.0.0-bridge.0"",
    ""babel-jest"": ""^25.1.0"",
    ""babel-plugin-import"": ""^1.11.0"",
    ""jest"": ""^25.1.0"",
    ""jest-transform-stub"": ""^2.0.0"",
    ""less"": ""^3.9.0"",
    ""less-loader"": ""^4.1.0"",
    ""vue-jest"": ""^3.0.5"",
    ""vue-template-compiler"": ""2.6.5""
  },
  ""jest"": {
    ""moduleFileExtensions"": [
      ""js"",
      ""json"",
      ""vue"",
      ""ts""
    ],
    ""moduleNameMapper"": {
      ""^@/(.*)$"": ""&lt;rootDir&gt;/src/$1"",
      ""^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$"": ""jest-transform-stub""
    },
    ""transform"": {
      "".*\\.(vue)$"": ""vue-jest"",
      ""^.+\\.js$"": ""&lt;rootDir&gt;/node_modules/babel-jest"",
      "".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$"": ""jest-transform-stub""
    },
    ""modulePaths"": [
      ""&lt;rootDir&gt;/src"",
      ""&lt;rootDir&gt;/node_modules""
  ],
  ""transformIgnorePatterns"": [""/node_modules/(?!epic-spinners)/""]
  },
  ""browserslist"": [
    ""&gt; 1%"",
    ""last 2 versions"",
    ""not ie &lt;= 8""
  ]
}
</code></pre>

<p><strong>.babelrc</strong></p>

<pre><code>{
    ""env"": {
      ""test"": {
        ""presets"": [[""@babel/env"", { ""targets"": { ""node"": ""current"" } }]]
      }
    }
  }
</code></pre>

<p><strong>babel.config.js</strong></p>

<pre><code>module.exports = {
  plugins: [
    [
      ""import"",
      { libraryName: ""ant-design-vue"", libraryDirectory: ""es"", style: true }
    ],
    ""@babel/plugin-syntax-dynamic-import""
  ]
}
</code></pre>
",https://stackoverflow.com/questions/60377022/vue-jest-jest-unit-test-syntaxerror-cannot-use-import-statement-outside-a,"['vuejs2', 'jestjs']",4133,True,11,1
useSelector of Undefined,"<p>Hi I am writting unit testing for a component it has redux in it. While testing it , throws an error UseSelector state undefined. UseSelector will be updated once after getting response from the api. Till that its value is undefined. But while unit tetsing it throws error on the first itself . How to overcome this issue.</p>

<p>Test File</p>

<pre><code>import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { act } from 'react-dom/test-utils';
import '@testing-library/jest-dom/extend-expect';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import LinkApplication from '../index';
import {reducer} from '../../../redux/summary/reducer';
let INITIAL_STATES = {
    isFetching: false,
    errorMessage: """",
    requestExtensionErrorMessage: """",
    requestExtensionSuccessMessage: """",
    linkApplicationSuccess: """",
    linkApplicationFailure: null,
    linkLoanSuccessMessage: """",
    linkLoanErrorMessage: """",
    LinkApplicationErrorMessage:"""",
  };
function renderWithRedux(
  component,
  { INITIAL_STATES, store = createStore(reducer, INITIAL_STATES) } = {},
) {
  return {
    ...render(&lt;Provider store={store}&gt;{component}&lt;/Provider&gt;),
  };
}
it('sumbits the form', async () =&gt; {
  const onSubmit = jest.fn();
  const { getByText, getByTestId } = renderWithRedux(
    &lt;LinkApplication onSubmit={onSubmit} /&gt;,
  );
  const Dob_Input = getByTestId('dob-input');
  const Phone_Input = getByTestId('phone-input');
  const form = getByTestId('form');
  act(() =&gt; {
    fireEvent.keyPress(Dob_Input, {
      target: { value: '1995-09-27' },
    });
    fireEvent.keyPress(Phone_Input, { target: { value: '9500902621' } });
  });
  expect(Dob_Input.value).toBe('1995-09-27');
  expect(Phone_Input.value).toBe('9500902621');
  await act(() =&gt; {
    fireEvent.submit(form);
  });
  expect(onSubmit).not.toHaveBeenCalled();
})
</code></pre>

<p>Component</p>

<pre><code>const LinkApplication = () =&gt; {
  const dispatch = useDispatch();
  let LinkApplicationErrorMessage = useSelector(
    state =&gt; state.summary.linkApplicationFailure
  );
}
</code></pre>

<p>Error</p>

<pre><code>TypeError: Cannot read property 'linkApplicationFailure' of undefined
const dispatch = useDispatch();
let LinkApplicationErrorMessage = useSelector(
state =&gt; state.summary.linkApplicationFailure
^
);

</code></pre>

<p>Please help me with that.</p>
",https://stackoverflow.com/questions/60668240/useselector-of-undefined,"['reactjs', 'react-testing-library']",4555,True,5,1
Getting System.ArgumentException even while sending the right number of parameters while using Moq setup,"<p>While unit testing my ASP.NET web api controllers,for one of my post requests, I am sending two arguments in the repo function, Like usual I am mocking the repository setup, but even when I send two arguments, I get the argument exception.</p>
<p>Repo Code-</p>
<pre><code>public async Task&lt;TblUser&gt; Register(TblUser user, string password)
    {
        byte[] passwordHash, passwordSalt;
        CreatePasswordHash(password, out passwordHash, out passwordSalt);
        user.APasswordHash = passwordHash;
        user.APasswordSalt = passwordSalt;
        await _context.TblUser.AddAsync(user);
        await _context.SaveChangesAsync();
        return user;
    }
</code></pre>
<p>Controller code-</p>
<pre><code>[HttpPost(&quot;register&quot;)]
    public async Task&lt;IActionResult&gt; Register(UserForRegisterDto userForRegisterDto)
    {
        userForRegisterDto.AUsername = userForRegisterDto.AUsername.ToLower();

        if (await _repo.UserExists(userForRegisterDto.AUsername))
            return BadRequest(&quot;username already exists&quot;);

        if(!ModelState.IsValid || userForRegisterDto.AUsername == null || userForRegisterDto.Password == null || userForRegisterDto.AEmail ==null || userForRegisterDto.Aname ==null)
        {
            return BadRequest(&quot;invalid user&quot;);
        }

        var userToCreate = _mapper.Map&lt;TblUser&gt;(userForRegisterDto);

        var createdUser = await _repo.Register(userToCreate, userForRegisterDto.Password);

        var userToReturn = _mapper.Map&lt;UserForDetailedDto&gt;(createdUser);

        return CreatedAtRoute(&quot;GetUser&quot;, new
        {
            controller = &quot;Users&quot;,
            id = createdUser.ACustomerId
        }, userToReturn
        );
    }
</code></pre>
<p>Controller Test code-</p>
<pre><code>[Test]
    public async Task GivenAValidUser_WhenIRegisterANewUser_ThenItReturnsOkWithResponse()
    {
        _mockAuthRepository = new Mock&lt;IAuthRepository&gt;();
        _mockAuthMapper = new Mock&lt;IMapper&gt;();
        _mockConfig = new Mock&lt;IConfiguration&gt;();
        UserForRegisterDto expectedUser = new UserForRegisterDto
        {
            Aname = &quot;Luffy&quot;,
            AUsername = &quot;luffy&quot;,
            AEmail = &quot;luffy@gmail.com&quot;,
            Password = &quot;password&quot;,
            ADob = new DateTime(2000, 12, 12)
        };
        _mockAuthMapper.Setup(mapper =&gt; mapper.Map&lt;TblUser&gt;(It.IsAny&lt;UserForRegisterDto&gt;()))
            .Returns(new TblUser());
        _mockAuthMapper.Setup(mapper =&gt; mapper.Map&lt;UserForDetailedDto&gt;(It.IsAny&lt;TblUser&gt;()))
        .Returns(new UserForDetailedDto());
        _mockAuthRepository.Setup(repo =&gt; repo.Register(It.IsAny&lt;TblUser&gt;(), It.IsAny&lt;string&gt;()))
        .ReturnsAsync((TblUser user) =&gt; user);

        _authController = new AuthController(_mockAuthRepository.Object,_mockConfig.Object, _mockAuthMapper.Object);
        var tblUser = await _authController.Register(expectedUser);
        var okResult = tblUser as OkObjectResult;
        Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(okResult);
        Assert.IsAssignableFrom&lt;OkObjectResult&gt;(tblUser);
        var result = ((OkObjectResult)tblUser).Value;
        Assert.NotNull(result);
        Assert.AreEqual(expectedUser, result);
        Assert.IsAssignableFrom&lt;TblUser&gt;(result);


    }
</code></pre>
<p>The exception is thrown by the line-</p>
<pre><code>            _mockAuthRepository.Setup(repo =&gt; repo.Register(It.IsAny&lt;TblUser&gt;(), It.IsAny&lt;string&gt;()))
    .ReturnsAsync((TblUser user) =&gt; user);
</code></pre>
<p>Like you can see, while setting up the mock repository, I am sending two arguments but I get the error-</p>
<pre><code>Message: 
System.ArgumentException : Invalid callback. Setup on method with 2 parameter(s) cannot invoke callback with different number of parameters (1).
</code></pre>
<p>Stack Trace:</p>
<pre><code>&lt;&gt;c__DisplayClass22_0 
&lt;SetReturnComputedValueBehavior&gt;g__ValidateCallback|4(Delegate callback)
MethodCall.SetReturnComputedValueBehavior(Delegate valueFactory)
NonVoidSetupPhrase`2.Returns[T1](Func`2 valueExpression)
GeneratedReturnsExtensions.ReturnsAsync[T,TMock,TResult]
(IReturns`2 mock, Func`2 valueFunction) AuthControllerTests.GivenAValidUser_WhenIRegisterANewUser_ThenItReturnsOkWithResponse() line 43
GenericAdapter`1.GetResult()
AsyncToSyncAdapter.Await(Func`1 invoke)
TestMethodCommand.RunTestMethod(TestExecutionContext context)
TestMethodCommand.Execute(TestExecutionContext context)
SimpleWorkItem.PerformWork()
</code></pre>
<p>I am new to unit testing but so far, my unit tests for GET and POST requests have been working fine this way. Is this an issue Hashing function I am calling inside?</p>
<p>Controller code that was working-
[AllowAnonymous]
[HttpPost()]
public async Task AddMovie(MovieForDetailedDto movieForDetailedDto)
{
if (await _repo.MovieExists(movieForDetailedDto.ATitle))
return BadRequest(&quot;movie already exists&quot;);</p>
<pre><code>        else if(!ModelState.IsValid || movieForDetailedDto.ATitle == null || movieForDetailedDto.APrice == null || movieForDetailedDto.AMovieDescription ==null)
        {
            return BadRequest(&quot;movie details not valid&quot;);
        }

        var movieToCreate = _mapper.Map&lt;TblMovie&gt;(movieForDetailedDto);

        var createdMovie = await _repo.AddMovie(movieToCreate);

        return Ok(createdMovie);
    }
</code></pre>
<p>Test that worked for the above controller-</p>
<pre><code>        [Test]
    public async Task GivenAValidMovie_WhenIPostANewMovie_ThenItReturnsOkWithResponse()
    {
        _mockMovieRepository = new Mock&lt;IMovieRepository&gt;();
        _mockMovieMapper = new Mock&lt;IMapper&gt;();
        TblMovie expectedMovie = new TblMovie
        {
            AMovieId = 55,
            ATitle = &quot;redemption&quot;,
            AMovieDescription = &quot;An action comedy adventure about brilliant robotics prodigy Hiro Hamada, who finds himself in the grips of a criminal plot that threatens to destroy the fast-paced, high-tech city of San Fransokyo. With the help of his closest companion-a robot named Baymax-Hiro joins forces with a reluctant team of first-time crime fighters on a mission to save their city.&quot;,
            ADuration = &quot;105 min&quot;,
            APrice = &quot;10&quot;,
            APurchasePrice = &quot;25&quot;,
            ARating = 5,
            AImageLink = &quot;http://upload.wikimedia.org/wikipedia/en/4/4b/Big_Hero_6_%28film%29_poster.jpg&quot;,
            ATrailerLink = &quot;//www.youtube.com/embed/z3biFxZIJOQ&quot;,
            AGenre = &quot;Comedy&quot;,
            AWideImage = &quot;https://github.com/tushar23091998/MovieRentalApp-FrontEnd/blob/master/src/app/images/bighero6.jpg?raw=true&quot;
        };
        _mockMovieMapper.Setup(mapper =&gt; mapper.Map&lt;TblMovie&gt;(It.IsAny&lt;MovieForDetailedDto&gt;()))
            .Returns(expectedMovie);
        _mockMovieRepository.Setup(repo =&gt; repo.AddMovie(It.IsAny&lt;TblMovie&gt;()))
            .ReturnsAsync((TblMovie movie) =&gt; movie);

        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.AddMovie(new MovieForDetailedDto
        {
            AMovieId = 55,
            ATitle = &quot;redemption&quot;,
            AMovieDescription = &quot;An action comedy adventure about brilliant robotics prodigy Hiro Hamada, who finds himself in the grips of a criminal plot that threatens to destroy the fast-paced, high-tech city of San Fransokyo. With the help of his closest companion-a robot named Baymax-Hiro joins forces with a reluctant team of first-time crime fighters on a mission to save their city.&quot;,
            ADuration = &quot;105 min&quot;,
            APrice = &quot;10&quot;,
            APurchasePrice = &quot;25&quot;,
            ARating = 5,
            AImageLink = &quot;http://upload.wikimedia.org/wikipedia/en/4/4b/Big_Hero_6_%28film%29_poster.jpg&quot;,
            ATrailerLink = &quot;//www.youtube.com/embed/z3biFxZIJOQ&quot;,
            AGenre = &quot;Comedy&quot;,
            AWideImage = &quot;https://github.com/tushar23091998/MovieRentalApp-FrontEnd/blob/master/src/app/images/bighero6.jpg?raw=true&quot;
        });
        var okResult = tblMovie as OkObjectResult;
        Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(okResult);
        Assert.IsAssignableFrom&lt;OkObjectResult&gt;(tblMovie);
        var result = ((OkObjectResult)tblMovie).Value;
        Assert.NotNull(result);
        Assert.AreEqual(expectedMovie,result);
        Assert.IsAssignableFrom&lt;TblMovie&gt;(result);


    }
</code></pre>
<p>So my previous repo functions which took only one parameter were working fine.</p>
<p>Thanks for your time. Apologies if the answer is too obvious.</p>
",https://stackoverflow.com/questions/64348042/getting-system-argumentexception-even-while-sending-the-right-number-of-paramete,"['c#', 'unit-testing', 'nunit', 'asp.net-core-webapi', 'argumentexception']",228,True,-1,1
Test conditional rendering of components based on ContextAPI data using Jest and Enzyme,"<p>I want to do unit testing on the Form component. <code>user</code> is context data that is shared with all the children component.</p>
<pre><code> const { user } = useContext(UserContextAPI);
 return (
  &lt;&gt; {!user ? (
        &lt;&gt;
          {navigation.push({
            pathname: &quot;./Login&quot;,
            state: { editProduct: &quot;edit&quot; },
          })}
        &lt;/&gt;
      ) : (
        &lt;Form&gt;.....&lt;/From&gt;
      )
  }
 &lt;/&gt;
);
</code></pre>
<p>I have written a simple test case to test form component</p>
<pre><code> it(&quot;should contain From component&quot;, () =&gt; {
   let wrapper = mount(
      &lt;BrowserRouter&gt;
        &lt;EditProduct.WrappedComponent /&gt;
      &lt;/BrowserRouter&gt;
    );
    expect(wrapper.find(&quot;Form&quot;).exist()).toEqual(true);
  });
</code></pre>
<p>But the test case failed I think based on conditional rendering it doesn't go to test the Form component. How could we do the conditional rendering based on the context data?</p>
",https://stackoverflow.com/questions/64474559/test-conditional-rendering-of-components-based-on-contextapi-data-using-jest-and,"['reactjs', 'jestjs', 'enzyme']",581,True,2,2
How can I mock a dependency of java.util.Random class?,"<p>Suppose in a class I have a dependency on java.util.Random class. Since random is a concrete class and not backed by an interface, how can I mock the dependency? Should I extend the random class and override the methods.</p>
<p>I was initially using Math.random() but since it was a static method, what can I do to mock it? How do I mock static method for unit testing.</p>
",https://stackoverflow.com/questions/64630622/how-can-i-mock-a-dependency-of-java-util-random-class,"['java', 'unit-testing']",1527,True,5,3
How to know the type of a value returned by a Redshift query?,"<p>In PostgreSQL, you can use the funtion <code>pg_typeof()</code> within the SELECT statement to get the data type of a value returned by a SQL query.</p>
<p>This function does not exist in Redshift, despite Redshift's SQL lineage.</p>
<p>I want to do this:</p>
<p><code>SELECT pg_typeof(0.25::numeric(5,2)) ;</code></p>
<p>and get:</p>
<p><code>numeric(5,2)</code></p>
<p>How do I get the data type of a value returned by a SQL query?
This is to help me with unit-testing my ETL development.</p>
",https://stackoverflow.com/questions/62684748/how-to-know-the-type-of-a-value-returned-by-a-redshift-query,"['sql', 'amazon-redshift']",3949,True,8,1
Best practices of phpunit in a complex scenario,"<p>I'm trying to test my php cms and I question many things about why &amp; how:</p>
<ul>
<li>official policy is <strong>NOT</strong> to test protected/private methods</li>
</ul>
<p>but then it's about functional/behavioral testing and not unit testing</p>
<ul>
<li>development of phpunit stopped support of database testing a whole time ago; sth they called it <code>dbunit</code> if I remember right</li>
</ul>
<p>as a result we do have to create complex test classes for database management or because these classes already exist in an extensive work like mine we do have to use methods from other classes existed here and there that facilitate database management so the system under test actually helps the testing software in a close interaction one with the other</p>
<ul>
<li>it is said that testing is actually call your code before even having written it using your awesome command line and move step-by-step to your goal</li>
</ul>
<p>but if your testing <s>code</s> targets a more functional approach then I can call my in-development method with any other way even from command line and debug it sending output to php log with <code>error_log</code>.</p>
<p>Having said that I save all the trouble of writing 100 lines of code + more than 100 lines of test files, changing 100 lines of code + changing more than 100 lines of test files and on and on....</p>
<p>In the above if we add all the arguments about not to test protected/private members we end in a simple question: why that fuss on unit testing of private/protected methods that might have long chain of internal calls when there are much simpler methods of testing while we code?</p>
<p>All the above introduction seems to me necessary for the reader to understand what I'm asking about:</p>
<p><strong>Given the next specific method can you propose the best approach of (unit?) testing?</strong></p>
<h1>1 Method under test</h1>
<p>File is <code>/home/test/server/auth/Auth.php</code></p>
<pre><code>namespace g3\auth;

use g3\Singleton;
use g3\TokenFactory;
use g3\Registry;
use g3\Header;
use g3\Session;
use g3\Lang;
use g3\Utils;
use g3\mail\MailClient;
use Firebase\JWT;

class Auth {
   /** @var AuthToken $token The AuthToken of this class */
   protected $token;
   /** @var PDO $dbh The PDO handler to the database */
   protected $dbh;
...............
...............
   /**
    * Called by user/admin during the registration.
    * 
    * We use argument '$params' to handle the additional fields that we added at 
    * table 'profiles' (beyond, 'id', 'emai', 'password', 'isactive' and 'dt'). 
    * An example for '$params': array('first_name' =&gt; &quot;John&quot;, 'second_name' =&gt; &quot;Doe&quot;).
    * The available fields:
    * - 'title', 
    * - 'fullname',
    * - 'first_name',
    * - 'second_name',
    * - 'username',
    * - 'address1',
    * - 'address2',
    * - 'zip1',
    * - 'zip2',
    * - 'tel',
    * - 'mobile',
    * - 'fax',
    * - 'city',
    * - 'state',
    * - 'country',
    * - 'birth',
    * - 'language',
    * - 'currency',
    * - 'img',
    * - 'capacity_kb'.
    * 
    * Two modes of call:
    * -by user: addUser($email, $password, $params, $name),
    * -by admin: addUser($email, $password, $params, $name, true).
    * 
    * In admin mode no request is added or email is sent.
    * 
    * If useradd succeeds but profile fails to be inserted in table 'profiles' 
    * then return array contains key 'message' although key 'error' remains 
    * 'false' (registration proceeds).
    * 
    * @param string $email
    * @param string $password
    * @param string[] $params Data for table 'profiles'
    * @param boolean $admin True to bypass activation process
    * 
    * @return A hash array with keys 'error', 'message' and if successful, 'uid'
    */
   protected function addUser($email, $password, $params = array(), $name = '', $admin = false) {
      $return['error'] = true;
      $query = $this-&gt;dbh-&gt;prepare(&quot;INSERT INTO {$this-&gt;token-&gt;get('table_users')} (isactive) VALUES (0)&quot;);
      if (!$query-&gt;execute()) {
         $return['message'] = $this-&gt;getLang()[&quot;system_error&quot;] . &quot; #03&quot;;
         return $return;
      }
      $uid = $this-&gt;dbh-&gt;lastInsertId();
      $email = \htmlentities(\strtolower($email));
      if (((int)$this-&gt;token-&gt;get('suppress_activation') != 1) &amp;&amp; !$admin) {
         $addRequest = $this-&gt;addRequest($uid, $email, &quot;activation&quot;, $name);
         if ($addRequest['error'] == 1) {
            $query = $this-&gt;dbh-&gt;prepare(&quot;DELETE FROM {$this-&gt;token-&gt;get('table_users')} WHERE id = ?&quot;);
            $query-&gt;execute(array($uid));
            $return['message'] = $addRequest['message'];
            return $return;
         }
         $isactive = 0;
      } else {
         $isactive = 1;
      }
      $password = $this-&gt;getHash($password);
      $query = $this-&gt;dbh-&gt;prepare(&quot;UPDATE {$this-&gt;token-&gt;get('table_users')} SET email = ?, password = ?, isactive = ? WHERE id = ?&quot;);
      if (!$query-&gt;execute(array($email, $password, $isactive, $uid))) {
         $query = $this-&gt;dbh-&gt;prepare(&quot;DELETE FROM {$this-&gt;token-&gt;get('table_users')} WHERE id = ?&quot;);
         $query-&gt;execute(array($uid));
         $return['message'] = $this-&gt;getLang()[&quot;system_error&quot;] . &quot; #04&quot;;
         return $return;
      }
      if (!\is_array($params))
         $params = array();
      if(($r = $this-&gt;addProfile($uid, $params)) !== true)
         $return['message'] = $r['message'];
      $return['error'] = false;
      $return['uid'] = $uid;
      return $return;
   }
.............
.............
}
</code></pre>
<p>Database is SQLite.</p>
<p>It's obvious that a numerous other methods of <code>class Auth</code> are called:</p>
<pre><code>Auth::addUser
  | | | |
  v | | |
Auth::getLang
    | | |
    v | |
Auth::addRequest
      | |
      v |
Auth::getHash
        |
        v
Auth::addProfile
</code></pre>
<p>Also a number of other classes are used:</p>
<pre><code>class Auth
  | | |
  v | |
Auth::token is a AuthToken: contains parameters supporting the 
authentication system like table names, database path etc.
    | |
    v |
class Lang: contains parameters that lead to language specific 
messages
      |
      v
Auth::dbh is a database connection returned by DbHandler::getHandler
class DbHandler: manages the database
</code></pre>
<p><strong>You can skip next parts and read &quot;5. Write some tests&quot;</strong></p>
<h1>2 Setup Composer</h1>
<ul>
<li><p>just download a local <code>composer.phar</code></p>
</li>
<li><p>build a <code>composer.json</code>: I don't care about composer's autoloader as I have mine and I load it there from my <code>/home/test/server/g3</code> sub-folder</p>
</li>
<li><p>I don't use <code>vendor</code> but only for developing packages all production software including my <code>g3</code> framework are deployed on <code>/home/test/server</code> sub-folder on seperate sub-folders with a custom autoloader</p>
</li>
</ul>
<p><em><strong>/home/test/composer.json</strong></em></p>
<pre><code>{
   &quot;autoload&quot;: {
      &quot;psr-4&quot;: {
         &quot;&quot;: &quot;server&quot;
      }
    },
   &quot;require-dev&quot;: {
         &quot;mockery/mockery&quot;: &quot;=1.3.1&quot;,
         &quot;phpunit/phpunit&quot;: &quot;=6.5.14&quot;,
         &quot;phpunit/php-invoker&quot;: &quot;=1.1.4&quot;,
         &quot;gealex/doublit&quot;: &quot;=2.1.5&quot;,
         &quot;phpspec/prophecy&quot;: &quot;=1.10.3&quot;
    }
}
</code></pre>
<p><em><strong>/home/test/vendor/autoloader.php</strong></em></p>
<pre><code>&lt;?php

// my autoloader
require_once(&quot;/home/test/server/g3/ClassLoader.php&quot;);

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit1e0ee11cc0a18a5af0d236383dd8a888::getLoader();
</code></pre>
<h1>3 Setup phpunit</h1>
<ul>
<li><p>just download a local <code>/home/test/server/dev/phpunit-6.phar</code></p>
</li>
<li><p>customize the <code>/home/test/server/dev/phpunit.xml</code></p>
</li>
</ul>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;phpunit backupGlobals=&quot;false&quot;
         backupStaticAttributes=&quot;false&quot;
         bootstrap=&quot;/home/test/vendor/autoload.php&quot;
         colors=&quot;true&quot;
         convertErrorsToExceptions=&quot;true&quot;
         convertNoticesToExceptions=&quot;true&quot;
         convertWarningsToExceptions=&quot;true&quot;
         processIsolation=&quot;false&quot;
         stopOnFailure=&quot;false&quot;
         syntaxCheck=&quot;false&quot;
         verbose=&quot;true&quot;&gt;

    &lt;testsuites&gt;
        &lt;testsuite name=&quot;Root&quot;&gt;
            &lt;directory suffix=&quot;Test.php&quot;&gt;../../tests/server/root&lt;/directory&gt;
        &lt;/testsuite&gt;

        &lt;testsuite name=&quot;Core&quot;&gt;
            &lt;directory suffix=&quot;Test.php&quot;&gt;../../tests/server/core&lt;/directory&gt;
        &lt;/testsuite&gt;

        &lt;testsuite name=&quot;Auth&quot;&gt;
            &lt;directory suffix=&quot;Test.php&quot;&gt;../../tests/server/auth&lt;/directory&gt;
        &lt;/testsuite&gt;

        &lt;testsuite name=&quot;mail&quot;&gt;
            &lt;directory suffix=&quot;Test.php&quot;&gt;../../tests/server/mail&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;

    &lt;filter&gt;
        &lt;whitelist processUncoveredFilesFromWhitelist=&quot;true&quot;&gt;
            &lt;directory suffix=&quot;.php&quot;&gt;server&lt;/directory&gt;
        &lt;/whitelist&gt;
    &lt;/filter&gt;

    &lt;php&gt;
        &lt;var name=&quot;skip_mail_integration_tests&quot; value=&quot;1&quot;/&gt;
        &lt;var name=&quot;skip_auth_integration_tests&quot; value=&quot;1&quot;/&gt;
        &lt;var name=&quot;domain&quot; value=&quot;4f4d4ebc35f1.eu.ngrok.io&quot;/&gt;
        &lt;var name=&quot;mailTo&quot; value=&quot;john.doe@gmail.com&quot;/&gt;
    &lt;/php&gt;
&lt;/phpunit&gt;
</code></pre>
<h1>4 Extend PHPUnit\Framework\TestCase</h1>
<p>First let's extend <code>PHPUnit\Framework\TestCase</code> with <code>/home/test/tests/server/CustomTestCase.php</code> that</p>
<ul>
<li><p>supports <code>Prophecy</code> and <code>Mockery</code></p>
</li>
<li><p>contains utility methods <code>callMethod</code>, <code>getProperty</code> and <code>setProperty</code> that can access private/protected members</p>
</li>
<li><p>initializes <code>\g3\Registry</code> with real <code>\g3\Token</code> values coming from json files</p>
</li>
</ul>
<pre><code>&lt;?php
declare(strict_types=1);

use Mockery\Adapter\Phpunit\MockeryTestCase;
use PHPUnit\Framework\TestCase;

/**
 * runTestsInSeparateProcesses
 */
class CustomTestCase extends MockeryTestCase {
   protected $prophet;
   
   // returns the call to private/protected methods
   public static function callMethod($obj, $name, array $args) {
      $class = new \ReflectionClass($obj);
      $method = $class-&gt;getMethod($name);
      $method-&gt;setAccessible(true);
      return $method-&gt;invokeArgs($obj, $args);
   }
   // returns private/protected properties
   public static function getProperty($obj, $name){
      $r = new ReflectionObject($obj);
      $p = $r-&gt;getProperty($name);
      $p-&gt;setAccessible(true);
      return $p-&gt;getValue($obj);
      // alternative syntax with closures
      //$cls = \Closure::bind(function() use ($name){return $this-&gt;{$name};}, $obj, \get_class($obj));
      //return $cls();
   }
   // sets a value to a private/protected property
   public static function setProperty($object, $property, $value){
       $ref = new \ReflectionClass($object);
       $ref_prop = $ref-&gt;getProperty($property);
       $ref_prop-&gt;setAccessible(true);
       $ref_prop-&gt;setValue($object, $value);
   }
   
   public static function setUpBeforeClass(){
      Mockery::globalHelpers();
   }
   public static function tearDownAfterClass(){
   }
   
   protected function setup() {
      $this-&gt;prophet = new \Prophecy\Prophet;
   }
   protected function tearDown() {
      $this-&gt;prophet-&gt;checkPredictions();
      Mockery::close();
   }
}
</code></pre>
<h1>5 Write some tests</h1>
<p>File is <code>/home/test/tests/server/g3/auth/AuthTest.php</code></p>
<pre><code>&lt;?php
declare(strict_types=1);

require_once(__DIR__ . '/../CustomTestCase.php');

/**
 * runTestsInSeparateProcesses
 */
class AuthTest extends CustomTestCase {
   protected $tokens;
   
   public static function setUpBeforeClass(){
      parent::setUpBeforeClass();
      // tokens initialize the g3 framework and these contain full data 
      // from json files; access them like: 
      // \g3\Registry::getInstance()-&gt;getToken('g3\auth\AuthToken') etc.
      static::callMethod(\g3\Dispatcher::getInstance(), 'tokenInit', array());
   }
   public static function tearDownAfterClass(){
      parent::tearDownAfterClass();
      \g3\Registry::getInstance()-&gt;destroy();
   }
   
   /**
    * Creates mocked constructor argument objects before each test.
    * These tokens do not contain data read from json files; dummy tokens.
    * Accessible through $this-&gt;tokens.
    */
   protected function setup() {
      parent::setup();
      
      $resolverToken = $this-&gt;getMockBuilder('\g3\ResolverToken')
         -&gt;disableOriginalConstructor()
         -&gt;getMock();
      
      $requestToken = $this-&gt;getMockBuilder('\g3\RequestToken')
         -&gt;disableOriginalConstructor()
         -&gt;getMock();
      
      $authToken = $this-&gt;getMockBuilder('\g3\auth\AuthToken')
         -&gt;disableOriginalConstructor()
         -&gt;getMock();
      
      $accountToken = $this-&gt;getMockBuilder('\g3\AccountToken')
         -&gt;disableOriginalConstructor()
         -&gt;getMock();
      
      $dbh = $this-&gt;getMockBuilder('\g3\DbHandler')
         -&gt;disableOriginalConstructor()
         -&gt;getMock();
      
      $lang = $this-&gt;getMockBuilder('\g3\Lang')
         -&gt;disableOriginalConstructor()
         -&gt;getMock();
      
      $session = $this-&gt;getMockBuilder('\g3\Session')
         -&gt;disableOriginalConstructor()
         -&gt;getMock();
      
      $this-&gt;tokens = array('accountToken' =&gt; $accountToken, 'resolverToken' =&gt; $resolverToken, 'requestToken' =&gt; $requestToken, 'authToken' =&gt; $authToken, 'dbh' =&gt; $dbh, 'lang' =&gt; $lang, 'session' =&gt; $session);
   }
   
   /**
    * Deletes mocked objects stored at $this-&gt;tokens after each test.
    */
   protected function tearDown() {
      parent::tearDown();
      $this-&gt;tokens = null;
   }
   
   /**
    * Prints a message on CLI
    */
   public function out($msg){
      $msg = \str_replace(array('test_', '_', &quot;\n&quot;), array('', ' ', &quot;:\n&quot;), $msg);
      fwrite(STDOUT, $msg);
   }

   /**
    * Adds an inactive user. It uses real tokens.
    */
   public function helper_addUserInactive($arr) {
      // AuthToken is not stored in Registry &amp; not synchronized
      \g3\TokenFactory::getInstance()-&gt;synchronize($arr['authToken'], 'r');
      $test = $this-&gt;getMockBuilder('\g3\auth\Auth')
         -&gt;setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         -&gt;setMethods(['addRequest', 'getHash'])
         -&gt;getMock();
      $test-&gt;expects($this-&gt;exactly(1))
         -&gt;method('addRequest')
         -&gt;will($this-&gt;returnValue(array('error' =&gt; false)));
      $test-&gt;expects($this-&gt;exactly(1))
         -&gt;method('getHash')
         -&gt;will($this-&gt;returnValue('123'));
      $token = static::getProperty($test, 'token');
      $token-&gt;set('suppress_activation', 0);
      $profile = array('first_name' =&gt; 'John', 'second_name' =&gt; 'Doe', 'username' =&gt; 'John', 'address1' =&gt; 'White House, Washington D.C.', 'country' =&gt; 'USA');
      // call 'addUser'
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', $profile, 'John'));
      $users = $arr['authToken']-&gt;get('table_users');
      $profiles = $arr['authToken']-&gt;get('table_profiles');
      
      return array(
         'dbh' =&gt; $arr['dbh'], 
         'user' =&gt; array('id' =&gt; $r['uid'], 'email' =&gt; $arr['to'], 'password' =&gt; '123', 'role' =&gt; 'guest', 'isactive' =&gt; '0'), 
         'profile' =&gt; $profile, 
         'tables' =&gt; array('users' =&gt; $arr['authToken']-&gt;get('table_users'), 'profiles' =&gt; $arr['authToken']-&gt;get('table_profiles'), 'requests' =&gt; $arr['authToken']-&gt;get('table_requests'))
      );
   }

/**
    * Adds an active user. It uses real tokens.
    */
   public function helper_addUserActive($arr) {
      // AuthToken is not stored in Registry &amp; not synchronized
      \g3\TokenFactory::getInstance()-&gt;synchronize($arr['authToken'], 'r');
      $test = $this-&gt;getMockBuilder('\g3\auth\Auth')
         -&gt;setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         -&gt;setMethods(['addRequest', 'getHash'])
         -&gt;getMock();
      $test-&gt;expects($this-&gt;never())
         -&gt;method('addRequest');
      $test-&gt;expects($this-&gt;exactly(1))
         -&gt;method('getHash')
         -&gt;will($this-&gt;returnValue('123'));
      $token = static::getProperty($test, 'token');
      $token-&gt;set('suppress_activation', 1);
      $profile = array('first_name' =&gt; 'John', 'second_name' =&gt; 'Doe', 'username' =&gt; 'John', 'address1' =&gt; 'White House, Washington D.C.', 'country' =&gt; 'USA');
      // call 'addUser'
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', $profile, 'John'));
      $users = $arr['authToken']-&gt;get('table_users');
      $profiles = $arr['authToken']-&gt;get('table_profiles');
      
      return array(
         'dbh' =&gt; $arr['dbh'], 
         'user' =&gt; array('id' =&gt; $r['uid'], 'email' =&gt; $arr['to'], 'password' =&gt; '123', 'role' =&gt; 'guest', 'isactive' =&gt; '1'), 
         'profile' =&gt; $profile, 
         'tables' =&gt; array('users' =&gt; $arr['authToken']-&gt;get('table_users'), 'profiles' =&gt; $arr['authToken']-&gt;get('table_profiles'), 'requests' =&gt; $arr['authToken']-&gt;get('table_requests'))
      );
   }
   
   /**
    * Adds an active user as admin. It uses real tokens.
    */
   public function helper_adminAddsUserActive($arr) {
      // AuthToken is not stored in Registry &amp; not synchronized
      \g3\TokenFactory::getInstance()-&gt;synchronize($arr['authToken'], 'r');
      $test = $this-&gt;getMockBuilder('\g3\auth\Auth')
         -&gt;setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         -&gt;setMethods(['addRequest', 'getHash'])
         -&gt;getMock();
      $test-&gt;expects($this-&gt;never())
         -&gt;method('addRequest');
      $test-&gt;expects($this-&gt;exactly(1))
         -&gt;method('getHash')
         -&gt;will($this-&gt;returnValue('123'));
      $token = static::getProperty($test, 'token');
      $token-&gt;set('suppress_activation', 0);
      $profile = array('first_name' =&gt; 'John', 'second_name' =&gt; 'Doe', 'username' =&gt; 'John', 'address1' =&gt; 'White House, Washington D.C.', 'country' =&gt; 'USA');
      // call 'addUser'
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', $profile, 'John', true));
      $users = $arr['authToken']-&gt;get('table_users');
      $profiles = $arr['authToken']-&gt;get('table_profiles');
      
      return array(
         'dbh' =&gt; $arr['dbh'], 
         'user' =&gt; array('id' =&gt; $r['uid'], 'email' =&gt; $arr['to'], 'password' =&gt; '123', 'role' =&gt; 'guest', 'isactive' =&gt; '1'), 
         'profile' =&gt; $profile, 
         'tables' =&gt; array('users' =&gt; $arr['authToken']-&gt;get('table_users'), 'profiles' =&gt; $arr['authToken']-&gt;get('table_profiles'), 'requests' =&gt; $arr['authToken']-&gt;get('table_requests'))
      );
   }
   
   /**
    * Inserts a user &amp; profile without the call to any `Auth` method.
    * It uses real tokens.
    */
   public function helper_insertUser($arr, $active = '0') {
      // AuthToken is not stored in Registry &amp; not synchronized
      \g3\TokenFactory::getInstance()-&gt;synchronize($arr['authToken'], 'r');
      $users = $arr['authToken']-&gt;get('table_users');
      $profiles = $arr['authToken']-&gt;get('table_profiles');
      $requests = $arr['authToken']-&gt;get('table_requests');
      // table 'users'
      $time = \time();
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;INSERT INTO {$users} (email, password, isactive, dt) VALUES (?, ?, ?, ?)&quot;);
      $query-&gt;execute(array($arr['to'], '123', $active, $time));
      $uid = $arr['dbh']-&gt;getHandler()-&gt;lastInsertId();
      return array(
         'dbh' =&gt; $arr['dbh'], 
         'user' =&gt; array('id' =&gt; $uid, 'email' =&gt; $arr['to'], 'password' =&gt; '123', 'role' =&gt; 'guest', 'isactive' =&gt; $active),  
         'tables' =&gt; array('users' =&gt; $users, 'profiles' =&gt; $profiles, 'requests' =&gt; $requests)
      );
   }

   /**
    * Deletes user from tables `users`, `profiles` and `requests`.
    * `$arr` is the return of `::test_helper_addUserInactive` or 
    * `::test_helper_addUserActive`.
    */
   public function helper_deleteAddedUser($arr) {
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      $requests = $arr['tables']['requests'];
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;DELETE FROM {$users} WHERE id = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;DELETE FROM {$profiles} WHERE uid = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;DELETE FROM {$requests} WHERE uid = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
   }

   /**
    * Helper that returns real tokens of g3 platform.
    * @group integration_email
    * @group test
    */
   public function test_helper_construct_with_real_tokens() {
      $systemToken = \g3\Registry::getInstance()-&gt;getToken('g3\SystemToken');
      $accountToken = \g3\Registry::getInstance()-&gt;getToken('g3\AccountToken');
      $lang = new \g3\Lang(ROOT . &quot;/server/g3/auth/language&quot;, $accountToken-&gt;get('site', 'language'));
      $exceptionToken = \g3\Registry::getInstance()-&gt;getToken('g3\ExceptionToken');
      $dbh = new \g3\DbHandler('sqlite', 'db_auth', $accountToken, $exceptionToken);
      // AuthToken is not stored in Registry &amp; not synchronized
      $authToken = \g3\TokenFactory::getInstance()-&gt;getToken('g3\auth\AuthToken', null, array('registry' =&gt; \g3\Registry::getInstance(), 'dbh' =&gt; $dbh));
      \g3\TokenFactory::getInstance()-&gt;synchronize($authToken, 'r');
      $requestToken = \g3\Registry::getInstance()-&gt;getToken('g3\RequestToken');
      $resolverToken = \g3\Registry::getInstance()-&gt;getToken('g3\ResolverToken');
      $session = \g3\Session::getInstance();
      $to = $GLOBALS['mailTo'];
      
      $this-&gt;assertTrue(true);
      
      return array('systemToken' =&gt; $systemToken, 'accountToken' =&gt; $accountToken, 'resolverToken' =&gt; $resolverToken, 'requestToken' =&gt; $requestToken, 'authToken' =&gt; $authToken, 'exceptionToken' =&gt; $exceptionToken, 'dbh' =&gt; $dbh, 'lang' =&gt; $lang, 'session' =&gt; $session, 'to' =&gt; $to);
   }

   // !!!WAIT WHAT THE HELL!!!
   // !!!WE DIDN'T EVEN BEGIN TO TEST!!!

   /*
    * ===============
    * Auth::addUser()
    * ===============
    */
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_for_misspelled_table_users($arr) {
      $this-&gt;out(__METHOD__ . &quot;\n&quot;);
      // AuthToken is not stored in Registry &amp; not synchronized
      \g3\TokenFactory::getInstance()-&gt;synchronize($arr['authToken'], 'r');
      $test = $this-&gt;getMockBuilder('\g3\auth\Auth')
         -&gt;setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         -&gt;setMethods(null)
         -&gt;getMock();
      $token = static::getProperty($test, 'token');
      $token-&gt;set('table_users', 'user');
      // call 'addUser'
      $this-&gt;expectException(PDOException::class);
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', array(), 'John'));
      echo &quot;\n&quot;;
   }
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_updates_tables_users_profiles($tokens) {
      $this-&gt;out(__METHOD__ . &quot;\n&quot;);
      $arr = $this-&gt;helper_addUserInactive($tokens);
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      // query table 'users'
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;SELECT email, role, password, isactive FROM $users WHERE id = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $row = $query-&gt;fetch(\PDO::FETCH_ASSOC);
      $this-&gt;assertSame($arr['user']['email'], $row['email']);
      $this-&gt;assertSame($arr['user']['role'], $row['role']);
      $this-&gt;assertSame($arr['user']['password'], $row['password']);
      $this-&gt;assertSame($arr['user']['isactive'], $row['isactive']);
      // query table 'profiles'
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;SELECT first_name, second_name, username, address1 FROM $profiles WHERE uid = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $row = $query-&gt;fetch(\PDO::FETCH_ASSOC);
      $this-&gt;assertSame($arr['profile']['first_name'], $row['first_name']);
      $this-&gt;assertSame($arr['profile']['second_name'], $row['second_name']);
      $this-&gt;assertSame($arr['profile']['username'], $row['username']);
      $this-&gt;assertSame($arr['profile']['address1'], $row['address1']);
      // delete entries in tables
      $this-&gt;test_helper_deleteAddedUser($arr);
      echo &quot;\n&quot;;
   }
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_updates_tables_users_profiles_with_supress_activation($tokens) {
      $this-&gt;out(__METHOD__ . &quot;\n&quot;);
      $arr = $this-&gt;helper_addUserActive($tokens);
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      // query table 'users'
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;SELECT email, role, password, isactive FROM $users WHERE id = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $row = $query-&gt;fetch(\PDO::FETCH_ASSOC);
      $this-&gt;assertSame($arr['user']['email'], $row['email']);
      $this-&gt;assertSame($arr['user']['role'], $row['role']);
      $this-&gt;assertSame($arr['user']['password'], $row['password']);
      $this-&gt;assertSame($arr['user']['isactive'], $row['isactive']);
      // query table 'profiles'
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;SELECT first_name, second_name, username, address1 FROM $profiles WHERE uid = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $row = $query-&gt;fetch(\PDO::FETCH_ASSOC);
      $this-&gt;assertSame($arr['profile']['first_name'], $row['first_name']);
      $this-&gt;assertSame($arr['profile']['second_name'], $row['second_name']);
      $this-&gt;assertSame($arr['profile']['username'], $row['username']);
      $this-&gt;assertSame($arr['profile']['address1'], $row['address1']);
      // delete entries in tables
      $this-&gt;test_helper_deleteAddedUser($arr);
      echo &quot;\n&quot;;
   }
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_updates_tables_users_profiles_for_admin($tokens) {
      $this-&gt;out(__METHOD__ . &quot;\n&quot;);
      $arr = $this-&gt;helper_adminAddsUserActive($tokens);
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      // query table 'users'
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;SELECT email, role, password, isactive FROM $users WHERE id = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $row = $query-&gt;fetch(\PDO::FETCH_ASSOC);
      $this-&gt;assertSame($arr['user']['email'], $row['email']);
      $this-&gt;assertSame($arr['user']['role'], $row['role']);
      $this-&gt;assertSame($arr['user']['password'], $row['password']);
      $this-&gt;assertSame($arr['user']['isactive'], $row['isactive']);
      // query table 'profiles'
      $query = $arr['dbh']-&gt;getHandler()-&gt;prepare(&quot;SELECT first_name, second_name, username, address1 FROM $profiles WHERE uid = ?&quot;);
      $query-&gt;execute(array($arr['user']['id']));
      $row = $query-&gt;fetch(\PDO::FETCH_ASSOC);
      $this-&gt;assertSame($arr['profile']['first_name'], $row['first_name']);
      $this-&gt;assertSame($arr['profile']['second_name'], $row['second_name']);
      $this-&gt;assertSame($arr['profile']['username'], $row['username']);
      $this-&gt;assertSame($arr['profile']['address1'], $row['address1']);
      // delete entries in tables
      $this-&gt;test_helper_deleteAddedUser($arr);
      echo &quot;\n&quot;;
   }
</code></pre>
<p>I just tested sth I knew from the beginning - several months ago - it was working o'right as I can send GET or POST requests and with injected <code>error_log</code> I have production error-free code bypassing all unit-testing theories.</p>
<p>Also these tests are prone to error if someone starts messing with the testing method they start producing code errors from the test file; in that case you have to debug the tests that try to test your code!</p>
<p><strong>From my point of view I start to believe that unit-testing is an excellent way to waste <s>loose</s> your time.</strong> I understand your argument that this is not unit testing so I replace <code>protected</code> with <code>public</code> does that fixes anything?
I wonder can someone prove me wrong? What's your approach then?</p>
",https://stackoverflow.com/questions/62831163/best-practices-of-phpunit-in-a-complex-scenario,"['php', 'unit-testing', 'phpunit']",720,False,0,1
Mock non-virtual methods using pre-processor,"<p>I am working on an embedded project in C++ where the resources are a bit limited. This means I try to be careful about using too many virtual methods unless I really need them. I am planning to start implementing unit-tests perhaps with Gtest.</p>
<p>Because the project is not too big in code size most of the code is written directly in the header file. The only penalty is a bit more compiling time. As it takes ~20 seconds to compile this is not an issue and in my opinion makes code easier to write/read.</p>
<p>If the project was running in Windows I would be all for creating new abstraction layers (or adding seam classes) and having more virtual methods where I need them for unit-testing. Because of the nature of the project I don't want to add extra virtual methods just for unit-testing purposes. I think it would be valid to do it but seems a bit unreasonable when the resources are scarce.</p>
<p>The project is running well and unit-testing is nice to have so I would like to keep code modifications to a minimum. One of the solutions to the problem is to do some trickery with the templates using &quot;hi-perf dependency injection&quot;. This to me seems like duck typing and still requires modifying the original source code where the class is used.</p>
<p>I was thinking why not just use the pre-processor:</p>
<pre><code>#ifdef TEST
#define TESTABLE virtual
#else
#define TESTABLE
#endif
</code></pre>
<p>Then when the time comes that a method needs to be mocked you could always modify the original source code for that class and write something like:</p>
<pre><code>TESTABLE void somePreviouslyUnmockeableMethod(void);
</code></pre>
<p>I am aware one of the disadvantages is that I would have now two source codes, one for production and one for testing. The same happens anyway when one decides to use a Mock class instead of the real class when unit-testing. If the code changes were quite big the changes with the pre-processor could be a real problem but I think with this definition they are kept to a minimum.</p>
<p>Is this a valid solution? Are the some negative consequences I may be overlooking?</p>
<p>Note that all the modules already include a <code>ProjectSettings.h</code> file where the <code>TESTABLE</code> definition could be added with ease.</p>
",https://stackoverflow.com/questions/64203672/mock-non-virtual-methods-using-pre-processor,"['c++', 'mocking', 'embedded', 'googletest']",180,False,0,1
React Hooks ref.current is undefined during test,"<p>TLDR - I have a responsive component using ref.current.offsetWidth but it doesn't work when I test it with Jest</p>
<p>The navbar component works and renders fine in localhost. But when I'm trying to stimulate different screen widths using Jest for unit testing, the ref hook is unable to pick up div length for some reason. Any suggestion on how to fix this?</p>
<p>Error: <code> TypeError: Cannot read property 'offsetWidth' of undefined</code></p>
<p>Code: Navbar.js</p>
<pre><code>// custom hook to get live div width 
const useContainerDimensions = myRef =&gt; {
  const getDimensions = () =&gt; ({
    width: myRef.current.offsetWidth,            //location of error
  });

  const [dimensions, setDimensions] = useState({ width: 0 });

  useEffect(() =&gt; {
    const handleResize = () =&gt; {
      setDimensions(getDimensions());
    };
    if (myRef.current) {
      setDimensions(getDimensions());
    }

    window.addEventListener('resize', handleResize);

    return () =&gt; {
      window.removeEventListener('resize', handleResize);
    };
  }, [myRef]);

  return dimensions;
};

const Navbar = () =&gt; {
  const inputRef = useRef();
  const { width } = useContainerDimensions(inputRef);

  useEffect(() =&gt; {
    if (width &gt;= 890) {
      setCurrTabPerRow(5);
      setTabStyle('5 tabs');
    }
    if (width &lt; 890) {
      setCurrTabPerRow(4);
      setTabStyle('4 tabs');
    }
  }, [width]);

  return (
    ... 
    &lt;div ref={inputRef}&gt;
      //...stuff
    &lt;/div&gt;
    ...
  )
}

export default Navbar;

</code></pre>
<p>navbar.test.js</p>
<pre><code>const resizeWindow = (x, y) =&gt; {
  window.innerWidth = x;
  window.innerHeight = y;
  window.dispatchEvent(new Event('resize'));
}

describe('Navbar component', () =&gt; {
  it('should render', () =&gt; {
    const component = mount(
      &lt;Navbar filter&gt;
        &lt;Navbar.Tab id=&quot;stuff1&quot; /&gt;
        &lt;Navbar.Tab id=&quot;stuff2&quot; /&gt;
        &lt;Navbar.Tab id=&quot;stuff3&quot; /&gt;
      &lt;/Navbar&gt;
    );
    act(() =&gt; {
      resizeWindow(500, 300);
    });
    expect(component).toMatchSnapshot();
  });
});
</code></pre>
",https://stackoverflow.com/questions/63530286/react-hooks-ref-current-is-undefined-during-test,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-hooks']",3755,True,4,2
The name &#39;string&#39; isn&#39;t a type and can&#39;t be used in an &#39;is&#39; expression,"<p>During unit testing of a function returning different types of objects, I need to check if the type of returned object is the same as expected. Therefore, I need to pass multiple classes inside a variable. Then I need to use this variable with the <code>is</code> operator to check types.</p>

<pre><code>final string = String;
assert('foo' is string);
</code></pre>

<p>But I am getting </p>

<pre><code>error: The name 'string' isn't a type and can't be used in an 'is' expression. 
</code></pre>

<p>I read somewhere that a library called <code>Dart:mirrors</code> can solve this problem but I haven't seen an actual example.</p>
",https://stackoverflow.com/questions/62251632/the-name-string-isnt-a-type-and-cant-be-used-in-an-is-expression,"['flutter', 'dart']",1618,True,7,2
How to incorporate both integration and unit testing in one test file using Cypress,"<p>I'm looking for best practices for setting up unit and integration tests using cypress for my react application. I wanted to know if we can combine both integration and unit testing(component based testing) in a single file. Or is there any better approach anyone can provide if we want to implement both IT and UT for our application using Cypress.</p>
",https://stackoverflow.com/questions/63932453/how-to-incorporate-both-integration-and-unit-testing-in-one-test-file-using-cypr,"['reactjs', 'unit-testing', 'integration-testing', 'cypress']",1784,False,1,2
Mocha - Chai Unit Terst report generation - NodeJS,"<p>I am doing Unit Testing using <code>Mocha chai</code> for sample <code>NodeJS</code> project. Followed by the below reference.</p>

<p><a href=""https://www.sitepoint.com/unit-test-javascript-mocha-chai/"" rel=""nofollow noreferrer"">https://www.sitepoint.com/unit-test-javascript-mocha-chai/</a></p>

<p>And I could run the tests successfully using terminal. It is showing success/failure test status.
But, Test Report is not generated.</p>

<p>I used the below command in terminal to run the test</p>

<pre><code>npm run test
</code></pre>

<p>How do I generate the report for the test.</p>
",https://stackoverflow.com/questions/61091857/mocha-chai-unit-terst-report-generation-nodejs,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'chai']",872,True,1,1
Testing dao layer with @DataJpaTest,"<p>I am writing unit testing using <strong>@DataJpaTest</strong>. Though it should do automatic rollback after every method, it is not doing that. Can you please help me with this. </p>

<p>This has 2 test cases written, ideally, test2 should return null, but it returns 1.</p>

<pre><code>@RunWith(SpringRunner.class)
@DataJpaTest
public class EmployeeRepositoryTest {

    @Autowired TestEntityManager em;

    @Autowired EmployeeRepository rep;

//  @Autowired EmployeeService service;
    //Spring context loaded only once, reused by other methods
    @Test
    public void test1() {
//      System.out.println(service); No such bean found
        Employee e= new Employee();
        e.setName(""Payal"");
        em.persist(e);
        em.flush();
        Employee emp=rep.findByName(""Payal"");
        assertNotNull(emp);
        assertThat(emp.getId()).isGreaterThan(0);
    }
    @Test
    public void test2() {
        Employee emp=rep.findByName(""Payal"");
        assertNull(emp);
    }
}
</code></pre>

<p>Complete code can be found at: 
<a href=""https://github.com/payalbnsl/SpringUnitTestDemo/tree/master/src/test/java/com/example/demo/dao"" rel=""nofollow noreferrer"">https://github.com/payalbnsl/SpringUnitTestDemo/tree/master/src/test/java/com/example/demo/dao</a></p>
",https://stackoverflow.com/questions/59854744/testing-dao-layer-with-datajpatest,"['spring', 'spring-boot', 'spring-test']",144,False,1,0
The name &#39;string&#39; isn&#39;t a type and can&#39;t be used in an &#39;is&#39; expression,"<p>During unit testing of a function returning different types of objects, I need to check if the type of returned object is the same as expected. Therefore, I need to pass multiple classes inside a variable. Then I need to use this variable with the <code>is</code> operator to check types.</p>

<pre><code>final string = String;
assert('foo' is string);
</code></pre>

<p>But I am getting </p>

<pre><code>error: The name 'string' isn't a type and can't be used in an 'is' expression. 
</code></pre>

<p>I read somewhere that a library called <code>Dart:mirrors</code> can solve this problem but I haven't seen an actual example.</p>
",https://stackoverflow.com/questions/62251632/the-name-string-isnt-a-type-and-cant-be-used-in-an-is-expression,"['flutter', 'dart']",1618,True,7,2
Instantiate a class with decorator ( mobx ) - React : Unit Testing,"<p>Looking for insights with this one.</p>
<p>Say we have</p>
<pre><code>class Thing {

  doSomething() { ... }
}
</code></pre>
<p>and we can</p>
<pre><code>const testThing = new Thing()
testThing.doSomething()
</code></pre>
<p>How, in React, say when we inject with MobX and it wraps everthing can we instantiate ?</p>
<pre><code>@inject('storeThing')
class Thing {

  doSomething() { ... }
}
</code></pre>
<p>now ...</p>
<pre><code>const testThing = new Thing()
testThing.doSomething() /* doSomething undefined because we have the decorator instead */
</code></pre>
<p>Without using enzyme etc <em>( I know how with shallow/mount(Component.wrapper... )</em>  .. in pure JS; how would we call this class to do some basic unit testing ?</p>
<p>Thanks. Hope I made sense.</p>
",https://stackoverflow.com/questions/63040807/instantiate-a-class-with-decorator-mobx-react-unit-testing,"['javascript', 'reactjs', 'mobx']",42,False,1,0
NUnit console with dll,"<p>I'm using NUnit for unit testing, and I want to send some parameters through the nuni3-console.
But when I insert the unit test project I have this error.</p>

<p>command inserted: nunit3-console pathToMyProject</p>

<p>Error: 'Not possible to associate a transparent proxy to the type...'
<a href=""https://i.stack.imgur.com/yENOa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yENOa.png"" alt=""enter image description here""></a></p>

<p>I dont know what it's wrong, and there is any other framework to send parameters on windows cmd?</p>
",https://stackoverflow.com/questions/60383531/nunit-console-with-dll,"['c#', 'unit-testing', 'automated-tests', 'nunit', 'nunit-console']",138,False,0,0
Jest in a REST API NODEJS couldn&#39;t find a Right test for the Controller.js,"<p>I created an REST API for logistics controls where is possible to create a truck driver, filter search for specifics drivers based if he is loaded or not, for date and etc.</p>

<p>Now to finish my project i'm trying to create a unit testing for this export module but a couldn't find a right solution:</p>

<pre><code>const Driver = require('../models/models.js');

// Create and Save a new driver
exports.create = (req, res) =&gt; {

  const { oLongitude, oLatitude } = req.body;
  const { dLongitude, dLatitude } = req.body;

  // Validade request
  if (!Object.keys(req.body).length) {
    return res.status(400).json({
      message: ""Form content can not be empty""
    });
  }

  //Create a driver
  const driver = new Driver({
    name: req.body.name,
    age: req.body.age,
    gender: req.body.gender,
    veichle: req.body.veichle,
    cnhType: req.body.cnhType,
    loaded: req.body.loaded,
    truckType: req.body.truckType,
    origin: {
      type: 'Point',
      coordinates: [oLongitude, oLatitude]
    },
    destination: {
      type: 'Point',
      coordinates: [dLongitude, dLatitude]
    },
    date: req.body.date
  });

  //Save driver in the database
  driver.save()
    .then(data =&gt; {
      res.json(data);
    }).catch(err =&gt; {
      res.status(500).send({
        message: err.message || ""Some error ocurred while creating the driver.""
      });
    });
};
</code></pre>

<p>This is what i've already tried:</p>

<pre><code>const httpMocks = require('node-mocks-http');
const { create } = require('../app/controllers/controller.js');

describe('create', () =&gt; {
  test('should create stuff', () =&gt; {
    const request = httpMocks.createRequest({
      method: 'POST',
      url: '/create'
    });

    const response = httpMocks.createResponse();

    create(request, response, (err) =&gt; {
      expect(err).toBeFalsy();
    });

    const { property } = JSON.parse(response._getData());

    expect(property).toBe({
      name: ""Antonio dos Santos"",
      age: ""27"",
      gender: ""masculino"",
      veichle: ""nao"",
      cnhType: ""D"",
      loaded: ""nao"",
      truckType: 2,
      oLongitude: -46.9213486,
      oLatitude: -23.7341936,
      dLongitude: -46.9057519,
      dLatitude: -23.8529033,
      date: ""08/02/2020""
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/60189651/jest-in-a-rest-api-nodejs-couldnt-find-a-right-test-for-the-controller-js,"['node.js', 'json', 'rest', 'unit-testing', 'jestjs']",461,True,0,1
Unit testing QWizard with QtTest,"<p>I am writing unit test cases for my QT application which contains a <code>QWizard</code>. I am using <code>QtTest</code> framework. But I am not able to get the Next button clicked on my wizard page.</p>

<pre><code>welcomePage-&gt;m_installedVersion-&gt;lineEdit()-&gt;setText(""1102"");
welcomePage-&gt;m_upgradeVersion-&gt;lineEdit()-&gt;setText(""12"");
welcomePage-&gt;completeChanged(); //Only the above two text fields are mandatory so Next button should be enabled here, but it is not. So I have manually enabled it below.

myWizard.getNextButton()-&gt;setEnabled(true);
while( !myWizard.getNextButton()-&gt;isEnabled())
{

}

//Trying different ways to click on Next    
QTest::mouseClick(myWizard.getNextButton(), Qt::RightButton, Qt::NoModifier, QPoint(), 5000);
QSignalSpy(myWizard.getNextButton(), &amp;QPushButton::clicked);
myWizard.getNextButton()-&gt;click();
</code></pre>

<p>The <code>initializePage</code> for the second page does not get called, so I don't think Next button has been clicked. How can I go to the Next page while unit testing?</p>
",https://stackoverflow.com/questions/59745303/unit-testing-qwizard-with-qttest,"['qt', 'qttest', 'qwizard']",128,True,-1,1
Unit Test for retrofit,"<p>I am learning how to use Unit Testing. I have an Retrofit call which I wish to test if it returns non empty list or I also can compare the generated URL to my URL for test. It does not matter. But it does not work when I run it it never goes to &quot;handleResponse&quot; function. In my activity it works fine.</p>
<pre><code>@RunWith(AndroidJUnit4::class)
class ApiTest {
    @Test
    fun apiConnection() {

        val compositeDisposable = CompositeDisposable()
        compositeDisposable.add(
            ApiClient.getClient.getQuestions(Params.getParamsSearch())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(this::handleResponse)
        )
    }

    private fun handleResponse(objectsQueryResult: ObjectsQueryResult) {
        assertTrue(objectsQueryResult.items.isEmpty());
        assertEquals(objectsQueryResult.items, &quot;&quot;);

    }
}
</code></pre>
",https://stackoverflow.com/questions/63596835/unit-test-for-retrofit,"['android', 'unit-testing', 'kotlin']",59,True,0,1
NPE returned by a mocked function spring boot,"<p>I'm new to testing and I'm trying to learn unit testing using JUnit and spring boot and that exception popped up.
As you can see I mocked the behavior of the function I needed in the TopicSevices but I still get this NPE, I also tried to add </p>

<pre><code>MockitoAnnotations.initMocks(this);
</code></pre>

<p>But it didn't work.</p>

<p>The controller code</p>

<pre><code>package com.example.test.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.dto.ExerciceDTO;

@CrossOrigin(""*"")
@RestController
public class ExerciceController {

    private final ExerciceServices exerciceServices;
    private final TopicService topicServices;

    public ExerciceController(ExerciceServices exerciceServices, TopicService topicServices) {

        this.exerciceServices = exerciceServices;
        this.topicServices = topicServices;
    }

    @GetMapping(""/exercices"")
    public List&lt;Exercice&gt; allExercices() {
        return exerciceServices.getAllExecices();
    }

    @PostMapping(""/exercices"")
    public Exercice createExercice(@Valid @RequestBody ExerciceDTO dto) {

        Exercice exercice = createExcerciceFromDto(dto);

        return exerciceServices.CreateeExercice(exercice);
    }

    public Exercice createExcerciceFromDto(ExerciceDTO dto) {

        Exercice exercice = new Exercice();

        exercice.setDifficulty(dto.getDifficulty());
        exercice.setImg(dto.getImg());
        exercice.setStatus(dto.getStatus());
        exercice.setTitle(dto.getTitle());

        for (Long id : dto.getListToppicId()) {
            try {
                System.out.println(topicServices.getTopicById(id));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return exercice;
    }

    @GetMapping(""/exercices/filter"")
    public List&lt;Exercice&gt; getExeerciceByDifficulty(@RequestParam(required = false) Long id,
            @RequestParam Difficulty difficulty, @RequestParam Status status) {

        return exerciceServices.exercicesFilterTopic(id, difficulty, status);

    }

}

</code></pre>

<p>The test code</p>

<pre><code>package com.example.test.controller;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.Topic;
import com.example.test.model.dto.ExerciceDTO;

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest

class ExerciceControllerTest {


    @MockBean
    private ExerciceServices exerciceServices;

    @MockBean
    private TopicService topicServices;

    @InjectMocks
    private ExerciceController exerciceController;

    ExerciceDTO dto = new ExerciceDTO();
    Exercice e = new Exercice();
    Topic t = new Topic();

    @BeforeEach
    public void setUp() throws Exception {
        Mockito.when(exerciceServices.getAllExecices()).thenReturn(Arrays.asList(e));
    }

    @Test
    public void givenDTOCreateTheExercice() {
        dto.setDifficulty(Difficulty.EASY);
        dto.setImg(""link"");
        dto.setStatus(Status.FINISHED);
        dto.setTitle(""title"");
        dto.setListToppicId(new HashSet&lt;&gt;(Arrays.asList(6L)));

        e.setDifficulty(Difficulty.EASY);
        e.setImg(""link"");
        e.setStatus(Status.FINISHED);
        e.setTitle(""title"");

        t.setId(6L);
        t.setTitle(""romayssae"");

        e.setTopics(new HashSet&lt;&gt;(Arrays.asList(t)));
        Optional&lt;Topic&gt; topic = Optional.of(t);

        Mockito.when(topicServices.getTopicById(6L)).thenReturn(topic);

        System.out.println(topicServices.getTopicById(6L));

        assertEquals(e, exerciceController.createExcerciceFromDto(dto));
    }


}

</code></pre>

<p>The Exception</p>

<pre><code>java.lang.NullPointerException
    at com.example.test.controller.ExerciceController.createExcerciceFromDto(ExerciceController.java:58)
    at com.example.test.controller.ExerciceControllerTest.givenDTOCreateTheExercice(ExcerciceControllerTest.java:77)
    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:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
</code></pre>
",https://stackoverflow.com/questions/60304011/npe-returned-by-a-mocked-function-spring-boot,"['java', 'spring', 'spring-boot', 'unit-testing', 'junit']",576,True,0,2
Celery mocking network calls inside task,"<p>I am using <code>Celery 4.3.0</code> with <code>pytest</code> am able to run my celery tasks for unit testing using <code>celery_worker</code> fixture. </p>

<p>Yet, inside my celery task, I want to mock network calls.</p>

<pre class=""lang-py prettyprint-override""><code>@pytest.mark.django_db(transaction=True)
@mock.patch(""lkl_core.newsletter.tasks.MailChimp"")
def test_celery_task_mail_chimp_subscription(mock_mc_client, celery_app, celery_worker):
    instance = SubscriptionFactory()
    assert mailchimp_subscription.apply_async(
            [instance.id,]
        ).wait(3) is None
</code></pre>

<p>In the above example, I want to mock.patch <code>lkl_core.newsletter.tasks.MailChimp</code> which lives inside <code>mailchimp_subscription</code> task. The mock operation is not applied to the task since I believe it runs on a different thread. </p>

<p>Any advice on how can I achieve that? </p>

<p>Thanks </p>
",https://stackoverflow.com/questions/62114429/celery-mocking-network-calls-inside-task,"['python-3.x', 'unit-testing', 'celery', 'pytest']",115,False,3,1
Unit Testing Echo Function,"<p>To be more specific I am working on an assignment involving unit testing. These are the test cases I'm currently working on:</p>

<pre><code>#include ""c-echo.h""

#include ""gtest/gtest.h""

TEST(EchoTest, HelloWorld) {
    char* test_val[3]; test_val[0] = ""./c-echo""; test_val[1] = ""hello""; test_val[2] = ""world"";
    EXPECT_EQ(""hello world"", echo(3.test_val));
}

TEST(EchoTest, EmptyString) {
        char* test_val[1]; test_val[0] = ""./c-echo"";
        EXPECT_EQ("""", echo(1.test_val));
    }

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&amp;argc, argv);
  return RUN_ALL_TESTS();
}
</code></pre>

<p>c-echo.h program:</p>

<pre><code>#include &lt;iostream&gt;

std::string echo(int length, char** chars) {
    std::string ret = """";
    for(int i = 1; i &lt; length; i++) {
        ret += chars[i];
        if(i &lt; length - 1) {
            ret += "" "";
        }
    }
    return ret;
}
</code></pre>

<p>The assignment stated that I needed to include three additional test cases (edge cases in particular) for the echo function. However, I can't seem to think of any. I'm really new to this whole testing thing. </p>

<p>Thank You</p>
",https://stackoverflow.com/questions/60960191/unit-testing-echo-function,"['c++', 'unit-testing', 'echo']",266,False,0,0
Not able to mock ngrx store in angular playground using any mock framework,"<p>I am trying to use angular playground where i can use common mock data with unit test cases but i am not able to do the following</p>

<ul>
<li>Mock NgRx store in Angular Playground sandbox scenerios using
TS-mockito </li>
<li>Not able to create common mock data for unit
testing(Karma) and angular playground. Is it possible?</li>
</ul>

<p>Can you please advise on this?</p>
",https://stackoverflow.com/questions/60659740/not-able-to-mock-ngrx-store-in-angular-playground-using-any-mock-framework,"['angular', 'unit-testing', 'karma-jasmine', 'ngrx', 'ngrx-store']",225,False,0,1
How to Implement Unit test on my retrofit2 presenter using mockito?,"<p>i want to make a unit testing by using mockito dependencies on my code. it is always failed because view.processMatchData(data) and view.hideLoading() are in closure part in this presenter code, so that unit test will not detect them. Please, somebody help me solve this problem.</p>

<pre><code>open class MatchSearchPresenter(
    private val view: MatchSearchView,
    private val apiService: ApiService,
    private val cari : String
) {
    fun searchMatch() {
        view.showLoading()
        apiService.loadSearchMatch(cari).enqueue(object : Callback&lt;MatchSearchResponseModel&gt; {
                override fun onResponse(call: Call&lt;MatchSearchResponseModel&gt;, response: Response&lt;MatchSearchResponseModel&gt;)
                {
                    if (response.isSuccessful) {
                        val data = response.body()!!
                        view.processMatchData(data)
                    }
                    view.hideLoading()
                }

                override fun onFailure(call: Call&lt;MatchSearchResponseModel&gt;, error: Throwable)
                {
                    Log.e(""Error"", error.message)
                    view.hideLoading()
                }
        })
    }
}
</code></pre>

<p>here are my unit test :</p>

<pre><code>class MatchSearchPresenterTest {
    @Mock
    private lateinit var view: MatchSearchView
    @Mock
    private lateinit var apiService: ApiService
    @Mock
    private lateinit var teamPresenter: MatchSearchPresenter
    @Mock
    private lateinit var call: Call&lt;MatchSearchResponseModel&gt;
    @Mock
    private lateinit var something: Callback&lt;MatchSearchResponseModel&gt;


    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        val kata = ""Man United""
        teamPresenter = MatchSearchPresenter(view, apiService, kata )
    }
    @Test
    fun searchMatch() {
        val teamId = ""Man United""
        val teams: MutableList&lt;PrevMatchData&gt; = mutableListOf()
        val data = MatchSearchResponseModel(teams)

        teamPresenter.searchMatch()

        argumentCaptor&lt;MatchSearchView&gt;().apply {
            Mockito.verify(apiService.loadSearchMatch(teamId).enqueue(something))
            firstValue.processMatchData(data)
            firstValue.hideLoading()
        }

        Mockito.verify(view).showLoading()
        Mockito.verify(view).processMatchData(data)
        Mockito.verify(view).hideLoading()
    }
}
</code></pre>

<p>but this is not working by showing message like this :</p>

<pre><code>java.lang.NullPointerException
    at com.example.footballleaguecataloguefourth.ui_bottom_navigation.schedule.match_search.MatchSearchPresenter.searchMatch(MatchSearchPresenter.kt:19)
    at com.example.footballleaguecataloguefourth.ui_bottom_navigation.schedule.match_search.MatchSearchPresenterTest.searchMatch(MatchSearchPresenterTest.kt:41)
</code></pre>
",https://stackoverflow.com/questions/61473078/how-to-implement-unit-test-on-my-retrofit2-presenter-using-mockito,"['unit-testing', 'kotlin', 'mockito', 'retrofit2']",36,True,0,1
Angular http get response in observable is not typecasting in unit tests,"<p>I'm trying to learn angular in-built unit testing.</p>
<p>I have service with method that uses http.get into pipe into map, and returns typed observable stream (Observable&lt;BankAccountFull[]&gt;).</p>
<p>However, when I'm trying to test it using logic from angular.io &quot;Testing services&quot; page, I keep getting error <code>Expected $[0] to be a kind of BankAccountFull, but was Object({...</code>.</p>
<p>Tried typecasting inside test's arrow function argument, and inside expect.</p>
<p>Service code:</p>
<pre><code>import { Injectable } from '@angular/core';
import { catchError, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { BankAccountFull } from '../types/bank-account';
import { Observable, of } from 'rxjs';
import { ACCOUNTTYPES, AccountType } from '../types/account-type';
import { TankType, TANKTYPES } from '../types/tank-type';
import { AccList } from '../types/acc-list';

@Injectable({
  providedIn: 'root'
})
export class BankAccountService {
  private accountsUrl = 'api/accounts';

  constructor(private http: HttpClient) { }

  getAccountList(token: string): Observable&lt;BankAccountFull[]&gt; {
    return this.http.get&lt;BankAccountFull[]&gt;(this.accountsUrl)
    .pipe(
      map(response =&gt; {
        const accounts: BankAccountFull[] = response as BankAccountFull[];
        return accounts.map((item) =&gt; {
          const temp: AccountType = ACCOUNTTYPES.find(el =&gt; el.id === item.accType);
          const tempRes: BankAccountFull = {...item};
          if (temp.id) {
            tempRes.accTypeHint = temp.hint;
            tempRes.accTypeImg = temp.img;
          }
          const tempTank: TankType = TANKTYPES.find(el =&gt; el.id === item.tankType);
          if (tempTank.id) {
            tempRes.tankTypeImg = tempTank.img;
            tempRes.tankTypeName = tempTank.name;
          }
          return tempRes;
        }
      );
      }),
      catchError(this.handleError&lt;BankAccountFull[]&gt;('getHeroes', []))
    );
  }

  private handleError&lt;T&gt;(operation = 'operation', result?: T): (error: any) =&gt; Observable&lt;T&gt; {
    return (error: any): Observable&lt;T&gt; =&gt; {
      console.error(error);
      return of(result as T);
    };
  }
}
</code></pre>
<p>Unit test code:</p>
<pre><code>import { BankAccountService } from './bank-account.service';
import { BankAccountFull } from '../types/bank-account';
import { of } from 'rxjs';
import { HttpClient } from '@angular/common/http';

describe('BankAccountService', () =&gt; {
  let httpClientSpy: {get: jasmine.Spy};
  let service: BankAccountService;

  beforeEach(() =&gt; {
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);    
    service = new BankAccountService(httpClientSpy as any);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

  it('should return expected accounts list', () =&gt; {
    const expectedAccList: BankAccountFull[] = 
      [
        new BankAccountFull(true, 1, '068985 2563', 1, 500000, 0,  
          '../../assets/img/acc-types/mortgage.png', 'Mortgage', '../../assets/img/tank-types/property-tank.png', 'Property Tank'),
        new BankAccountFull(false, 2, '068985 2563', 1, 500000, 0,  '../../assets/img/acc-types/mortgage.png', 'Mortgage', 
          '../../assets/img/tank-types/property-tank.png', 'Property Tank'),
        new BankAccountFull(false, 3, '068985 2563', 2, 50000, 1, '../../assets/img/acc-types/car-loan.png', 'Car loan', 
          '../../assets/img/tank-types/property-tank.png', 'Work Tank'),
        new BankAccountFull(false, 4, '068985 2563', 3, 50000, 1, '../../assets/img/acc-types/personal-loan.png', 'Personal credit', 
          '../../assets/img/tank-types/property-tank.png', 'Work Tank'),
      ];

    httpClientSpy.get.and.returnValue(of(expectedAccList));

    service.getAccountList('someMD5Token').subscribe(
      (accList: BankAccountFull[]) =&gt; expect(accList as BankAccountFull[]).toEqual(expectedAccList, 'expected accounts list'),
      fail
    );
  });
});
</code></pre>
<p>testing summary:</p>
<pre><code>BankAccountService &gt; should return expected accounts list
Expected $[0] to be a kind of BankAccountFull, but was Object({ active: true, id: 1, name: '068985 2563', accType: 1, balance: 500000, tankType: 0, accTypeImg: '../../assets/img/acc-types/mortgage.png', accTypeHint: 'Mortgage', tankTypeImg: '../../assets/img/tank-types/property-tank.png', tankTypeName: 'Property Tank' }).
Expected $[1] to be a kind of BankAccountFull, but was Object({ active: false, id: 2, name: '068985 2563', accType: 1, balance: 500000, tankType: 0, accTypeImg: '../../assets/img/acc-types/mortgage.png', accTypeHint: 'Mortgage', tankTypeImg: '../../assets/img/tank-types/property-tank.png', tankTypeName: 'Property Tank' }).
Expected $[2] to be a kind of BankAccountFull, but was Object({ active: false, id: 3, name: '068985 2563', accType: 2, balance: 50000, tankType: 1, accTypeImg: '../../assets/img/acc-types/car-loan.png', accTypeHint: 'Car loan', tankTypeImg: '../../assets/img/tank-types/property-tank.png', tankTypeName: 'Work Tank' }).
Expected $[3] to be a kind of BankAccountFull, but was Object({ active: false, id: 4, name: '068985 2563', accType: 3, balance: 50000, tankType: 1, accTypeImg: '../../assets/img/acc-types/personal-loan.png', accTypeHint: 'Personal credit', tankTypeImg: '../../assets/img/tank-types/property-tank.png', tankTypeName: 'Work Tank' }).
</code></pre>
",https://stackoverflow.com/questions/64641298/angular-http-get-response-in-observable-is-not-typecasting-in-unit-tests,"['angular', 'typescript', 'unit-testing', 'rxjs', 'jasmine']",736,True,0,1
How to write unit testing checking null input values using wicket,"<p>I am busy with a wicket application and need to do unit testing, and I have a login page that validates inputs from a <code>List&lt;Customer&gt;</code> but I have no idea where to start, I did try something but it gave me errors and just have no clue what I am doing any help is appreciated </p>

<p>Homepage.java</p>

<pre><code>     form.add(new AjaxButton(""error"") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target)
            {
                for (Customer item: lstCustomer){

                    if (item.name.equals(username.getInput()) &amp;&amp; item.password.equals(password.getInput())){

                        final String usernameValue = username.getModelObject();

                        PageParameters pp = new PageParameters();
                        pp.add(""username"", usernameValue);
                        setResponsePage(SuccessPage.class, pp);
                        valid[0] = true;
                        break;

                    }else {
                        logger.error(""In the else"");
                        valid[0] = false ;
                    }
                }

                if ( valid[0] == false){

                    errorDialog.open(target);

                }


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

<p>TestPage</p>

<pre><code>private WicketTester tester;

    @Before
    public void setUp()
    {
        tester = new WicketTester(new WicketApplication());
    }

    @Test
    public void homepageRendersSuccessfully()
    {
        //start and render the test page
        tester.startPage(HomePage.class);

        //assert rendered page class
        tester.assertRenderedPage(HomePage.class);


    }

    @Test
    public void validLogin(){
        FormTester form = tester.newFormTester(""userForm"");
        form.setValue(""username"", ""emile"");
        form.setValue(""password"", ""123"");
        form.submit();
        tester.assertRenderedPage(SuccessPage.class);

    }
</code></pre>

<p>And then I get this error :</p>

<pre><code>[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket extensions initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket jQuery UI initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-b020ca32-fe17-43e9-8cc5-3b7a618b2f93] init: Wicket jQuery UI initializer (theme-uilightness)

java.lang.NullPointerException
    at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1593)
    at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1516)
    at org.apache.wicket.util.tester.BaseWicketTester.getComponentFromLastRenderedPage(BaseWicketTester.java:1625)
    at org.apache.wicket.util.tester.BaseWicketTester.newFormTester(BaseWicketTester.java:1311)
    at org.apache.wicket.util.tester.BaseWicketTester.newFormTester(BaseWicketTester.java:1295)
    at com.mycompany.TestHomePage.validLogin(TestHomePage.java:35)
    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.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
",https://stackoverflow.com/questions/60541445/how-to-write-unit-testing-checking-null-input-values-using-wicket,"['wicket', 'wicket-tester']",256,True,0,2
Check which parameters were passed when a function is called,"<p>I am unit testing a method where I do two different things with same parameter.I want to check which parameters are passed in both the statements. and either they are same. </p>

<p><strong>Method I am testing</strong> </p>

<pre><code> doWork(value: boolean) {
   if (value) {
      add(value);
    } else {
      delete(value);
   }
  }
</code></pre>

<p>I know I can test with ""toHaveBeenCalledWith"" for a specific value.</p>

<p>But here I would like to test where it's the same for <strong>add</strong> and for <strong>delete</strong>.</p>
",https://stackoverflow.com/questions/62037361/check-which-parameters-were-passed-when-a-function-is-called,"['angularjs', 'unit-testing', 'jasmine']",511,True,0,1
Xunit Test for odd numbers,"<p>I am trying to improve my unit testing skills and i was wondering if someone could tell me the best way of writing a test for writing a test for &quot;sorted odd numbers of a given array of integers&quot;. At the moment I am passing the data into the test with params but I would to verify the output is correct aswell.</p>
<pre><code>    [Theory]
    [InlineData(1,2,3,4)]
    public void SortArrayOddNumber(params int[] number)
    {
        var s = number.Where(n =&gt; (n % 2) == 0).OrderBy(n=&gt;n);
    }
</code></pre>
",https://stackoverflow.com/questions/62609862/xunit-test-for-odd-numbers,"['c#', 'xunit']",509,True,0,4
All tests get terminated in Intellij with Spring Boot and JUnit5,"<p>I was trying to write a simple test in my Spring boot app with JUnit5 and I notice that all of my tests get instanly terminated. I downloaded some unit testing example and it worked just fine so I don't know what is wrong with my set up.</p>

<pre><code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringDemoApplication.class, args);
    }

}

</code></pre>

<p>Here's my example test that gets terminated:</p>

<pre><code>import org.junit.jupiter.api.Test;

class DemoClassTest {

    @Test
    void testOne() {

    }
}
</code></pre>

<p>And here's my pom.xml</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;2.3.0.RELEASE&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.example&lt;/groupId&gt;
    &lt;artifactId&gt;SpringDemo&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;SpringDemo&lt;/name&gt;
    &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;

    &lt;properties&gt;
        &lt;java.version&gt;14&lt;/java.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
            &lt;artifactId&gt;lombok&lt;/artifactId&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                    &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;

        &lt;!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;
            &lt;version&gt;5.2.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;2.23.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

&lt;/project&gt;

</code></pre>

<p><a href=""https://i.stack.imgur.com/EFfde.jpg"" rel=""nofollow noreferrer"">Image from Intellij</a></p>
",https://stackoverflow.com/questions/62134808/all-tests-get-terminated-in-intellij-with-spring-boot-and-junit5,"['java', 'spring', 'spring-boot', 'intellij-idea', 'junit']",4827,True,0,1
Element implicitly has an &#39;any&#39; type because expression of type &#39;string&#39; can&#39;t be used to index type {&quot;1&quot; : { &quot;key&quot;: string}; &quot;2&quot; : { &quot;key&quot;: string};},"<p>I have a json file of ids as keys as such</p>
<pre><code>&quot;1&quot; : { &quot;key&quot;: &quot;value&quot;},
&quot;2&quot; : { &quot;key&quot;: &quot;value&quot;},
</code></pre>
<p>I import this json in my class as data object then use the id passed to the method to retrieve the corresponding object, as such</p>
<pre><code>funx = (key: string) {
  this.temp = data[key]
}
</code></pre>
<p>but I get the following error, that doesn't cause any runtime issues, but its blocking my unit testing and I'm getting it an error in my editor</p>
<pre><code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type {&quot;1&quot; : { &quot;key&quot;: string};
&quot;2&quot; : { &quot;key&quot;: string};}
</code></pre>
",https://stackoverflow.com/questions/63065058/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b,['typescript'],418,True,0,1
Writing Mocha Chai Test cases for NodeJs Controllers,"<p>I am new to unit testing. I am trying to write test cases for controller.js files for nodejs microservices files. I am unable to understand where I am going wrong. Always throws an error &quot;TypeError: Cannot read property 'empId' of undefined&quot; for 2 of these properties.</p>
<p>This is the controller code:</p>
<pre><code>const crmgDetails = db.crmgResource_details;
const employeeProposal = db.employee_Proposal;
const Op = db.Sequelize.Op;
const raDetails = db.crmgRaSheet_entity;
let results = [];
Sequelize = require('sequelize')

exports.findOne = (req, res) =&gt; {
    console.log(req.body.empId);
    crmgDetails.findAll({where: {
        resEmployeeNumber: req.body.empId
    }
    })
       .then(data =&gt; {
           res.send(data);
        })
        .catch(err =&gt; {
            res.status(500).send({
                message:
                    err.message || &quot;Some error occurred while retrieving tutorials.&quot;
      });
    });
};

exports.findMatchingDemandsForRmg = (req,res) =&gt; {
    let proposedDemands = [];
    
    employeeProposal.findAll({
        where: {
            emp_id: req.body.empId,
            demandSbu : req.body.sbu
        }
    }).then(proposedEmployee =&gt; {
        console.log('proposedEmployee',proposedEmployee);
        if(proposedEmployee.length === 0){
            crmgDetails.findAll({
                where: {
                    resEmployeeNumber: req.body.empId,
                    demandSbu: req.body.sbu
                }
            }).then(matchingDemands =&gt; {
                
                console.log('matchingDemands  ',matchingDemands)
                proposedDemands = matchingDemands;
                
            })
        }
        else{
            console.log(&quot;crmg Employee&quot;)
            console.log(proposedEmployee)
            
            
                for(let employee of proposedEmployee){
                
                        crmgDetails.findOne({
                            where: {
                                demandUid: employee.demandUid,
                                resEmployeeNumber: req.body.empId,
                                demandSbu: req.body.sbu
                            }
                        }).then( crmgProposed=&gt; {
                            proposedDemands.push(crmgProposed);
                        })
                
                    
                }
            
        }
        setTimeout(() =&gt; {
            console.log(proposedDemands)
        res.send(proposedDemands);
        }, 3000);
        
        
    }).catch((err)=&gt;{
        res.status(500).send({
            message:
              err.message || &quot;Some error occurred while retrieving tutorials.&quot;
          });
    })

}

exports.getResourceAllocationDetails = (req,res) =&gt; {
    employeeProposal.findAll({
        include: {
            model: raDetails
        },
        where: Sequelize.and(
            {activeFlag : true},
            Sequelize.or({status:&quot;Accepted By RMG&quot;},
            {status:&quot;Rejected&quot;}
        ))
    }).then(employees =&gt; {
        res.send(employees)
    })
}
</code></pre>
<p>This is the test file I tried to write without my head:</p>
<pre><code>const CrmgRaSheetModel = require('../controllers/crmgResource_Details.controller')
describe('Check for succcessful fetech API call', () =&gt; {
  it('property getResourceAllocationDetails should be called', async () =&gt; {
    CrmgRaSheetModel.getResourceAllocationDetails((res) =&gt; {
      expect(res).to.be.an('object')
              return res.json()
          })
  });
  it('property findMatchingDemandsForRmg should be called', async () =&gt; {
    CrmgRaSheetModel.findMatchingDemandsForRmg((res) =&gt; {
      expect(res).to.be.an('object')
              return res.json()
          })
  });
  it('property findOne should be called', async () =&gt; {
    CrmgRaSheetModel.findOne((res) =&gt; {
      expect(res).to.be.an('object')
              return res.json()
          })
  })
})
</code></pre>
",https://stackoverflow.com/questions/63202246/writing-mocha-chai-test-cases-for-nodejs-controllers,"['node.js', 'unit-testing', 'testing', 'mocha.js', 'chai']",229,False,0,1
"What causes this error , unmarshalling json","<p>I am unit testing a basic controller wherein, in certain scenarios, I return some pre compiled static json from a file.</p>
<p>The problem I am experiencing is that, when I attempt to return this static json inside my response as follows:</p>
<pre><code>//records is my json from a file
return ResponseEntity.ok(new JsonApiEnvelope&lt;&gt;(records));
</code></pre>
<p>I get the following error :</p>
<pre><code>java.lang.IllegalArgumentException: Passed in List contains (at least) one element (type: java.util.LinkedHashMap) that is not JsonApi annotated. Expected ALL contents of the list be of type(s) with the @JsonApiType annotation
    at com.cradlepoint.jsonapiary.envelopes.JsonApiEnvelope.validateTypeJsonAPIAnnotated(JsonApiEnvelope.java:144)
    at com.cradlepoin...
</code></pre>
<p>What may be causing this behaviour? The json is valid, it has been through a  formatter.</p>
",https://stackoverflow.com/questions/63754993/what-causes-this-error-unmarshalling-json,"['spring-boot', 'spring-mvc', 'junit']",214,False,-1,1
"Moq, Visual Studio Unit Testing - Tests keep skipping a method in a mocked service","<p>I'm testing a GET action method that calls a public method in a service that has been mocked.</p>

<p>The test fails. When I placed a break-point in the service method, I found that it gets skipped during execution of the test. How do I ensure that the service method doesn't get skipped?</p>

<p>I'm using Visual Studio Unit Testing Tools, Moq, Castle Windsor</p>
",https://stackoverflow.com/questions/61809268/moq-visual-studio-unit-testing-tests-keep-skipping-a-method-in-a-mocked-servi,"['c#', 'visual-studio', 'unit-testing', 'moq', 'castle-windsor']",582,True,0,1
How can I write unit tests for angular&#39;s HttpClient with Jasmine Marbles?,"<p>I have a project where I extensively use angular HttpClient requests as a basis for streams. I would love to test these requests using jasmine marbles, as it seems to be 'industry standard' for unit testing of streams.</p>

<p>I am however struggling with getting the whole thing to work, either the HttpTestingController fails, or the marble fails. I have built a <a href=""https://stackblitz.com/edit/angular-unit-tests-4gmjxn"" rel=""nofollow noreferrer"">stack blitz</a> to demonstrate my point.</p>
",https://stackoverflow.com/questions/60797546/how-can-i-write-unit-tests-for-angulars-httpclient-with-jasmine-marbles,"['angular', 'testing', 'rxjs', 'jasmine-marbles']",855,True,2,1
How to test DOM update in Vue.js with Mocha?,"<p>I'm struggling to understand some basic concepts of unit testing in Vue.js using Karma, Mocha and Chai.</p>

<p>This is my component:</p>

<p><strong><code>VueExample.vue</code></strong></p>

<pre><code>&lt;template&gt;
    &lt;div&gt;
        &lt;p&gt;{{ name }}&lt;/p&gt;
        &lt;input v-model=""name""&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
    export default {
        name: 'VueExample',
        data () {
            return {
                name: 'Bruce Lee'
            };
        }
    }
&lt;/script&gt;
</code></pre>

<p>This is how I'm trying to test it:</p>

<p><strong><code>VueExample.spec.js</code></strong></p>

<pre><code>import Vue from 'vue';
import VueExample from ""../../../components/VueExample"";

describe('VueExample.vue', () =&gt; {
    let vm;

    beforeEach(() =&gt; {
        const Constructor = Vue.extend(VueExample);
        vm = new Constructor().$mount();
    });

    it('should change the name', done =&gt; {
        const input = vm.$el.querySelector('input');
        input.value = 'Chuck Norris';
        expect(vm.$el.querySelector('p').textContent).to.equal('Bruce Lee');
        Vue.nextTick(() =&gt;{
            expect(vm.$el.querySelector('p').textContent).to.equal('Chuck Norris');
            console.log(vm.$el.querySelector('p').textContent);
            done();
        });
    });
});
</code></pre>

<p>I use Karma to run the tests and Chai as assertion library. Everything is properly configured in <code>karma.conf.js</code>. When I run this test, it fails. The text inside the tag <code>&lt;p&gt;</code> doesn't change. The <code>console.log</code> command outputs <em>Bruce Lee</em>.</p>

<p>The tests are run with Firefox.</p>
",https://stackoverflow.com/questions/59896318/how-to-test-dom-update-in-vue-js-with-mocha,"['javascript', 'vue.js', 'mocha.js', 'karma-mocha']",1293,True,5,3
How to mock @ngrx/store state in Angular 8 unit tests with MockStore and MemoizedSelector,"<p>I am trying to create unit testing with jest in angular 8 with RXJS. I want to mock store. I am using <a href=""https://ngrx.io/guide/store/testing"" rel=""noreferrer"">https://ngrx.io/guide/store/testing</a> example of Using Mock Selectors. could anyone help me to how can I use  MemoizedSelector and  MockStore to use mock the store independently.</p>

<pre><code> this.store.select(homeState).pipe(select(s =&gt; s.checkStatus)).subscribe(status =&gt; {
     console.log(status);
     // We performation other action.
});
</code></pre>

<p>I have many selectors in this component. how can I mock many selectors and update the selector's value for each test case? </p>
",https://stackoverflow.com/questions/61472514/how-to-mock-ngrx-store-state-in-angular-8-unit-tests-with-mockstore-and-memoize,"['unit-testing', 'mocking', 'angular8', 'ngrx', 'ngrx-store']",15023,True,8,1
How do I unit test a private Cocoapods library?,"<p>I am trying to find out how to set up unit testing for my private cocoapod library.</p>

<p>Here is the expecting result:</p>

<p>I added a unit testing target 'MyPodTests' to the 'Pods' Project, then I changed target to my 'MyPodTests' scheme. Then I created test classes for my unit tests. I can now select my 'MyPodLib' scheme and press CMD+U and the testing target executes the tests. This is the behavior I am looking for.</p>

<p>This approach, however, has some drawbacks. If I do 'pod update' or 'pod install' on my example app, the test target is gone. if I call pod update on my Example application, the tests are gone too. I'm certain there is a correct way to do this. Also, I would like to prevent the test classes from being loaded into any consumers using the library, therefore I added an exclusion to my podspec:</p>

<pre><code>s.exclude_files = 'Pod/Classes/**/Test/*'
</code></pre>

<p>When I select MyPodLib and press CMD+U nothing is happening, and if I select MyPodTests and press CMD+U it throws ""No such module 'MyPodLib'"" error.</p>
",https://stackoverflow.com/questions/59926770/how-do-i-unit-test-a-private-cocoapods-library,"['swift', 'unit-testing', 'xctest', 'swift5']",2149,True,3,1
Is there the ability to unit test a MaterialSearchBar on Android Studio?,"<p>I've been unit testing my code and have been struggling to find a way to unit test a MaterialSearchBar on Android Studio from the <code>implementation 'com.github.mancj:MaterialSearchBar:+'</code> package. </p>

<p>I have attempted to unit test it by typing     </p>

<pre><code>@Test
public void searchForTony() {
    onView(withId(R.id.search_bar)).perform(click()).perform(typeText(""Tony""));
}
</code></pre>

<p>But this does not seem to work, this is similar to the way I unit tested my EditText fields, can I please have some guidance on how to approach this?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/61373939/is-there-the-ability-to-unit-test-a-materialsearchbar-on-android-studio,"['java', 'android', 'unit-testing', 'android-studio', 'searchbar']",87,False,1,0
How to unit test a method in angular which creates object of imported class,"<p>I am unit testing an angular component using jasmine and karma. Comonent has a method which creates new object of an imported class and call one of its member function. How should I write unit test case for following scenario.</p>

<p>Relevant code of <code>myapp.component.ts</code></p>

<pre><code>import { pdfctrls } from '../path/to/pdfctrl';

@Component({
  selector: 'app-myapp',
  templateUrl: './myapp.component.html',
  styleUrls: ['./myapp.component.css']
})
export class MyappComponent {
  obj: any;

  // other variables and method 

  // this method needs to be unit tested
  downloadPdf() {
    const pdf: pdfctrls = new pdfctrls(this.obj);
    pdf.getPdfData('filename');
  }

  // rest of the methods
}
</code></pre>

<p>Relevant code of <code>pdfctrl.ts</code></p>

<pre><code>export class pdfctrls {
  obj: any;

  constructor(obj) {
    this.obj= obj;
  }

  getPdfData = function (params) {
    // method implementation
  }

  // rest of the methods
</code></pre>

<p>I have tried to spy on <code>pdfctrl</code> class but it didn't worked. Solution which makes least changes in <code>myapp.component.ts</code> is preferred.</p>
",https://stackoverflow.com/questions/61931063/how-to-unit-test-a-method-in-angular-which-creates-object-of-imported-class,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",5894,True,1,1
How to test method call from within another method using junit,"<p>I am new to unit testing in java so please excuse if this is a silly question. I have a method like the one below. What I want to do is verify that this method is being called and also check that the parameters that are passed are not null and also being called. How can I go about doing this in junit/mockito?</p>
<pre><code>public &lt;return type&gt; callMe(Object objectA) {

if(objectA.name != null &amp;&amp; objectA.age != null) {
someOtherMethod(objectA.name, objectA.age)

  }
}
</code></pre>
",https://stackoverflow.com/questions/62525403/how-to-test-method-call-from-within-another-method-using-junit,"['java', 'junit', 'mocking', 'mockito']",367,True,1,1
cannot import graphql query files in jest vue,"<p>I adding unit tests to my Nuxt/Vue project and I'm using Jest for unit testing, I'm fetching data from the server-side using Apollo Client and I have a problem with importing .gql files inside test files.</p>
<p>here is the query file <strong>names.gql</strong></p>
<pre><code>{
 names {
  created_at
  id
  name
  published_at
  updated_at
 }
}
</code></pre>
<p>I'm importing the query inside Vue component like this</p>
<pre><code>import namesQuery from &quot;@/queries/names&quot;;
</code></pre>
<p><strong>Test file:</strong></p>
<pre><code>import { mount } from '@vue/test-utils';

import Names from '@/components/Names';

describe('Names', () =&gt; {
  test('is a Vue instance', () =&gt; {
    const wrapper = mount(Names)
    expect(wrapper.vm).toBeTruthy()
  })
})
</code></pre>
<p>When I run the tests, it says:</p>
<pre><code>SyntaxError: Unexpected token '{'
</code></pre>
<p><strong>Please advise.</strong></p>
",https://stackoverflow.com/questions/65133028/cannot-import-graphql-query-files-in-jest-vue,"['vue.js', 'jestjs', 'nuxt.js', 'apollo-client']",743,True,1,1
"Nova Laravel Unit Testing Expecting Return 201, But Return 403","<p>I'm gonna make a Unit Testing for my resource.
Here my testing function below :</p>
<pre><code>public function testCreateMyResource()
{
    $user = factory(\App\User::class)-&gt;states('admin')-&gt;create();
    $this-&gt;actingAs($user);
    $data = [
        'Field' =&gt; &quot;Example&quot;,
    ];

    $response = $this-&gt;actingAs($user)-&gt;postJson('/nova-api/my-resource?editing=true&amp;editMode=create',$data);
    $response-&gt;assertStatus(201);
    $response-&gt;assertJson(['status' =&gt; true]);
    $response-&gt;assertJson(['message' =&gt; &quot;Created!&quot;]);

}
</code></pre>
<p>But it was return 403.
I expected to return 201 as I login normally to Nova dashboard and create new record in the form.
It seems like forbidden to access the route inside Testing Class.
Is there anyway to access the route ? Please any body help me to solve this.</p>
",https://stackoverflow.com/questions/64640387/nova-laravel-unit-testing-expecting-return-201-but-return-403,"['laravel', 'unit-testing', 'phpunit', 'laravel-nova', 'laravel-unit-test']",180,False,1,0
How to unit test a method that takes event as parameter [Angular/Jasmine],"<p>I'm a beginner in Unit testing in Angular using Jasmine and Karma. My template is:</p>

<pre><code>&lt;p-overlayPanel #op&gt;
  &lt;div&gt;
    ...  
  &lt;/div&gt;
&lt;/p-overlayPanel&gt;

&lt;button (click)=""closeTimeselector($event, op)""&gt;
  Close
&lt;/button&gt;
</code></pre>

<p><strong>Note: <code>p-overlayPanel</code> is <code>primeng</code>'s component.</strong></p>

<p>Here's my logic:</p>

<pre><code>closeTimeselector(event, element) {
    element.hide(event);
}
</code></pre>

<p>I've to check when <code>Close</code> button is pressed from the template, the above method should be called and it should work as expected.</p>

<p>Here's my spec file:</p>

<pre><code>import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { ...} from './timeselector.component';
...

fdescribe('Timeselector', () =&gt; {
   ...
  let fixture: ComponentFixture&lt;TimeselectorComponent&gt;;
  let component: TimeselectorComponent;
  let mockTranslateService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        imports: [
            ...
        ],
        declarations: [TimeselectorComponent],
        providers: [

        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));


  beforeEach(() =&gt; {
    ...
    fixture=TestBed.createComponent(TimeselectorComponent);
    component=fixture.componentInstance;
    timeselector=new TimeselectorComponent(mockTranslateService);
  })

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

  it('...', () =&gt; {
    ...
  })
})
</code></pre>

<p>Can you please help me with the approach. What should I test. Is it even testable ? Please help me.</p>
",https://stackoverflow.com/questions/61781564/how-to-unit-test-a-method-that-takes-event-as-parameter-angular-jasmine,"['angular', 'karma-jasmine']",6876,True,1,1
Testing Moq with Where Throws NotSupportedException,"<p>I am new to Moq and unit testing in asp net. Let me dive straight into it.</p>

<p>My Test Function is the following:</p>

<pre><code>namespace OfflineMessagingAPI.Tests
{

    public class MessageTests
    {
        [Fact]
        public void ShouldGetAllMessagesSentByAUser()
        {
            // Arrange Data ----
            MessageRequest Request = new MessageRequest();
            Request.From = ""userVIP"";

            var listOfMessages = new List&lt;AspNetUserMessage&gt;();
            listOfMessages.Add(new AspNetUserMessage {
                From = Request.From,
                To = ""User1"",
                Text = ""DummyTxt""
            });

            listOfMessages.Add(new AspNetUserMessage
            {
                From = ""User2"",
                To = Request.From,
                Text = ""txt2""
            });

            var TranformedList = listOfMessages.AsQueryable();

            // Setup database mocker
            Mock&lt;BlockedUsersAndMessages&gt; mockRepo = new Mock&lt;BlockedUsersAndMessages&gt;();
            mockRepo.Setup(x =&gt; x.AspNetUserMessages.Where(o =&gt; o.From == Request.From || o.To == Request.From)).Returns(TranformedList);
            var controller = new MessageController(mockRepo.Object);

            // Act ---
            IEnumerable&lt;AspNetUserMessage&gt; messages = controller.GetAllMessages(Request);

            // Assert ---
            Assert.Equal(messages.AsQueryable(), TranformedList));
        }
    }
}
</code></pre>

<p>My Where has lambda expression queries as:</p>

<pre><code>Where(o =&gt; o.From == Request.From || o.To == Request.From)
</code></pre>

<p>because that's how I call it in the GetAllMessages method.</p>

<p>When I run this test I get the following error:
Message Error</p>

<pre><code>  Message: 
    System.NotSupportedException : Unsupported expression: ... =&gt; ....Where&lt;AspNetUserMessage&gt;(o =&gt; o.From == MessageTests.&lt;&gt;c__DisplayClass0_0.Request.From || o.To == MessageTests.&lt;&gt;c__DisplayClass0_0.Request.From)
    Extension methods (here: Queryable.Where) may not be used in setup / verification expressions.
  Stack Trace: 
    Guard.IsOverridable(MethodInfo method, Expression expression)
    InvocationShape.ctor(LambdaExpression expression, MethodInfo method, IReadOnlyList`1 arguments, Boolean exactGenericTypeArguments)
    ExpressionExtensions.&lt;Split&gt;g__Split|4_1(Expression e, Expression&amp; r, InvocationShape&amp; p)
    ExpressionExtensions.Split(LambdaExpression expression)
    Mock.Setup(Mock mock, LambdaExpression expression, Condition condition)
    Mock`1.Setup[TResult](Expression`1 expression)
    MessageTests.ShouldGetAllMessagesSentByAUser() line 41
</code></pre>

<p>I can not understand the problem here, any help would be so appreciated!</p>
",https://stackoverflow.com/questions/61176091/testing-moq-with-where-throws-notsupportedexception,"['asp.net-mvc', 'unit-testing', 'moq']",611,True,1,1
Method put in android.util.SparseArray not mocked,"<p>I would like to run a test which contains this code:</p>
<pre><code>    @Test
    public void deleteItemWithKeyGreaterThenTest() {
        SparseArray&lt;String&gt; sparseArray = new SparseArray&lt;String&gt;();
        sparseArray.put(0, &quot;zero&quot;);
</code></pre>
<p>but when I run the test I get:</p>
<pre><code>java.lang.RuntimeException: Method put in android.util.SparseArray not mocked.
</code></pre>
<p>I've already read this <a href=""https://stackoverflow.com/questions/45124522/unit-testing-arraymap-throws-method-put-in-android-util-arraymap-not-mocked"">Unit testing ArrayMap throws Method put in android.util.ArrayMap not mocked</a> but it did not provide a clear solution.</p>
<p>Can you please tell me what I'm doing wrong?</p>
<p>Thank you in advance!</p>
<p>EDIT: full code</p>
<pre><code>import org.junit.Test;

import static org.junit.Assert.*;

import android.util.SparseArray;

@Test
public void deleteItemWithKeyGreaterThenTest() {
    SparseArray&lt;String&gt; sparseArray = new SparseArray&lt;String&gt;();
    sparseArray.put(0, &quot;zero&quot;);
    assertEquals(sparseArray.size(), 1);
}
</code></pre>
<p>also tried both:</p>
<pre><code>android {
    compileSdkVersion 29
    buildToolsVersion &quot;29.0.2&quot;
    defaultConfig {
        applicationId &quot;com.example.navmaze&quot;
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName &quot;1.0&quot;
        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    testOptions {
        unitTests.returnDefaultValues = true
        unitTests.includeAndroidResources = true
    }
}
</code></pre>
<p>and</p>
<pre><code>android {
    compileSdkVersion 29
    buildToolsVersion &quot;29.0.2&quot;
    defaultConfig {
        applicationId &quot;com.example.navmaze&quot;
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName &quot;1.0&quot;
        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
</code></pre>
<p>and these are my dependencies:</p>
<pre><code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    testImplementation 'androidx.test:core:1.2.0'
    testImplementation 'org.mockito:mockito-core:1.10.19'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'org.jetbrains:annotations-java5:15.0'
}
</code></pre>
",https://stackoverflow.com/questions/60123494/method-put-in-android-util-sparsearray-not-mocked,"['android-studio', 'junit4']",1891,True,1,1
Android Studio - Null pointer exception in Unit test,"<p>I'm currently trying to complete unit testing on my game and have ran into a null pointer exception in the following code:</p>

<p>Setting up Test:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class CardMenuTesting {


@Mock
private Game game = Mockito.mock(Game.class);
@Mock
private Input input;
@Mock
private AssetManager assetManager;
@Mock
private Bitmap bitmap;
@Mock
private Paint paint;
@Mock
private CardMenu cardMenu = Mockito.mock(CardMenu.class);
@Mock
private InstructionsScreen instructionsScreen = Mockito.mock(InstructionsScreen.class);
@Mock
GameScreen gameScreen = Mockito.mock(GameScreen.class);

//@Mock
//private CharacterTestScreen characterTestScreen;

@Before
public void setUp() {
    when(game.getAssetManager()).thenReturn(assetManager);
    when(assetManager.getBitmap(any(String.class))).thenReturn(bitmap);
    when(game.getInput()).thenReturn(input);
    when(cardMenu.getGame()).thenReturn(game);
    when(cardMenu.getName()).thenReturn(""CardMenu"");
    when(instructionsScreen.getGame()).thenReturn(game);
    when(instructionsScreen.getName()).thenReturn(""InstructionsScreen"");

    cardMenu = new CardMenu(game);


    when(game.getAssetManager()).thenReturn(assetManager);
    when(gameScreen.getName()).thenReturn(""Game Screen"");

    cardMenu.instructionButton();

}
</code></pre>

<p>TEST METHOD:</p>

<pre><code>@Test
public void testPlayButton() {

    CardMenu cardMenu = new CardMenu(game);

    cardMenu.getInstructions().setPushTriggered(true);
    cardMenu.instructionButton();

    assertTrue(game.getScreenManager().getCurrentScreen().getName() == ""InstructionsScreen"");

}
</code></pre>

<p>The method in the Card Menu class I am trying to test:</p>

<pre><code>public void instructionButton()
{
    InstructionsScreen instructionsScreen = new InstructionsScreen(mGame);

    if (instructions.isPushTriggered()) {
        mGame.getScreenManager().addScreen(instructionsScreen);
    }
}
</code></pre>

<p>When I run the unit test I get a NullPonterException at:</p>

<pre><code>mGame.getScreenManager().addScreen(instructionsScreen);
</code></pre>

<p>and</p>

<pre><code>cardMenu.instructionButton();
</code></pre>

<p>The stack trace is as follows:</p>

<pre><code>java.lang.NullPointerException
at CardMenu.instructionButton(CardMenu.java:161)
at CardMenuTesting.testPlayButton(CardMenuTesting.java:118)
</code></pre>

<p>I want the unit test to pass. Any help appreciated.</p>
",https://stackoverflow.com/questions/61138497/android-studio-null-pointer-exception-in-unit-test,"['java', 'unit-testing', 'android-studio']",822,False,0,0
Unit Testing ICommand and Methods,"<p>I have developed an WPF application using MVVM as a architecture and am writing some unit tests as part of this. In my view I have a button that is bound to a property in the ViewModel which can be seen below. </p>

<p><strong>ViewModel</strong></p>

<pre><code>public ICommand MoreInfoCommand
{
    get
    {
        if (_moreInfoCommand == null) 
        {
             _moreInfoCommand = new RelayCommand(parameter =&gt; OpenLink());
        }
        return _moreInfoCommand;
    }
}

private void OpenLink() 
{
    try 
    {
         Process.Start(""https://www.google.com/"");
    }
    catch
    {
      // catch error...
    }
}
</code></pre>

<p>In my unit testing I have created the following unit test:</p>

<p><strong>UnitTest</strong></p>

<pre><code>[Description(""Test MoreInfoCommand"")]
[TestMethod]
public void TestMoreInfoCommand() 
{
     viewModel vm = new viewModel();
     Assert.IsTrue(vm.MoreInfoCommand.CanExecute(null));
}
</code></pre>

<p>Currently this tests the the property to see if when the button is clicked in the UI the relevant method can be executed. This passes as the conditions are met, however its my understanding I need to test the functionality as well. With this in mind how do I, for example tests that the correct functionality occurs when the button is clicked. I.e how to test what occurs when the ICommand MoreInfoCommand is executed as a result of button click in the UI. </p>

<p>I know private methods can be tested directly, but should in my unit testing I be checking the functionality as well and if so, how can I do this. </p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/62022588/unit-testing-icommand-and-methods,"['c#', 'wpf', 'unit-testing', 'mvvm', 'icommand']",1223,True,1,2
Why fixture.detectChanges() is required for a unit test [Jasmine/Karma],"<p>I'm learning Unit testing with Jasmine and Karma. My test case is passing but I do not understand one thing. Here's my typescript:</p>

<pre><code>// array list of objects where each month will have one object i.e. 12 objects (Jan to Dec)
monthsData: Array&lt;{
    monthName: string;
    monthYear: number;
    isInRange: boolean;
    isLowerEdge: boolean;
    isUpperEdge: boolean;
}&gt;;

rangeState: { edge1Exists: boolean; edge2Exists: boolean; edgeIndexes: Array&lt;number&gt; };

initRangeState() {} &lt;---- method which should be called; Not important for this question
</code></pre>

<p>And here's my test case in spec file:</p>

<pre><code>it('should re-initialize range state when reflection is triggered', () =&gt; {
    fixture.detectChanges(); &lt;--- why this is required ?
    const rangeState = { edge1Exists: true, edge2Exists: true, edgeIndexes: [] };
    const monthsData = {
        monthName: 'Jan',
        monthYear: 2020,
        isInRange: true,
        isLowerEdge: true,
        isUpperEdge: false
    };
    fixture.componentInstance.rangeState = rangeState;
    fixture.componentInstance.monthsData[0] = monthsData;
    ...
    expect(fixture.componentInstance.initRangeState).toHaveBeenCalled();
});
</code></pre>

<p>I do not understand that when I passed dummy <code>rangeState</code> and <code>monthsData</code> already. Then why I need to run <code>fixture.detectChanges()</code> in first place. My test case is failing without calling that. Please tell me the reason behind it. I'm sure there is something that I don't know.
Here's the screenshot when <code>fixture.detectChanges()</code> is removed:</p>

<p><a href=""https://i.stack.imgur.com/hQP5u.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/hQP5u.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/62180812/why-fixture-detectchanges-is-required-for-a-unit-test-jasmine-karma,"['angular', 'unit-testing', 'karma-jasmine']",25758,True,12,1
angular element unit testing .valid returns false,"<p>I have the following input element in an angular form</p>
<pre><code>&lt;input type=&quot;text&quot; 
                                    id=&quot;description&quot; name=&quot;description&quot; [value]=&quot;description&quot;
                                    [(ngModel)]=&quot;description&quot; (change)=&quot;update(description)&quot;
                                    #description=&quot;ngModel&quot; maxlength=&quot;100&quot; required/&gt;
</code></pre>
<p>Now my problem is that when in actual development in the <code>update</code> method <code>update(elementRef: any)</code> when I check <code>elementRef.valid</code> it returns true, however in unit testing when I check the same it returns <code>false</code>, I`m not sure what is going wrong here.</p>
<p>On further investigation I found out that if I removed <code>required</code> then it passes the validation on the unit test.</p>
",https://stackoverflow.com/questions/63126976/angular-element-unit-testing-valid-returns-false,"['angular', 'unit-testing']",26,False,0,0
For unit testing how to make a namespace derived?,"<p>I have two namespaces:</p>
<pre><code>namespace MyNamespace
</code></pre>
<p>and</p>
<pre><code>namespace MyNamespace.Test
</code></pre>
<p>the second one is for Unit Testing. I don't want to make the classes within &quot;MyNamespace&quot; public but I want the unit tests to be able to access them. I tried internal because from the <a href=""https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers"" rel=""nofollow noreferrer"">Access Modifier documentation</a> I had assumed that &quot;MyNamespace.test&quot; would be derived but it's not working. Do I use a different access modifier or is my namespace wrong?</p>
",https://stackoverflow.com/questions/63075668/for-unit-testing-how-to-make-a-namespace-derived,"['c#', 'namespaces', 'access-modifiers']",572,True,0,1
Problems with Kotlin Result&lt;T&gt; on unit tests,"<p>I am working on an android Application and I opted to use Kotlin Result class so as to handle success/failure on my operations. I made the changes to the code, but the tests stop working and I cannot understand why. Here I show you some snippets:</p>
<p><strong>FireStoreClient.kt</strong></p>
<pre><code>suspend fun items(): Result&lt;ItemsResponse&gt;
</code></pre>
<p><strong>NetworkDataSource.kt</strong></p>
<pre><code>suspend fun getItems(): List&lt;Item&gt; =
    fireStoreClient.items().fold({ it.items.map { item -&gt; item.toDomain() } }, { emptyList() })
</code></pre>
<p><strong>NetworkDataSourceTest.kt</strong></p>
<pre><code>@ExperimentalCoroutinesApi
@Test
fun `Check getItems works properly`() = runBlockingTest {
    whenever(fireStoreClient.items()).doReturn(success(MOCK_ITEMS_DOCUMENT))
    val expectedResult = listOf(
        Item(
            id = 1,
            desc = &quot;Description 1&quot;
        ),
        Item(
            id = 2,
            desc = &quot;Description 2&quot;
        )
    )
    assertEquals(expectedResult, dataSource.getItems())
}
</code></pre>
<p>And this is the exception I am getting right now. Any clue? It appears that the fold() method is not being executed when unit testing.</p>
<pre><code>java.lang.ClassCastException: kotlin.Result cannot be cast to ItemsResponse

    at NetworkDataSource.getItems(NetworkDataSource.kt:31)
</code></pre>
",https://stackoverflow.com/questions/65420765/problems-with-kotlin-resultt-on-unit-tests,"['android', 'unit-testing', 'kotlin']",4545,True,6,3
Skip expressjs middlewares in unit test,"<p>I'm attempting to ""skip"" all of the middleware(s) in my App.ts for express.</p>

<p>I'm unit testing a specific route and I don't care about all of the logging / other logic that occurs in the app.ts middlewares.</p>

<p>It does not seem that there is a way to skip over these middlewares and instead I have to mock/stub all of the services/etc used?</p>
",https://stackoverflow.com/questions/60060644/skip-expressjs-middlewares-in-unit-test,"['node.js', 'unit-testing', 'express']",97,False,0,1
Coroutine testing fails with &quot;This job has not completed yet&quot;,"<p>I'm following Craig Russell's blog post about testing coroutines: <a href=""https://craigrussell.io/2019/11/unit-testing-coroutine-suspend-functions-using-testcoroutinedispatcher/"" rel=""noreferrer"">https://craigrussell.io/2019/11/unit-testing-coroutine-suspend-functions-using-testcoroutinedispatcher/</a> but I can't get this test to pass:</p>
<pre><code>@Test
fun multipleLaunch() = runBlockingTest {
    var result = 0
    val jobs = mutableListOf&lt;Job&gt;()
    for (j in 0 until 10) {
        val job = launch(testDispatcherProvider.io()) {
            delay(1000)
            result++
        }
        jobs.add(job)
    }
    jobs.forEach { job -&gt;
        job.join()
    }
    assertEquals(10, result)
}
</code></pre>
<p>Basically I'm launching a bunch of parallel jobs and want to get the result once all of them are finished.
I'm getting this, by now classical exception:</p>
<blockquote>
<p>java.lang.IllegalStateException: This job has not completed yet</p>
</blockquote>
<p>Please advise how to get this to work as intended.</p>
<p>My complete code:</p>
<pre><code>class LaunchTest {
    @get:Rule
    var coroutinesTestRule = CoroutineTestRule()

    val testDispatcherProvider = object : DispatcherProvider {
        override fun io(): CoroutineDispatcher = coroutinesTestRule.testDispatcher
    }

    @Test
    fun multipleLaunch() = runBlockingTest {
        var result = 0
        val jobs = mutableListOf&lt;Job&gt;()
        for (j in 0 until 10) {
            val job = launch(testDispatcherProvider.io()) {
                delay(1000)
                result++
            }
            jobs.add(job)
        }
        jobs.forEach { job -&gt;
            job.join()
        }
        assertEquals(10, result)
    }
}

class CoroutineTestRule constructor(val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()) : TestWatcher() {
    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(testDispatcher)
    }

    override fun finished(description: Description?) {
        super.finished(description)
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }
}
</code></pre>
",https://stackoverflow.com/questions/62858250/coroutine-testing-fails-with-this-job-has-not-completed-yet,"['unit-testing', 'kotlin', 'kotlin-coroutines']",5649,True,6,2
"Nodejs Jest mocking is not working in multiple describe block in a single file, it works in first describe block only","<p>I am using jest for unit testing in my node express application,please excuse , because i am new to all this </p>

<p>in my abc.test.js</p>

<pre><code>const s3Helper = require('../../../../../lib/s3_helper');

beforeEach(async () =&gt; {
  s3Helper.uploadBufferToS3 = jest.fn(() =&gt; true);
});
describe('test1', () =&gt; {
 it('test1', async () =&gt; {

   expect(s3Helper.uploadBufferToS3)
      .toHaveBeenCalled();
 });
});

describe('test2', () =&gt; {
 it('test2', async () =&gt; {

   expect(s3Helper.uploadBufferToS3)
      .toHaveBeenCalled();
 });
});
</code></pre>

<p>so when i run this test file in test1 it returns that test is passed, however in test2 it returns expected >=1 returned 0.
since i am mocking it beforeEach i expect it should return 1 for each describe block</p>
",https://stackoverflow.com/questions/59854695/nodejs-jest-mocking-is-not-working-in-multiple-describe-block-in-a-single-file,"['node.js', 'express', 'jestjs', 'jest-mock-axios']",403,False,0,0
Angular unit test combineLatest,"<p>I have started off with unit testing with Jest Framework in Angular since a while now. However i am stuck in a situation where I need to unit test <strong>combineLatest</strong> RxJS operator. My component looks like below.</p>
<p>Component:</p>
<pre class=""lang-typescript prettyprint-override""><code>public userData;
public productData;

constructor(
    private readonly userService: UserService,
    private readonly productService: ProductService
) {}

public ngOnInit() {
    this.initialize();
}

public initialize() {
    combineLatest([
        this.userService.getUserData(),
        this.productService.getProductData()
    ])
    .subscribe([userData, productData] =&gt; {
        this.userData = userData;
        this.productData = productData;
    });
}
</code></pre>
<p>I have mocked both my services and my unit test looks like below.</p>
<pre class=""lang-typescript prettyprint-override""><code>it('should initialize user and product data', fakeAsync(() =&gt; {
    spyOn(userService, 'getUserData');
    spyOn(productService, 'getProductData');
    component.initialize();
    tick();
    fixture.detectChanges();
    expect(userService.getUserData).toHaveBeenCalled();
    expect(productService.getProductData).toHaveBeenCalled();
    expect(component.userData).toBeDefined();
    expect(component.productData).toBeDefined();
}));
</code></pre>
<p>This test fails with <strong>Received: undefined.</strong> But the same kind of test works when working with a single observable.</p>
",https://stackoverflow.com/questions/64604536/angular-unit-test-combinelatest,"['angular', 'unit-testing', 'rxjs', 'jestjs', 'combinelatest']",6811,True,3,2
function and statements not covered in istanbul and jest,"<p>I'm using <a href=""https://istanbul.js.org/"" rel=""nofollow noreferrer"">https://istanbul.js.org/</a> for Code coverage and <a href=""https://jestjs.io/"" rel=""nofollow noreferrer"">https://jestjs.io/</a> for unit testing on the following sendMail function. However, I keep getting Istanbul coverage error that the function <code>function(error, info)</code> and the statements <code>return console.log(error);</code> and <code>console.log('Message sent: ' + info.response);</code> are not covered. In the code, I only call <code>sendMail()</code> and I have no idea what elase I need to do to stop the coverage errors. Any advice and ideas? Thanks so much!!</p>
<pre><code>sendMail() {    
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            return console.log(error);
        }
        console.log('Message sent: ' + info.response);
    });
}
</code></pre>
<p>jest test case:</p>
<pre><code>test(&quot;send email test&quot;, () =&gt; {        
        sendMail();        
    });
</code></pre>
",https://stackoverflow.com/questions/63975685/function-and-statements-not-covered-in-istanbul-and-jest,"['typescript', 'jestjs', 'istanbul']",743,False,0,0
what should be returned if the service could not implement,"<p>Suppose that I have a method which will transfer some money from a user to another user, but if the current balance is less than the amount of money that user wanted to transfer, it should not be able to transfer. what should be returned to show that the transaction is successfully implemented or not. what is the proper way to do this?</p>

<p>Service class</p>

<pre><code>@Service
public class TransactionService {
    public TransactionService(){

    }
    public void transferBalanceToAccount(Account senderAccount, Account receiverAccount,Long transferBalance){   
        if(senderAccount != null &amp;&amp; receiverAccount != null){
            // get both account balance
            Long senderCurrentBalance = senderAccount.getBalance();
            Long receiverCurrentBalance = receiverAccount.getBalance();

            if(senderCurrentBalance &lt; transferBalance) {
                // i have no idea what to do
                return;
            }

            senderAccount.setBalance(senderCurrentBalance - transferBalance);
            receiverAccount.setBalance(receiverCurrentBalance + transferBalance);
        }
    }
}
</code></pre>

<p>Unit testing</p>

<pre><code>@Test
    public void transferBalanceToAccountShouldNotBeAbleToTransfer(){
        // Arrange
        Account sender = new Account();
        sender.setBalance(0L);
        Account receiver = new Account();
        receiver.setBalance(100L);

        // Act
        transactionService.transferBalanceToAccount(sender, receiver, 10L);

        // Assert
        // I'm struggling
        assertEquals();
    }
</code></pre>
",https://stackoverflow.com/questions/60728919/what-should-be-returned-if-the-service-could-not-implement,"['java', 'spring', 'spring-boot', 'rest']",45,True,0,2
How to mock url with Pytest parametrize and responses,"<p>I am new to unit testing in Python. I am trying to mock a response, but the url doesn't get mocked returning error that the mock is not registered and gives me a hint to use the real URL, with the real one it works, but it needs to be mocked somehow. Tried out pytest parametrize without success.</p>
<p>This is what I tried so far:</p>
<pre><code>FAKE_HOST = &quot;https://fake-host.com&quot;
@pytest.mark.parametrize(
    (&quot;fake_url&quot;),
    [(FAKE_HOST, &quot;https://fake-host.com&quot;)],
)
@responses.activate
def test_item(fake_url):
    responses.add(
        responses.GET,
        f&quot;{fake_url}/rest/info?name=item&quot;,
        status=200,
    )

    resp = requests.get(
        &quot;https://{fake_url}/rest/info?name=item&quot;

    )
    assert resp.status_code == 200
</code></pre>
",https://stackoverflow.com/questions/65071675/how-to-mock-url-with-pytest-parametrize-and-responses,"['python', 'unit-testing', 'pytest']",1216,True,0,1
Spring Boot unit test won&#39;t run. NullInsteadOfMockException,"<p>I've been following JavaWorld's JUnit 5 Guide to write my tests but the tests won't run. The exception is NullInsteadOfMockException. Can anyone help me figure out what I'm doing wrong?
JavaWorld's guide is at <a href=""https://www.javaworld.com/article/3537563/junit-5-tutorial-part-1-unit-testing-with-junit-5-mockito-and-hamcrest.html"" rel=""nofollow noreferrer"">https://www.javaworld.com/article/3537563/junit-5-tutorial-part-1-unit-testing-with-junit-5-mockito-and-hamcrest.html</a></p>

<p>Error message:</p>

<pre><code>org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to when() is null!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();
Also, if you use @Mock annotation don't miss initMocks()
</code></pre>

<p>Test class:</p>

<pre><code>@ExtendWith(MockitoExtension.class)
class ConferenceServiceTest {

    @Autowired
    ConferenceServiceImpl conferenceService;

    @Mock
    ConferenceRepository conferenceRepository;

    @Mock
    ConferenceRoomRepository conferenceRoomRepository;

    Conference conference;
    ConferenceRoom conferenceRoom;
    final Integer MAX_CAPACITY = 5;

    @BeforeEach
    void setUp() {
        LocalDateTime conferenceStartDateTime = LocalDateTime.of(2020, Month.JUNE, 20, 10, 15);
        LocalDateTime conferenceEndDateTime = LocalDateTime.of(2020, Month.JUNE, 20, 11, 15);
        conference = new Conference(""conferenceName"", conferenceStartDateTime, conferenceEndDateTime);
        conferenceRoom = new ConferenceRoom(""testRoomName"", ""testRoomLocation"", MAX_CAPACITY);
        conference.setConferenceRoom(conferenceRoom);
    }

    @Test
    void addConference_alreadyExists() {
        doReturn(conference).when(conferenceService).findConference(conference);

        assertThrows(ConferenceAlreadyExistsException.class, () -&gt; conferenceService.addConference(conference));
    }
}
</code></pre>

<p>JUnit and Mockito part of my pom.xml</p>

<pre><code> &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;3.3.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&lt;/artifactId&gt;
            &lt;version&gt;5.6.2&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                    &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
</code></pre>

<p>Service class code</p>

<pre><code>@Service
@Slf4j
public class ConferenceServiceImpl implements ConferenceService {

    private ConferenceRepository conferenceRepository;
    private ConferenceRoomRepository conferenceRoomRepository;

    public ConferenceServiceImpl(ConferenceRepository conferenceRepository, ConferenceRoomRepository conferenceRoomRepository) {
        this.conferenceRepository = conferenceRepository;
        this.conferenceRoomRepository = conferenceRoomRepository;
    }

    public String addConference(Conference conference) {

        throw new RuntimeException(""Not yet implemented"");
    }

    public String cancelConference(Conference conference) {

        throw new RuntimeException(""Not yet implemented"");
    }

    public String checkConferenceRoomAvailability(Conference conference) {

        throw new RuntimeException(""Not yet implemented"");
    }

    public Conference findConference(Conference conference) {
        return conferenceRepository.findConferenceByNameAndStartDateAndTimeAndEndDateAndTime(
                conference.getName(), conference.getStartDateAndTime(), conference.getEndDateAndTime());
    }

    public ConferenceRoom findConferenceRoom(ConferenceRoom conferenceRoom) {
        return conferenceRoomRepository.findConferenceRoomByNameAndAndLocation(
                conferenceRoom.getName(), conferenceRoom.getLocation());
    }

}
</code></pre>
",https://stackoverflow.com/questions/62376209/spring-boot-unit-test-wont-run-nullinsteadofmockexception,"['java', 'spring-boot', 'junit', 'mockito']",3855,True,0,4
separate unit testing and E2E testing in npm build,"<p>I am using ant-design-pro in my project. For unit testing it's jest and for e2e testing it's puppeteer. To run tests we have npm run test:all which basically runs tests for all types of tests. Is there a way to separate these files to run tests separately like run only jest files(.test.js) or e2e files(.e2e.js)?</p>
<p>Thanks in advance for your help</p>
",https://stackoverflow.com/questions/63787187/separate-unit-testing-and-e2e-testing-in-npm-build,"['reactjs', 'jestjs', 'puppeteer', 'ant-design-pro']",575,False,0,1
"Expected spy toggleStyle to have been called, when calling function","<p>I am using jasmine testing.</p>
<p>And i have this function:</p>
<pre><code> style: string;
 toggleStyle(style: string, version: string) {
    this.style = `mapbox://styles/mapbox/${style}-${version}`;
  }

</code></pre>
<p>and template:</p>
<pre><code> &lt;div class=&quot;map-menu-item&quot; (click)=&quot;toggleStyle('outdoors', 'v11')&quot; [state]=&quot;[true]&quot; menuItemToggle&gt;
        &lt;span&gt;
          &lt;fa-icon [icon]=&quot;faMountain&quot; size=&quot;sm&quot; class=&quot;pr-2&quot;&gt;&lt;/fa-icon&gt;Outdoors
        &lt;/span&gt;
      &lt;/div&gt;
</code></pre>
<p>So I have this unit testing function:</p>
<pre><code> fit('Should mapbox style when user click on icon', () =&gt; {
    spyOn(component, 'toggleStyle').and.callThrough();
    fixture.debugElement.query(By.css('.map-menu-item')).nativeElement.click();
    fixture.detectChanges();
    expect(component.toggleStyle).toHaveBeenCalled();
  });
</code></pre>
<p>So I call the function: toggleStyle</p>
<p>But I stil get this error:</p>
<pre><code>Expected spy toggleStyle to have been called.
</code></pre>
<p>Of course I googled on this error. But I do a callThrough and I call the function.</p>
<p>So What I have to change?</p>
<p>Thank you</p>
<p>I am using this.style also here:</p>
<pre><code>async ngOnInit() {
    this.style = `mapbox://styles/mapbox/light-v10`;
    const earthquakes: GeoJSON.FeatureCollection = &lt;any&gt;await import('./amsterdam.geo.json');
    this.earthquakes = {...earthquakes};
  }
</code></pre>
<p>Here is it used:</p>
<pre><code>&lt;mgl-map [style]=&quot;style&quot; [zoom]=&quot;[9]&quot; [center]=&quot;[4.899, 52.372]&quot;&gt;
  &lt;mgl-control position=&quot;top-left&quot;&gt;
    &lt;div class=&quot;d-flex flex-column justify-content-start map-menu&quot;&gt;
      &lt;span class=&quot;map-menu-header&quot;&gt;Sensor&lt;/span&gt;
      &lt;div class=&quot;map-menu-item&quot; (click)=&quot;toggleLayer('amsterdam')&quot; [state]=&quot;[true]&quot; menuItemToggle&gt;
        &lt;span&gt;
          &lt;fa-icon [icon]=&quot;faVideo&quot; size=&quot;sm&quot; class=&quot;pr-2&quot;&gt;&lt;/fa-icon&gt;CityHeat
        &lt;/span&gt;
      &lt;/div&gt;
      &lt;div class=&quot;map-menu-item&quot; (click)=&quot;toggleLayer('earthquakes')&quot; [state]=&quot;[true]&quot; menuItemToggle&gt;
        &lt;span&gt;
          &lt;fa-icon [icon]=&quot;faWifi&quot; size=&quot;sm&quot; class=&quot;pr-2&quot;&gt;&lt;/fa-icon&gt;Wi-Fi
        &lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;d-flex flex-column justify-content-start map-menu&quot;&gt;
      &lt;span class=&quot;map-menu-header&quot;&gt;Layer&lt;/span&gt;
      &lt;div class=&quot;map-menu-item&quot; (click)=&quot;toggleStyle('light', 'v10')&quot; [state]=&quot;[true]&quot; menuItemToggle&gt;
        &lt;span&gt;
          &lt;fa-icon [icon]=&quot;faAdjust&quot; size=&quot;sm&quot; flip=&quot;horizontal&quot; class=&quot;pr-2&quot;&gt;&lt;/fa-icon&gt;Light
        &lt;/span&gt;
      &lt;/div&gt;     
      &lt;div class=&quot;map-menu-item&quot; (click)=&quot;toggleStyle('outdoors', 'v11')&quot; [state]=&quot;[true]&quot; menuItemToggle&gt;
        &lt;span&gt;
          &lt;fa-icon [icon]=&quot;faMountain&quot; size=&quot;sm&quot; class=&quot;pr-2&quot;&gt;&lt;/fa-icon&gt;Outdoors
        &lt;/span&gt;
      &lt;/div&gt;
      &lt;div class=&quot;map-menu-item&quot; (click)=&quot;toggleStyle('satellite', 'v9')&quot; [state]=&quot;[true]&quot; menuItemToggle&gt;
        &lt;span&gt;
          &lt;fa-icon [icon]=&quot;faSatellite&quot; size=&quot;sm&quot; class=&quot;pr-2&quot;&gt;&lt;/fa-icon&gt;Satellite
        &lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/mgl-control&gt;
  
&lt;/mgl-map&gt;


</code></pre>
",https://stackoverflow.com/questions/64970237/expected-spy-togglestyle-to-have-been-called-when-calling-function,"['javascript', 'angular', 'karma-jasmine', 'istanbul']",38,True,0,1
How to exclude async methods from Code Coverage using ExcludeCodeCoverage attribute in XunitTest Asp.net Core 3.1?,"<p>I created an Asp.net Core web application and have Unit testing of XUnit.Net test framework.</p>
<p>The ExcludeCodeCoverage attribute on async methods does not exclude that method from code coverage.</p>
<p>Any solution that I can exclude my async methods from code coverage in Xunit.Net Test Asp.Net Core framework?</p>
<p>Consider the following code example where the method does not get excluded from code coverage even after adding the attribute.</p>
<pre><code>[ExcludeFromCodeCoverage]        
    public async Task&lt;string&gt; GetName(string userId){}
</code></pre>
",https://stackoverflow.com/questions/63450215/how-to-exclude-async-methods-from-code-coverage-using-excludecodecoverage-attrib,"['unit-testing', 'asp.net-core-mvc', 'code-coverage', 'asp.net-core-3.1', 'xunit.net']",313,False,0,0
UserDefaults instance for unit testing?,"<p>I have a class which I want to test. It uses UserDefaults in its logic.
I know I have to inject a test double to test it, but I want to make it without too much effort.</p>
<p>If it's possible to make a temporary UserDefaults instance which is only valid during the unit testing, that will be the best. Or do I have to write a wrapper for mocking eventually?</p>
",https://stackoverflow.com/questions/65191363/userdefaults-instance-for-unit-testing,"['swift', 'unit-testing', 'nsuserdefaults', 'userdefaults']",796,True,3,1
How do I unit test a my class which sends emails?,"<p>I have a class like:</p>

<pre><code>public class StarshipEmailSender {

    @Value(""${email.from-email-address:}"")
    String from;

    @Value(""${email.from-name:}"")
    private String fromName;

    @Value(""${email.smtp.credentials-path:}"")
    String credentialPath;

    @Value(""${email.smtp.host:}"")
    String smtpHost;

    @Value(""${email.smtp.port:587}"")
    private int smtpPort;

    @Autowired
    private AClientFactory clientFactory;

    private Properties sessionProperties;
    private String smtpUsername = null;
    private String smtpPassword = null;

    public StarshipEmailSender() {
        sessionProperties = new Properties();
        sessionProperties.put(""mail.transport.protocol"", ""smtp"");
        sessionProperties.put(""mail.smtp.port"", smtpPort);
        sessionProperties.put(""mail.smtp.starttls.enable"", ""true"");
        sessionProperties.put(""mail.smtp.auth"", ""true"");
    }


    public void sendMail(List&lt;String&gt; to, String subject, String contentType, String body)
            throws MessagingException, UnsupportedEncodingException {

        Session session = Session.getDefaultInstance(sessionProperties);
        MimeMessage msg = contructMIMEMessage(session, to, subject, contentType, body);
        Transport transport = session.getTransport();
        try {
            long start = System.currentTimeMillis();

            transport.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);
            transport.sendMessage(msg, msg.getAllRecipients());
            log.info(""Email sent to : "" + to + "" in "" + (System.currentTimeMillis()-start) + "" millis"");
        } finally {
            transport.close();
        }
    }


    MimeMessage contructMIMEMessage(Session session, List&lt;String&gt; to, String subject, String contentType,
            String body) throws UnsupportedEncodingException, MessagingException {
        // code to construct a mime message ...
    }


}

</code></pre>

<p>How do I unit test the <code>sendMail()</code> method? It's got a lot of variables that are declared inside the method and I can't mock them from a test class :/ I have mocked all the other methods because they were easier, but this method confounds me. Or have I constructed this class in a bad way that doesn't allow flexibility for unit testing?</p>
",https://stackoverflow.com/questions/60645400/how-do-i-unit-test-a-my-class-which-sends-emails,"['java', 'unit-testing', 'mocking', 'mockito']",305,False,0,1
How to test for error condition from invalid input,"<p>I'm trying to do a test:</p>
<ul>
<li>The test cases are stored in a <code>slice</code> of <code>struct</code>s with <code>input</code> and <code>expect</code>.</li>
<li>The expect can be <code>int</code> or <code>Error</code>.</li>
</ul>
<p>The goal is to expect an Error if the input will cause an invalid result. I've learnt that it's not recommended to return an error string in Go. How can I expect an error whilst doing unit testing in Go?</p>
<p>Here's the code:</p>
<pre class=""lang-golang prettyprint-override""><code>func arrIdx(arr []int, idx int) (int, error) {
    if idx &gt;= 0 &amp;&amp; idx &lt; len(arr) {
        return arr[idx], nil
    }
    return 0, fmt.Errorf(&quot;This is an error&quot;)
}
func TestArrIdx(t *testing.T) {
    arr := []int{1, 2, 3, 4, 5}
    tests := []struct {
        arr []int
        idx  int
        expect int // or an error
    }{
        {arr, len(arr) - 1, 5, nil},
        {arr, 1, 2, nil},
        // {arr, -1, 0, t.Error},
    }
    for _, test := range tests {
        testName := fmt.Sprintf(&quot;%d&quot;, test.input)
        t.Run(testName, func(t *testing.T) {
            got := arr[test.input]
            if got != test.expect {
                t.Errorf(&quot;got %v, want %v&quot;, got, test.expect)
            } else {
                fmt.Printf(&quot;got %v expect %v\n&quot;, got, test.expect)
            }
        })
    }
}
</code></pre>
",https://stackoverflow.com/questions/62980957/how-to-test-for-error-condition-from-invalid-input,"['unit-testing', 'go', 'testing', 'error-handling']",1059,True,0,1
unit testing iOS function with dispatch,"<p>I'm working with unit testing for the first time and I'm lost with some specific cases.</p>

<p>Despite reading a lot I'm confused about how to test a function like this in iOS:</p>

<pre><code>func myFunction() {

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
          // Tasks to do in background
            dispatch_async(dispatch_get_main_queue(), ^(void){
            // Get the results
            // Update UI
         });
    });
}
</code></pre>

<p>I've read about ""expectations"" (<a href=""https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations?language=objc"" rel=""nofollow noreferrer"">https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations?language=objc</a>), but I don't know how to use them. I guess I should have to call
expectation.fulfill(), but I don't know where.</p>
",https://stackoverflow.com/questions/62430118/unit-testing-ios-function-with-dispatch,"['ios', 'unit-testing', 'dispatch-async', 'expectations']",47,True,0,1
JUnit Spring MVC,"<p>I would like to ask for help regarding on how to perform unit testing on the following codes.  I developed it using Java Spring MVC framework.</p>

<pre><code>@GetMapping(""/top3Downtime/{type}/{date}"")
 public List&lt;Top3DowntimeChart&gt; getTop3DowntimeByDate(@PathVariable String type, @PathVariable 
 String date) 
         throws ParseException{

     if (type.equals(weekType)) {
            String weekStart = date.substring(0, 10);
            return top3DowntimeRepository.getTop3DowntimeChartByWeek(dateUtil.getParsedDate(weekStart));

        } else if (type.equals(monthType)) {
            String monthValue = date.substring(5, 7);
            String monthYear = date.substring(0, 4);    
            String fullStartDate = monthYear + ""-"" + monthValue + ""-"" + ""01"";

            return top3DowntimeRepository.getTop3DowntimeChartByMonth(dateUtil.getParsedDate(fullStartDate));

        } else if (type.equals(quarterType)) {
            String quarterValue = date.substring(0, 2);
            String quarterYear = date.substring(3, 7);

            return top3DowntimeRepository.getTop3DowntimeChartByQuarter(dateUtil.getFirstQuarterMonth(quarterValue, quarterYear));

        } else if (type.equals(yearType)) {
            String year = date.substring(0, 4);     
            beginningFormat = year + startDateOfYear;
            endingFormat = year + endDateOfYear;
            return top3DowntimeRepository.getTop3DowntimeChartByYear(dateUtil.getParsedDate(beginningFormat));

        } else {
            return top3DowntimeRepository.getTop3DowntimeChartByDate(dateUtil.getParsedDate(date));
        }
 }
</code></pre>

<p>So far, this is the codes I have made to JUnit test my program but I was not able to have it fully covered.  Errors were telling me I am missing some branches.  Any assistance would be appreciated.  Thanks.</p>

<pre><code>@MockBean
private Top3DowntimeChart top3DowntimeChart;
@MockBean
private VarianceChart varianceChart;
@MockBean
private VarianceChartOnOffSite varianceChartOnOffSite;
@Autowired
private WebApplicationContext webApplicationContext;
@Mock
private DateUtil dateUtil;
@Autowired
private Top3DowntimeRepository top3DowntimeRepository;
private MockMvc mockMvc;

List&lt;Top3DowntimeChart&gt; top3Downtime;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

    availabilityImpactChart = new AvailabilityImpactChart(91.90, ""NCR"", 20);
    availPerAtmRatingChart = new AvailPerAtmRatingChart(""98"", ""97"");
    consecutiveOfflineChart = new ConsecutiveOfflineChart(""2020-01-01"", 88);
    downtimeBreakdownChart = new DowntimeBreakdownChart(""97"", ""85"");
    downtimeChart = new DowntimeChart(95.95, ""Category1"", ""2020-01-01"");
    downtimeDistDailyChart = new DowntimeDistDailyChart(""nameOfRegion"", ""atmOutOfService"", ""beginningOfDay"", ""cardReader"", ""cashDistributor"", ""cashHandler"", ""commandRejected"", ""communication"", ""connection"", 
            ""encryptor"", ""endOfDay"", ""purgedBin"");
    downtimeDistOverallChart = new DowntimeDistOverallChart(""date"", ""atmOutOfService"", ""beginningOfDay"", ""cardReader"", ""cashDistributor"", ""cashHandler"", ""commandRejected"", ""communication"", 
            ""connection"", ""encryptor"", ""endOfDay"", ""purgedBin"");
    downtimeIntervTrendChart = new DowntimeIntervTrendChart(""eventCategory"", ""2020-01-01"", ""00:00:00"", 12.00f);
    eventCategory = new EventCategory(""eventDescription"", ""eventCategoryString"");
    heatMapChart = new HeatMapChart(97.12, ""phRegion"", 20, ""2020-01-01"");
    impactPerRegionChart = new ImpactPerRegionChart(""locationName"", 25);
    intervalChart = new IntervalChart(""duration"", ""time"", 15.15f);
    overallChart = new OverallChart(""2020-01-01"", 91.01, 8);
    overviewChart = new OverviewChart(""region"", ""availabilityPercentage"");
    overviewDowntime = new OverviewDowntime(""eventDescription"", 85.88);
    perRegionPerfChart = new PerRegionPerfChart(""regionAcronym"", 90.00);
    top3DowntimeChart = new Top3DowntimeChart(""eventCategoryType"", ""column2"", ""column3"");
    varianceChart = new VarianceChart(""2020-01-01"", 88.90);
    varianceChartOnOffSite = new VarianceChartOnOffSite(""siteClass"", 87.77, 85.00);

}

@Test
public void testGetTop3DowntimeByDate() throws Exception {  

    when(top3DowntimeChart.getEventCategoryType()).thenReturn(""eventCategoryType"");
    when(top3DowntimeChart.getColumn2()).thenReturn(""column2"");
    when(top3DowntimeChart.getColumn3()).thenReturn(""column3"");
    when(top3DowntimeRepository.getTop3DowntimeChartByDate(dateUtil.getParsedDate(""2019-10-10""))).thenReturn(top3Downtime);
       //Top3DowntimeChart data = new Top3DowntimeChart(""ATM Out of Service"", ""19.22"", ""23.15"");
         //assertNotNull(data);
         this.mockMvc.perform(get(""/top3Downtime/date/2019-10-10"") .accept(MediaType.APPLICATION_JSON))
   .andExpect(status().isOk())
   .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));

}
@Test
public void failedGetTop3DowntimeByDate() throws Exception {  

    when(top3DowntimeChart.getEventCategoryType()).thenReturn(""eventCategoryType"");
    when(top3DowntimeChart.getColumn2()).thenReturn(""column2"");
    when(top3DowntimeChart.getColumn3()).thenReturn(""column3"");
       //Top3DowntimeChart data = new Top3DowntimeChart(""ATM Out of Service"", ""19.22"", ""23.15"");
         //assertNotNull(data);
         this.mockMvc.perform(get(""/top3Downtime/date/"") .accept(MediaType.APPLICATION_JSON))
   .andExpect(status().isBadRequest());

}
</code></pre>
",https://stackoverflow.com/questions/59607153/junit-spring-mvc,['java'],64,False,0,2
Switching between Databricks Connect and local Spark environment,"<p>I am looking to use Databricks Connect for developing a pyspark pipeline. DBConnect is really awesome because I am able to run my code on the cluster where the actual data resides, so it's perfect for integration testing, but I also want to be able to, during development and unit testing (<code>pytest</code> with <code>pytest-spark</code>), simply using a local Spark environment.</p>

<p>Is there any way to configure DBConnect so for one use-case I simply use a local Spark environment, but for another it uses DBConnect?</p>
",https://stackoverflow.com/questions/61734742/switching-between-databricks-connect-and-local-spark-environment,"['apache-spark', 'pyspark', 'databricks', 'databricks-connect']",907,False,11,1
Unit tests mocks fails on rest API requests in Python,"<p>Hi I am new to unit testing and I am digging into mocks and pytest.I am trying to unit test two rest api requests where the GET request checks if an item doesn't exist in the API and if it does not create it with POST request and to create a folder, otherwise if it exists just to create a folder.</p>
<p>I tried to use <code>Mocker()</code> and I am stuck on <code>AttributeError: Mocker</code> when I try to mock the <code>GET</code> request.</p>
<p>This is the code I am trying to test:</p>
<pre><code>
   client = requests.session()
    # get item by name
    response = client.get(
        f&quot;https://url.com/rest/item/info?name=test_item&quot;,
        auth=username, password),
    )

    if (
        response.status_code == 200
        and response.json()[&quot;status&quot;]
        == &quot;Item doesn't exist!&quot;
    ):
        logging.info(f&quot;Creating item&quot;)
        client.post(
            &quot;https://url.com/rest/item/create?name=test_item&quot;,
            auth=username, password),
        )
        # directory creation
        dir_make = &quot;mkdir -p test_item/temperature&quot;
        exec_cmd(dir_make)

    elif response.status_code == 200 and response.json()[&quot;status&quot;]==&quot;OK&quot;:
        # directory creation
        dir_make = &quot;mkdir -p test_item/temperature&quot;
        exec_cmd(dir_make)

</code></pre>
<p>And this is the unit test that fails with <code>AttributeError</code>:</p>
<pre><code>def test_existing_item(requests_mock, monkeypatch):
    with requests_mock.Mocker() as mock:
        mock.get(&quot;https://url.com/rest/item/info?name=test_item&quot;, text=&quot;OK&quot;)

        resp = requests.get(&quot;https://url.com/rest/item/info?name=test_item&quot;)
        assert resp.text == &quot;OK&quot;

</code></pre>
<p>EDIT: Test for item not found and <code>POST</code> mock. It seems like it doesn't add coverage to the <code>else</code> statement. How can be tested if the item exists and only the folder needs to be added in that case?</p>
<p>EDIT 2: Added <code>elif</code> statement instead of <code>else</code> and 2 separate tests, still the one <code>test_existing_items()</code> doesn't cover the <code>elif</code> statement...What am I doing wrong in that case?</p>
<pre><code>def test_existing_item(monkeypatch):
    with requests_mock.Mocker() as mock_request:
        mock_request.get(requests_mock.ANY, text=&quot;success!&quot;)
        resp = requests.get(
            &quot;https://url.com/rest/item/info?name=test_item&quot;,
            auth=(&quot;mock_username&quot;, &quot;mock_password&quot;),
        )
        if resp.status_code == 200 and resp.json()[&quot;status&quot;] == &quot;OK&quot;:
            dir_make = &quot;mkdir -p test_item/temperature&quot;
            exec_cmd(dir_make)


    encoded_auth = b64encode(b&quot;mock_username:mock_password&quot;).decode(&quot;ascii&quot;)

    assert mock_request.last_request.headers[&quot;Authorization&quot;] == f&quot;Basic {encoded_auth}&quot;


def test_post_item(monkeypatch):
    with requests_mock.Mocker() as mock_request:
        mock_request.get(requests_mock.ANY, text=&quot;success!&quot;)
        resp = requests.get(
            &quot;https://url.com/rest/item/info?name=test_item&quot;,
            auth=(&quot;mock_username&quot;, &quot;mock_password&quot;),
        )

        if resp.status_code == 200 and resp.json()[&quot;status&quot;] == &quot;ERROR&quot;:
            mock_request.get(requests_mock.ANY, text=&quot;success!&quot;)
            requests.post(
                &quot;https://url.com/rest/item/create?name=test_item&quot;,
                auth=(&quot;mock_username&quot;, &quot;mock_password&quot;),
            )

        dir_make = &quot;mkdir -p test_item/temperature&quot;
        exec_cmd(dir_make)


    encoded_auth = b64encode(b&quot;mock_username:mock_password&quot;).decode(&quot;ascii&quot;)

    assert mock_request.last_request.headers[&quot;Authorization&quot;] == f&quot;Basic {encoded_auth}&quot;
</code></pre>
<p>I am not familiar with unit testing so any help would be appreciated to unit test this code.</p>
",https://stackoverflow.com/questions/64971331/unit-tests-mocks-fails-on-rest-api-requests-in-python,"['python', 'unit-testing', 'mocking', 'pytest']",1271,True,0,1
Unit Tests for async code (indexedDB) inside React Component,"<p>I am trying to write unit tests for a React component - That looks something broadly as follows -</p>
<ol>
<li>a handle to a db is passed to a component</li>
<li>The component also receives <code>data</code> as <code>props</code> (that will change) - perhaps this is something that could come through a Redux store.</li>
<li>Now what I do in my <code>useEffect</code> for this <code>data</code> change is - Write into <code>indexDB</code> (actually using the <code>idb</code> library) and then on <code>success</code>, I read some of this data and setup a local state using <code>setData</code> and use this state to <code>render</code></li>
</ol>
<p>Basically all of the above works - so there is no problem with that (It's perhaps not right, but works!). My challenge is how to write unit test for this code. I have looked at using <code>async</code> inside <code>jest</code>.</p>
<p>The code looks something like as follows -</p>
<pre class=""lang-js prettyprint-override""><code>
const Component = ({db, data}) =&gt; {

  useEffect(() =&gt; {
    const saveDataToDB = (data, successCB) =&gt; {
       const tx = db.transaction(&quot;store&quot;, &quot;readwrite&quot;);
       
       const transactions = [tx.store.add(data)];
       transactions.push(tx.done);
  
       Promise.all(transactions).then((res) =&gt; {
          successCB();
       });
       
      const cb = () =&gt; {
          // Do somethingl
       }; 
       
       saveDataToDb(data, cb);

    };

  }, [data]);

   // Rendering part. 
   return (
     &lt;div id=&quot;component-div&quot;&gt;


     &lt;/div&gt;


   );


};

export default Component;
</code></pre>
<p>and I am trying to write the tests for this component using something like following</p>
<pre class=""lang-js prettyprint-override""><code>
describe('Component Tests', () =&gt; {
  
  it(&quot;Component Renders with Data&quot;, () =&gt; {
    const wrapper = mount(&lt;Component data={data} db={db}/&gt;);
    expect(wrapper.find(&quot;#component-div&quot;).toEqual(true);

  });


});

</code></pre>
<p>May be - there's something wrong the way component is implemented, that makes unit testing challenging. But it works, so not sure in general about what's the strategy for unit testing components that could have a few promise chains to resolve?</p>
",https://stackoverflow.com/questions/64046570/unit-tests-for-async-code-indexeddb-inside-react-component,"['reactjs', 'jestjs']",340,False,0,1
Mocking Static Method in c++,"<p>I just started working on unit testing using googleTest.
I have a situation where I have a static method of one class is calling inside the other class</p>

<pre><code>class A {
  public:
   static bool retriveJsonData(std::string name, Json::Value&amp; responseJsonData);
}
</code></pre>

<p>In other class i am using the Class A retriveJsonData method.</p>

<pre><code>class B {
   public:
     bool Method1 (std::string name) {
        Json::Value sampleJsonData;
        return A::retriveJsonData(name, sampleJsonData);
 }
</code></pre>

<p>Mocking of class A</p>

<pre><code>class MockA : public A {
  public:
    MOCK_MEHTOD2(retriveJsonData, bool(std::string, Json::Value));
</code></pre>

<p>}</p>

<p>Now I have to mock retriveJsonData in Testing of Method2 of class B using EXPECT_CALL.</p>

<p>Please help me to resolve how can I test this situation?</p>
",https://stackoverflow.com/questions/61227916/mocking-static-method-in-c,"['c++11', 'googletest', 'googlemock']",5234,True,2,4
Mock output binding Azure function python,"<p>I want to create a unit test for my Azure Functions in Python using unittest. I am following the example in <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#unit-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#unit-testing</a> , but I have added a blob output binding to my Http Trigger function, which I do not know how to mock when manually calling my function.</p>
<p>This is my function.json:</p>
<pre><code>{
  &quot;scriptFile&quot;: &quot;__init__.py&quot;,
  &quot;bindings&quot;: [
    {
      &quot;authLevel&quot;: &quot;function&quot;,
      &quot;type&quot;: &quot;httpTrigger&quot;,
      &quot;direction&quot;: &quot;in&quot;,
      &quot;name&quot;: &quot;req&quot;,
      &quot;methods&quot;: [
        &quot;post&quot;
      ],
      &quot;route&quot; : &quot;normalize&quot;
    },
    {
      &quot;type&quot;: &quot;http&quot;,
      &quot;direction&quot;: &quot;out&quot;,
      &quot;name&quot;: &quot;$return&quot;
    },
    {
      &quot;name&quot;: &quot;todb&quot;,
      &quot;type&quot;: &quot;blob&quot;,
      &quot;direction&quot;: &quot;out&quot;,
      &quot;path&quot;: &quot;carga-db/web_{rand-guid}.csv&quot;,
      &quot;connection&quot;: &quot;bbdstorage_STORAGE&quot;
    }
  ]
}
</code></pre>
<p>And this is my TestCase class:</p>
<pre><code>import unittest

import azure.functions as func
from web_api import main

class TestFunction(unittest.TestCase):
    def test_my_function(self):
        # Construct a mock HTTP request.
        req = func.HttpRequest(
            method='POST',
            body=None,
            url='/api/normalize')

        # Call the function.
        resp = main(req, #what to put here?)

        # Check the output.
        self.assertEqual(
            resp.get_body(),
            b'Hello Test',
        )
</code></pre>
",https://stackoverflow.com/questions/64215034/mock-output-binding-azure-function-python,"['python', 'unit-testing', 'azure-functions']",463,False,2,0
Can&#39;t pass unit testing for a simple math question,"<p>This is the code I scraped together and when unit testing it, I receive two errors shown below. The code works fine otherwise. How can I edit it to pass the test? I would greatly appreciate your help.</p>
<p>Also, if you know any resources which would help me learn to do it myself next time, please feel free to suggest one. Thank you very much in advance.</p>
<pre><code>import numpy as np


def calculate(arr):
    if len(arr) != 9:
        raise ValueError('List must contain nine numbers.')
    else:
        arr = np.array(arr)
        new_arr = arr.reshape((3, 3))
        mean = {'mean': [np.mean(new_arr, 0).tolist(), np.mean(new_arr, 1).tolist(), np.mean(arr).tolist()]}
        variance = {'variance': [np.var(new_arr, 0).tolist(), np.var(new_arr, 1).tolist(), np.var(arr).tolist()]}
        standard_deviation = {
            'standard deviation': [np.std(new_arr, 0).tolist(), np.std(new_arr, 1).tolist(), np.std(arr).tolist()]}
        maxi = {'max': [np.max(new_arr, 0).tolist(), np.max(new_arr, 1).tolist(), np.max(arr).tolist()]}
        mini = {'min': [np.min(new_arr, 0).tolist(), np.min(new_arr, 1).tolist(), np.min(arr).tolist()]}
        summ = {'sum': [np.sum(new_arr, 0).tolist(), np.sum(new_arr, 1).tolist(), np.sum(arr).tolist()]}
        return print(mean), print(variance), print(standard_deviation), print(maxi), print(mini), print(summ)


calculate([0, 1, 2, 3, 4, 5, 6, 7, 8])

</code></pre>
<h2>ERROR: test_calculate (test_module.UnitTests)</h2>
<p>Traceback (most recent call last):</p>
<p>File &quot;/home/runner/RectangularConsiderateInverse/test_module.py&quot;, line 10, in test_calculate
self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[2,6,2,8,4,0,1,5,7]'&quot;)</p>
<p>File &quot;/usr/lib/python3.8/unittest/case.py&quot;, line 943, in assertAlmostEqual
diff = abs(first - second)
TypeError: unsupported operand type(s) for -: 'tuple' and 'dict'</p>
<h2>ERROR: test_calculate2 (test_module.UnitTests)</h2>
<p>Traceback (most recent call last):</p>
<p>File &quot;/home/runner/RectangularConsiderateInverse/test_module.py&quot;, line 15, in test_calculate2
self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[9,1,5,3,3,3,2,9,0]'&quot;)</p>
<p>File &quot;/usr/lib/python3.8/unittest/case.py&quot;, line 943, in assertAlmostEqual
diff = abs(first - second)
TypeError: unsupported operand type(s) for -: 'tuple' and 'dict'</p>
<p><strong>The unit testing code:</strong></p>
<pre><code>import unittest
import mean_var_std


# the test case
class UnitTests(unittest.TestCase):
    def test_calculate(self):
        actual = mean_var_std.calculate([2,6,2,8,4,0,1,5,7])
        expected = {'mean': [[3.6666666666666665, 5.0, 3.0], [3.3333333333333335, 4.0, 4.333333333333333], 3.888888888888889], 'variance': [[9.555555555555557, 0.6666666666666666, 8.666666666666666], [3.555555555555556, 10.666666666666666, 6.222222222222221], 6.987654320987654], 'standard deviation': [[3.091206165165235, 0.816496580927726, 2.943920288775949], [1.8856180831641267, 3.265986323710904, 2.494438257849294], 2.6434171674156266], 'max': [[8, 6, 7], [6, 8, 7], 8], 'min': [[1, 4, 0], [2, 0, 1], 0], 'sum': [[11, 15, 9], [10, 12, 13], 35]}
        self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[2,6,2,8,4,0,1,5,7]'&quot;)

    def test_calculate2(self):
        actual = mean_var_std.calculate([9,1,5,3,3,3,2,9,0])
        expected = {'mean': [[4.666666666666667, 4.333333333333333, 2.6666666666666665], [5.0, 3.0, 3.6666666666666665], 3.888888888888889], 'variance': [[9.555555555555555, 11.555555555555557, 4.222222222222222], [10.666666666666666, 0.0, 14.888888888888891], 9.209876543209875], 'standard deviation': [[3.0912061651652345, 3.39934634239519, 2.0548046676563256], [3.265986323710904, 0.0, 3.8586123009300755], 3.0347778408328137], 'max': [[9, 9, 5], [9, 3, 9], 9], 'min': [[2, 1, 0], [1, 3, 0], 0], 'sum': [[14, 13, 8], [15, 9, 11], 35]}
        self.assertAlmostEqual(actual, expected, &quot;Expected different output when calling 'calculate()' with '[9,1,5,3,3,3,2,9,0]'&quot;)
    
    def test_calculate_with_few_digits(self):
        self.assertRaisesRegex(ValueError, &quot;List must contain nine numbers.&quot;, mean_var_std.calculate, [2,6,2,8,4,0,1,])

if __name__ == &quot;__main__&quot;:
    unittest.main() ```
</code></pre>
",https://stackoverflow.com/questions/64427356/cant-pass-unit-testing-for-a-simple-math-question,"['python', 'numpy', 'unit-testing']",206,True,-1,1
How do I write customized unit tests in R?,"<p>I am using the tinytest package for unit testing and wanted to modify some of the tests which did not work out. To boil down the problem I give the following example. I define a new function</p>

<pre class=""lang-r prettyprint-override""><code>expect_equal_new &lt;- function(a,b){expect_equal(a,b)}
</code></pre>

<p>If I put <code>expect_equal_new</code> and <code>expect_equal</code> in a test file and run <code>test_all()</code> from the tinytest package, only the result of <code>expect_equal</code> appears in the summary. 
Why is that the case? Is there a way that <code>test_all()</code> also finds <code>expect_equal_new</code>?</p>
",https://stackoverflow.com/questions/61418036/how-do-i-write-customized-unit-tests-in-r,"['r', 'unit-testing', 'testing', 'automated-tests', 'tinytest']",56,False,2,0
Unit testing of HttpsCallable cloud functions - online mode,"<p>I am designing a backend api (for android and iOS apps) around <a href=""https://firebase.google.com/docs/functions/callable"" rel=""nofollow noreferrer"">HttpsCallable</a> cloud functions. It becomes quite cumbersome to test them through the app, so I wish to switch to unit testing the functions (before production deployment) using the <code>firebase-functions-test</code> tool. I have been following this <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">unit testing tutorial</a>. </p>

<p>I am having some issues running the unit tests in online mode. Let me provide some details.  </p>

<p>Here is my `package.json' content:</p>

<pre><code>{
  ""name"": ""functions"",
  ""description"": ""Cloud Functions for Firebase"",
  ""scripts"": {
    ""lint"": ""eslint ."",
    ""serve"": ""firebase serve --only functions"",
    ""shell"": ""firebase functions:shell"",
    ""start"": ""npm run shell"",
    ""deploy"": ""firebase deploy --only functions"",
    ""logs"": ""firebase functions:log"",
    ""test"": ""mocha --reporter spec""
  },
  ""engines"": {
    ""node"": ""8""
  },
  ""dependencies"": {
    ""@google-cloud/tasks"": ""^1.9.0"",
    ""@googlemaps/google-maps-services-js"": ""^2.0.2"",
    ""chai"": ""^4.2.0"",
    ""firebase-admin"": ""^8.6.0"",
    ""firebase-functions"": ""^3.3.0"",
  },
  ""devDependencies"": {
    ""eslint"": ""^5.12.0"",
    ""eslint-plugin-promise"": ""^4.0.1"",
    ""firebase-functions-test"": ""^0.1.7"",
    ""mocha"": ""^7.1.1""
  },
  ""private"": true
}
</code></pre>

<p>I am using google APIs (<em>Directions</em>, <em>Geocoding</em> etc) from firebase backend, therefore to be able to access them while running my tests, I configured my tests located at <code>test/index.test.js</code> as recommended in the <em>Unit testing tutorial</em> as follows:</p>

<pre><code>const firebaseConfig = {
  apiKey: ...,
  authDomain: ...,
  databaseURL: ""https://my-project.firebaseio.com"",
  projectId: ""my-project"",
  storageBucket: ""my-project.appspot.com"",
  messagingSenderId: ********,
  appId: *********
};


const test = require('firebase-functions-test')(firebaseConfig
  , 'path_to_json_keyfile/myproject.json');
</code></pre>

<p>Below is the sample test code. Note that all my callable functions return <a href=""https://firebase.google.com/docs/reference/node/firebase.functions.HttpsError"" rel=""nofollow noreferrer"">HttpsError</a>, and the test below, simply checks for the <code>code</code> field of <code>HttpsError</code>, if its <code>ok</code>, the test passes. The functions I am testing reside in a separate <code>rides.js</code> file, which the <code>index.js</code> exports as <code>exports.rides = require(./rides.js)</code> (not shown below)</p>

<pre><code>const chai = require('chai');
const assert = chai.assert;

describe('Cloud functions', () =&gt; {
  let rideFunctions;
  before(() =&gt; {
    rideFunctions = require('../index.js');
  });

  after(() =&gt; {
    test.cleanup();
  });

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

    it('should return ok', async () =&gt; {
      data = {
        riderType: 1,
        pickup_lat: 37.0,
        pickup_lng: -122,
        dropoff_lat: 37.01,
        dropoff_lng: -122.01,
        scheduledTime: 1585939000,
        ts: 1585939000,
        tz_id: ""uslax""
      }

      context = {
        auth: {
          uid: AUTH_ID_FOR_USER_ACCOUNT
        }
      };

      const wrappedGetRideEstimate = test.wrap(rideFunctions.rides.getRideEstimate);

      let httpsError = await wrappedGetRideEstimate(data, context);
      return assert.equal(httpsError.code, 'ok');
    });


  })

  describe('testCallable', () =&gt; {
    it('should return ok', async () =&gt; {
      data = {}
      context = {}
      const wrappedTestCallable = test.wrap(rideFunctions.rides.testCallable);
      let httpsError = await wrappedTestCallable(data, context);
      return assert.equal(httpsError.code, 'ok');

    })
  })


})
</code></pre>

<p><strong>Problem</strong></p>

<ol>
<li>My simple <code>testCallable</code> function of the form </li>
</ol>

<pre><code>exports.testCallable = functions.https.onCall((data, context) =&gt; {
    console.log('testCallable');
    return new functions.https.HttpsError('ok', '', '');
})
</code></pre>

<p>passes the test (as expected) but inexplicably, it seems it is running in the offline mode, as there is no record of it on cloud function logs in Firebase Console. Also, if I disable connectivity of my laptop, the test result remains the same suggesting that somehow this function is running in the offline mode. </p>

<ol start=""2"">
<li><p>My <code>getRideEstimate</code> function which calls the google <code>Directions</code> API, returns a lengthy <code>400</code> error indicating some issue with forming the request to Directions API. I don't know if this error is related to the first problem, but since the Directions API call is embedded deeper inside the <code>getRideEstimate</code> function, it does suggest that the function is getting called, but somehow the API call is failing. </p></li>
<li><p>Is there any other way to test HttpsCallable functions in online mode?</p></li>
</ol>
",https://stackoverflow.com/questions/61037187/unit-testing-of-httpscallable-cloud-functions-online-mode,"['javascript', 'firebase', 'google-cloud-functions', 'firebase-tools', 'google-directions-api']",987,False,2,1
Angular unit test ngOnInit subscription,"<p>I am starting out with unit testing in Angular 9 with Jasmine.  </p>

<p>I am testing a simple component which implements <code>ngOnInit</code>:</p>

<pre><code>export class HomeComponent implements OnInit {

      constructor(private router: Router
        , private authenticationService: AuthenticationService) { }

        ngOnInit(): void {
        this.authenticationService.checkIsAuthenticatedObservable()
        .subscribe(
          (isAuthenicated: boolean) =&gt; {
            if (isAuthenicated === true) {
              this.router.navigate(['/observation-feed']);
            }
          });
        }
      }
</code></pre>

<p>I am hitting the error with executing the ngOnInIt lifecycle hook:</p>

<pre><code>TypeError: Cannot read property 'subscribe' of undefined
    at &lt;Jasmine&gt;
    at HomeComponent.ngOnInit (http://localhost:9876/_karma_webpack_/main.js:8140:13)
</code></pre>

<p>My test spec is setup like this:</p>

<pre><code>describe('HomeComponent', () =&gt; {
  let component: HomeComponent;
  let fixture: ComponentFixture&lt;HomeComponent&gt;;
  let router: Router;
  let mockAuthenticationService;

  beforeEach(async(() =&gt; {
    mockAuthenticationService = jasmine.createSpyObj(['checkIsAuthenticatedObservable']);

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([
          // { path: 'login', component: DummyLoginLayoutComponent },
        ])
      ],
      declarations: [ HomeComponent ],
      providers: [
        { provide: AuthenticationService, useValue: mockAuthenticationService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HomeComponent);
    router = TestBed.get(Router);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    mockAuthenticationService.checkIsAuthenticatedObservable.and.returnValue(of(false));
    fixture.detectChanges();
    // component.ngOnInit();

    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>I have attempted various combinations of setting up the mock object, and calling <code>fixture.detectChanges();</code> and <code>component.ngOnInit();</code> at different points in the intialization.  None of what I have tried has worked.  What's going wrong here?</p>
",https://stackoverflow.com/questions/60739568/angular-unit-test-ngoninit-subscription,"['angular', 'jasmine']",4327,True,1,1
Which `Clock` implementation is the default in java.time?,"<p>The <em>java.time</em> framework built into Java 8 and later includes the <a href=""https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Clock.html"" rel=""noreferrer""><code>Clock</code></a> class. This class provides several variations useful for testing our date-time handling code.</p>
<pre><code>Instant.now( Clock.fixed​( myInstant , myZoneId ) )
</code></pre>
<p>Which <code>Clock</code> instance represents the default used implicitly in <em>java.time</em> calls where we do not specify a <code>Clock</code>?</p>
<pre><code>Instant.now()
</code></pre>
<p>I imagine the default is either:</p>
<ul>
<li><a href=""https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Clock.html#systemDefaultZone()"" rel=""noreferrer""><code>systemDefaultZone()</code></a></li>
<li><a href=""https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Clock.html#systemUTC()"" rel=""noreferrer""><code>systemUTC()</code></a></li>
</ul>
<p>…but the documentation does not say which.</p>
<p>When doing unit-testing, sometimes we need a clock with altered behavior. But when we want to explicitly pass a <code>Clock</code> object that gives default behavior, what do we use?</p>
",https://stackoverflow.com/questions/62494522/which-clock-implementation-is-the-default-in-java-time,"['java', 'clock', 'java-time']",1469,True,10,1
Spring Boot: One auto-configuration for prod and another one for unit tests,"<p>I'm working on a library which has two maven modules: <code>core</code> and <code>test</code>. Both of the modules come with an auto-configuration class (defined in <code>spring.factories</code>).</p>

<p><code>test</code> actually is dependent on <code>core</code> (it uses its interfaces and supply mock classes).</p>

<p>Now, as a user of the library I'd like to:</p>

<ul>
<li>On production, to <code>@Autowire</code> the real implementation</li>
<li>On unit-testing to <code>@Autowire</code> the mocked implementation</li>
</ul>

<p>So I guess I need to use some <code>@CondiationalOn...</code> classes but how exactly? </p>
",https://stackoverflow.com/questions/62373865/spring-boot-one-auto-configuration-for-prod-and-another-one-for-unit-tests,"['java', 'spring', 'spring-boot', 'dependency-injection', 'mocking']",47,False,1,0
How can we run C++ Unit Test in Github Workflow?,"<p>I am using Microsoft Unit Testing Framework. I have successfully created and used the tests to check the program. I want to create an assignment for students where the same test cases can run as a workflow so that the assignments can be checked on every push on Github repository. How to configure the workflow so that the workflow use the test file in the folder to run the tests?</p>
",https://stackoverflow.com/questions/63452906/how-can-we-run-c-unit-test-in-github-workflow,"['c++', 'unit-testing', 'github', 'github-actions']",1068,False,1,0
How do I Mock User.Identity with MOQ?,"<p>I am new to unit testing, and I need to mock the user Identity in my controller.
My Test fails at User.Identity.IsAuthenticated. I get a  nullReferenceException. I mean this is expected.
I believe I just do not know how to use Moq with Identity.</p>

<pre><code>
        public IActionResult Index()
        {
            bool isAuthenticated = User.Identity.IsAuthenticated;


            if (!isAuthenticated)
            {
                return RedirectToPage(""/Account/Login"", new { area = ""Identity"" });
            }

            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim = claimsIdentity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);



            userId = claim.Value;

            var model = new YeetViewModel();
            location = _accountServices.getLocation(userId);
            model.yeets = _yeetServices.GetYeetsByNew(location);

            model.location = location;

            return View(model);
        }
</code></pre>

<p>This is my Test function</p>

<pre><code> [Fact]
        public void PassWithUser()
        {
            // Arrange


            var controller = new YeetController(_logger);


             var fakeHttpContext = new Mock&lt;HttpContext&gt;();
            var fakeIdentity = new GenericIdentity(""User"");
            var principal = new GenericPrincipal(fakeIdentity, null);


            ViewResult views = controller.Index() as ViewResult;

            // Act
            // Expecting it to throw because the user inside Index is null and not set to anything
            Assert.NotNull(views);
        }
</code></pre>

<p>Please help me understand what I am doing wrong, and how to actually use Moq correctly. Sorry for my beginerness.</p>
",https://stackoverflow.com/questions/60292808/how-do-i-mock-user-identity-with-moq,"['.net', 'asp.net-core', 'asp.net-identity', 'moq', 'xunit']",30,False,1,0
How to unit testing OidcSecurityService.checkAuth function with Jasmine?,"<p>I am using Jasmine for unit testing in Angular. And I am using the OidcSecurityService service for security. Now I want to unit test this piece for the automatic login:</p>
<pre><code>export class AppComponent implements OnInit {
  title = 'cityflows-client';
  constructor(public oidcSecurityService: OidcSecurityService, private router: Router, public platform: Platform) {}

  ngOnInit() {
    this.oidcSecurityService
      .checkAuth()

      .subscribe(isAuthenticated =&gt; {
        if (!isAuthenticated) {
          if ('/autologin' !== window.location.pathname) {
            this.write('redirect', window.location.pathname);
            this.router.navigate(['/autologin']);
          }
        }
        if (isAuthenticated) {
          this.navigateToStoredEndpoint();
        }
      });
  }
</code></pre>
<p>and so the unit test looks like this:</p>
<pre><code>describe('AppComponent', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      providers:    [ {provide: OidcSecurityService, useClass: OidcSecurityServiceStub} ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create the app', () =&gt; {
    expect(component).toBeTruthy();
  }); 
});
</code></pre>
<p>And the stub looks like this:</p>
<pre><code>export class OidcSecurityServiceStub {
  getToken() {
    return 'some_token_eVbnasdQ324';
  }

  checkAuth(url: string) {
    return of(url);
  }

  authorize(authOptions?: AuthOptions) {
    if (authOptions) {
      return authOptions.urlHandler('http://localhost');
    } else {
      return null;
    }
  }
}
</code></pre>
<p>But i see in the coverage report this:</p>
<p>by the if that the else part is not taken.</p>
<p>So what I have to change? Thank you</p>
<pre><code>  it('should redirect user to login page if user is not logged in', () =&gt; {
    
    expect(component).toBeTruthy();
  });
</code></pre>
",https://stackoverflow.com/questions/64366686/how-to-unit-testing-oidcsecurityservice-checkauth-function-with-jasmine,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'istanbul']",690,True,1,1
F#: How to test internal modules from another project?,"<p>I follow the best F# practices from <a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-fsharp-with-mstest"" rel=""nofollow noreferrer"">.Net documentation</a>:</p>
<ul>
<li>I create a project for the Application (console, not library)</li>
<li>I create a project for the Tests (with Expecto but doesn't matter)</li>
</ul>
<p>Problem: Some of my Application modules are not exposed via the <code>internal</code> keyword. Thus I cannot import these modules in my Tests project.</p>
<p>=&gt; How can I perform unit testing of these modules? Should I remove the internal access control?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/63481258/f-how-to-test-internal-modules-from-another-project,"['.net-core', 'f#']",169,True,1,1
Get the calling method name in ILogger,"<p>I have a custom logger class which implements the ILogger interface. The custom logger is a separate assembly/nuget. I was trying to use stacktrace to find the name of the calling method but it seems it differs if used in the program versus a unit testing project. Is there a more convenient way to get the calling method e.g. the calling assembly method name?</p>
<pre><code>public class MyClass {

   private void HelloWorld() {
        var myLoggerProvider = new LoggerProvider(Config);
        LoggerFactory.AddProvider(myLoggerProvider);
        var logger = LoggerFactory.CreateLogger&lt;Program&gt;();
        LogInformation(&quot;HelloWorld&quot;);
   }
}
</code></pre>
<p>//   Inside custom logger</p>
<pre><code> ////...
     public void Log&lt;TState&gt;(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func&lt;TState, Exception, string&gt; formatter)
    {
       //   Get the calling function name
      var classFunction = new StackTrace(4).GetFrame(0).GetMethod().Name;
    }
 ///....
</code></pre>
",https://stackoverflow.com/questions/65358040/get-the-calling-method-name-in-ilogger,"['c#', 'asp.net-core']",21,False,1,0
How to negative assert_response in unit testing with Rails,"<p>How can one test if the HTTP response is <strong>not</strong> something in the standard unit-testing framework with Rails (Ver 6.0, more specifically)? Basically it is negation of <a href=""https://apidock.com/rails/v6.0.0/ActionDispatch/Assertions/ResponseAssertions/assert_response"" rel=""nofollow noreferrer"">assert_response</a> like this:</p>
<pre class=""lang-rb prettyprint-override""><code>test &quot;should get index&quot; do
  get restricted_articles_url
  assert_response_NOT :success  # &lt;= this method does not exist.
end
</code></pre>
<p>The background is, the user tested should not be granted access to the URL (or Controller method), but what response would be returned may change later in the development and the exact response is of secondary importance.</p>
",https://stackoverflow.com/questions/64554065/how-to-negative-assert-response-in-unit-testing-with-rails,"['ruby-on-rails', 'unit-testing', 'httpresponse']",207,True,1,2
Why mocking a Repository requires a virtual function and mocking IRepository overrides the existing function?,"<p>I am doing unit testing using NUnit and Moq framework. When I try to mock the IRepository using mockRepo.Setup(x=&gt;x.GetStr(It.IsAny)()).Returns(str) then the method which is to be tested gets overridden inside Repository class and the build fails. But instead mocking the IRepository if I mock the Repository making the method which is to be tested as virtual then the data is getting mocked and the test runs.</p>
",https://stackoverflow.com/questions/64114132/why-mocking-a-repository-requires-a-virtual-function-and-mocking-irepository-ove,"['c#', 'asp.net-core', 'nunit', 'moq', 'irepository']",211,True,1,1
How to unit test a method with a nested call to super class method?,"<p>I have Java 8, JUNIT, and Mockito in my project, but I am still learning the unit testing art.So need your help.</p>

<p>In my scenario --> <code>class B extends Class A</code></p>

<p>CLass B contains a public method <code>mOfB()</code></p>

<p>CLass A contains a method <code>mOfA()</code></p>

<p>I would like to JUnit my method <code>mOfB()</code>. </p>

<p><code>mOfB()</code> contains a call to <code>mOfA()</code>. And <code>mOfA()</code> returns a <code>List&lt;Employee&gt;</code> </p>

<p><code>Employee</code> is an object with few attributes in primitive datatype and a <code>Map&lt;Depts, CostCentre&gt;</code></p>

<p>How should I approach JUnit testing here? </p>
",https://stackoverflow.com/questions/61943002/how-to-unit-test-a-method-with-a-nested-call-to-super-class-method,"['java', 'junit']",489,True,1,1
"Xunit test, creating a user","<p>Hey im trying to make this unit test work but it says, A test class may only define a single public constructor.
but im not quite sure what to do or what im doing wrong?</p>
<pre><code>using Application;
using Domain.Models;
using Infrastructure;
using Infrastucture.Reposetories.Interface;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using Xunit;

namespace Tests
{
    public class UserTests
    {

        [Collection(&quot;Sequential&quot;)]
        public class Usertets
        {
            private readonly IUsersHandlers usersHandler;
            
            public Usertets(IUsersHandlers usersHandler)
            {
                this.usersHandler = usersHandler;

            }
            private readonly DB Context;

            public Usertets(DB dB)
            {
                this.Context = dB;
            }
            Guid UserID = Guid.NewGuid();
            [Fact]
            public void CreateUserTest()
            {
                usersHandler.CreateUser(UserID, &quot;Christian&quot;, &quot;Gerken&quot;, &quot;christianger14@yahoo.dk&quot;, &quot;hejsa1&quot;, &quot;25669504&quot;, (new DateTime(2000, 1, 1)), &quot;sofie6&quot;, 7120, &quot;danmark&quot;, Gender.Male);


                var check = Context.Users.Where(x =&gt; x.ID == UserID).FirstOrDefault();
                Assert.NotNull(check);
            }

            [Fact]
            public void FindUser()
            {
                
                var user = usersHandler.GetUsersByID(UserID);
                Assert.NotNull(user);
            }
        }


    }
}
    
</code></pre>
<p>im using depency injection though optimictic concurrency
for my Iuserhandlers usershandler and and dataacces layer</p>
<p>but is there something based on this that im missing? or am I trying the wrong unit testing?</p>
",https://stackoverflow.com/questions/65152324/xunit-test-creating-a-user,"['c#', 'dependency-injection', 'concurrency', 'xunit']",194,True,1,2
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension &quot;.ts&quot; on Visual Studio Code,"<p>I've been working on unit-testing some code, and out of seemingly nowhere, I got an error about unknown file extensions (before, I got errors about how some type wasn't recognized).</p>
<p>Here is my package.json:</p>
<pre><code>{
  &quot;name&quot;: &quot;cgt-core-engine-mv&quot;,
  &quot;description&quot;: &quot;API container for other CGT plugins&quot;,
  &quot;version&quot;: &quot;1.01.03&quot;,
  &quot;author&quot;: &quot;CG-Tespy&quot;,
  &quot;repository&quot;: {
    &quot;type&quot;: &quot;git&quot;,
    &quot;url&quot;: &quot;https://github.com/CG-Tespy/CGT_CoreEngine_MV&quot;
  },
  &quot;scripts&quot;: {
    &quot;build&quot;: &quot;tsc &amp; (rollup -c)&quot;,
    &quot;test&quot;: &quot;mocha -r ts-node/register Test/**/*.ts&quot;
  },
  &quot;dependencies&quot;: {},
  &quot;devDependencies&quot;: {
    &quot;@types/chai&quot;: &quot;^4.2.12&quot;,
    &quot;@types/mocha&quot;: &quot;^8.0.0&quot;,
    &quot;@types/sinon&quot;: &quot;^9.0.4&quot;,
    &quot;chai&quot;: &quot;^4.2.0&quot;,
    &quot;mocha&quot;: &quot;^8.0.1&quot;,
    &quot;rollup&quot;: &quot;^2.00.1&quot;,
    &quot;rollup-plugin-node-resolve&quot;: &quot;^5.2.0&quot;,
    &quot;rollup-pluginutils&quot;: &quot;^2.8.2&quot;,
    &quot;sinon&quot;: &quot;^9.0.2&quot;,
    &quot;ts-node&quot;: &quot;^8.10.2&quot;,
    &quot;typescript&quot;: &quot;^3.9.6&quot;
  },
  &quot;type&quot;: &quot;module&quot;
}
</code></pre>
<p>Here is my tsconfig.json:</p>
<pre><code>{
    &quot;compilerOptions&quot;: {
      &quot;target&quot;: &quot;es5&quot;,
      &quot;module&quot;: &quot;CommonJS&quot;,
      &quot;esModuleInterop&quot;: true,

      &quot;sourceMap&quot;: false,
      &quot;downlevelIteration&quot;: true,
    },
    &quot;include&quot;: [&quot;_MainSource/**/*&quot;, &quot;Tests/**/*&quot;, &quot;@typeDefs/**/*&quot;],
}
</code></pre>
<p>I really have no idea where this came from. I have a separate project where I was able to unit-test things just fine, and it didn't give me any errors. The package.json for it:</p>
<pre><code>{
  &quot;name&quot;: &quot;unittesting&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;description&quot;: &quot;For practicing unit-testing&quot;,
  &quot;main&quot;: &quot;main.js&quot;,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;mocha -r ts-node/register test/**/*.ts&quot;
    
  },
  &quot;author&quot;: &quot;&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;devDependencies&quot;: {
    &quot;@types/chai&quot;: &quot;^4.2.11&quot;,
    &quot;@types/mocha&quot;: &quot;^8.0.0&quot;,
    &quot;chai&quot;: &quot;^4.2.0&quot;,
    &quot;mocha&quot;: &quot;^8.0.1&quot;,
    &quot;ts-node&quot;: &quot;^8.10.2&quot;,
    &quot;typescript&quot;: &quot;^3.9.7&quot;
  },
  &quot;type&quot;: &quot;module&quot;
}
</code></pre>
<p>Its tsconfig:</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    /* Basic Options */

    &quot;target&quot;: &quot;es5&quot;,                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    &quot;module&quot;: &quot;CommonJS&quot;,                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    
    &quot;esModuleInterop&quot;: true,
    
  },
  &quot;include&quot;: [&quot;src/**/*&quot;, &quot;tests/**/*&quot;],
}
</code></pre>
<p>What could be causing this issue? I've tried the suggestions <a href=""https://stackoverflow.com/questions/62096269/cant-run-my-node-js-typescript-project-typeerror-err-unknown-file-extension"">here</a>, but it didn't work (even after looking at the Github issue linked).</p>
",https://stackoverflow.com/questions/63386054/typeerror-err-unknown-file-extension-unknown-file-extension-ts-on-visual-s,"['typescript', 'unit-testing', 'visual-studio-code']",19466,False,21,2
VueComponent.mounted : TypeError: Cannot read property &#39;get&#39; of undefined in mounted hook,"<p>I am using jest for unit testing in nuxt js
I have mounted hook like this</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>async mounted(){
  
  try{
     var response = await this.$axios.get(""api_url here"");
     this.result = response.data;
  } catch(e){
    console.log(""Exception: "",e)
  }
}</code></pre>
</div>
</div>
</p>
<p>when i do unit test for it my code is . utnit.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>jest.mock(""axios"", () =&gt; ({
   get: () =&gt; Promise.resolve({ data: [{ val: 1 }] })
}));


import { mount } from '@vue/test-utils';
import file from '../filefile';
import axios from ""axios"";


describe('file', () =&gt; {
  test('check comp. working correctly', () =&gt; {
    var wrapper = mount(file);
    afterEach(() =&gt; {
      wrapper.destroy()
    })
  })   
})</code></pre>
</div>
</div>
</p>
<p>I am getting this warn there and there is no data in the results</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>Exception:  TypeError: Cannot read property 'get' of undefined
          at VueComponent.mounted</code></pre>
</div>
</div>
</p>
<p>how do I know what is the problem here, is this I can not access axios in the unit file Is there  any specific way to test Axios in mounted hook</p>
",https://stackoverflow.com/questions/63806420/vuecomponent-mounted-typeerror-cannot-read-property-get-of-undefined-in-mou,"['unit-testing', 'vue.js', 'jestjs', 'nuxt.js', 'vue-test-utils']",2991,True,3,1
Trouble with generics using custom equality comparison,"<p>I have a class heirarchy as follows:</p>

<pre><code>public abstract class Issue
{
    // some base properties
    // these are not included in equality checks for deriving classes
    // also not performing equality checks on this base class (it is abstract anyway)
}

public class IssueTypeA : Issue, IEquatable&lt;IssueTypeA&gt;
{
    // some properties specific to this class
    // these are the two for which equality comparison is performed
    public string requirement { get; set; }
    public string preamble { get; set; }

    public bool Equals(IssueTypeA that)
    {
        // determine based on the values of the properties
        // they must both be the same for equality
        if ((this.requirement.Equals(that.requirement)) &amp;&amp;
           (this.preamble.Equals(that.preamble)))
        {
            return true;
        }

        return false;
    }
}

public class IssueTypeB : Issue, IEquatable&lt;IssueTypeB&gt;
{
    // some properties specific to this class

    public bool Equals(IssueTypeB that)
    {
        // determine based on the values of the properties
    }
}
</code></pre>

<p>There is another class, intended to receive objects in the above heirarchy (except the base class, of course), and do some comparison operations with them:</p>

<pre><code>public class Comparer&lt;T&gt; where T : Issue
{
    // various comparison methods
    public IEnumerable&lt;T&gt; getReferenceChangedIssues(IEnumerable&lt;T&gt; spreadsheetIssues, IEnumerable&lt;T&gt; downloadedIssues)
    {
        foreach (T spreadsheetRecord in T spreadsheetIssues)
        {
            foreach (T downloadedIssue in downloadedIssues)
            {
                // this is the point of failure
                // there are cases in which this should be true, but it is not
                if (spreadsheetRecord.Equals(downloadedIssue))
                {
                    // the referenceChanged method works fine by itself
                    // it has been unit tested
                    if (spreadsheetRecord.referenceChanged(downloadedIssue))
                        yield return spreadsheetRecord;
                }
            }
        }
    }
}
</code></pre>

<p>Through unit testing and debugging, it's apparent that the <strong>custom</strong> <code>Equals</code> methods defined above are not being used correctly by <code>Comparer</code>. Why is this? It is also intended to include methods with some set operations in the future, which will need <code>Equals</code>.</p>
",https://stackoverflow.com/questions/61605771/trouble-with-generics-using-custom-equality-comparison,"['c#', '.net', 'generics']",46,False,0,1
Prevent synchronous API usage with EF Core,"<p>How can I prevent synchronous database access with Entity Framework Core? e.g. how can I make sure we are calling ToListAsync() instead of ToList()?</p>
<p>I've been trying to get an exception to throw when unit testing a method which calls the synchronous API. Are there configuration options or some methods we could override to make this work?</p>
<p>I have tried using a DbCommandInterceptor, but none of the interceptor methods are called when testing with an in-memory database.</p>
",https://stackoverflow.com/questions/62752224/prevent-synchronous-api-usage-with-ef-core,"['c#', 'entity-framework-core', 'ef-core-3.1']",621,True,6,4
How to set EntryAssembly for tests in .Net Core,"<p>I am currently migrating a project and it's test projects from .Net Framework to .Net Core. </p>

<p>In .Net Framework, we used to be able to do something like this to set the EntryAssembly for tests :</p>

<pre><code>AppDomainManager manager = new AppDomainManager();
FieldInfo entryAssemblyfield = manager.GetType().GetField(""m_entryAssembly"", BindingFlags.Instance | BindingFlags.NonPublic);
entryAssemblyfield.SetValue(manager, assembly);

AppDomain domain = AppDomain.CurrentDomain;
FieldInfo domainManagerField = domain.GetType().GetField(""_domainManager"", BindingFlags.Instance | BindingFlags.NonPublic);
domainManagerField.SetValue(domain, manager);
</code></pre>

<p>Taken from here : <a href=""https://dejanstojanovic.net/aspnet/2015/january/set-entry-assembly-in-unit-testing-methods/"" rel=""noreferrer"">https://dejanstojanovic.net/aspnet/2015/january/set-entry-assembly-in-unit-testing-methods/</a></p>

<p>Since AppDomainManager is not available in .Net Core anymore, how can we accomplish something similar so that <code>Assembly.GetEntryAssembly();</code> returns what I want instead of the tests project assembly.</p>
",https://stackoverflow.com/questions/60604441/how-to-set-entryassembly-for-tests-in-net-core,"['c#', '.net-core', 'mstest', 'appdomain', '.net-core-3.1']",992,True,6,1
How can I mock Authentication in a Spring Boot when using an Exernal Authentication Source,"<p>I have a Spring Boot based app that us using ISAM Authentication from an external provider.
I have a rest/json endpoint <code>/actuator/health</code> that returns different data depending on if the user is authenticated or not.</p>

<p>How can I mock authentication during unit testing to ensure my configuration is correct?</p>

<p>In <code>setup()</code>, I've tried setting a token manually, and overriding AuthorizationService to return true.</p>

<pre><code>@Before
public void setUp() throws Exception
{
   mockMvc = webAppContextSetup(wac).apply(springSecurity()).build();

   List roles = Arrays.asList(new SimpleGrantedAuthority(""ROLE_USER""));

   UsernamePasswordAuthenticationToken auth =
           new UsernamePasswordAuthenticationToken(""dave"", ""secret"",
                                                   roles);

   if (!auth.isAuthenticated()) { fail(""NOT AUTHENTICATED!""); }

   SecurityContextHolder.getContext().setAuthentication(auth);

   //fake logged in
   when(authorizationService.isCurrentUserAuthorized(anyString(),
                                                     anyString(),
                                                     ArgumentMatchers.any(ResourceType.class),
                                                     ArgumentMatchers.any(ActionType.class)))
     .thenReturn(true);
}
</code></pre>

<p>However, when I run</p>

<pre><code>Authentication auth = SecurityContextHolder.getContext().getAuthentication();

if (!auth.isAuthenticated()) { fail(""NOT AUTHENTICATED!""); }

UsernamePasswordAuthenticationToken authToken =
              (UsernamePasswordAuthenticationToken)auth;

mockMvc.perform(get(""/health_secure"")
                  .principal(auth)
                  .header(""Authorization"", ""Bearer "" + token))
       .andDo(print())
       .andExpect(status().isOk())
       .andExpect(forwardedUrl(""/actuator/health""));
</code></pre>

<p>I get:  </p>

<pre class=""lang-none prettyprint-override""><code>""error"":""invalid_token"",""error_description"":""Cannot convert access token to JSON""
</code></pre>
",https://stackoverflow.com/questions/60400474/how-can-i-mock-authentication-in-a-spring-boot-when-using-an-exernal-authenticat,"['java', 'spring', 'spring-boot', 'spring-security', 'mockmvc']",898,True,0,2
Need Help | UnitTest | Kafka custom ConcurrentKafkaListenerContainerFactory with Custom Record FilterStrategy,"<p>Trying to unit test, ConcurrentKafkaListenerContainerFactory with custom RecordFilterStrategy, however not able to find optimal approach to test the filter strategy.</p>
<pre><code>  class ConsumerConfiguration {

  @Bean
  public ConcurrentKafkaListenerContainerFactory&lt;String, Message&gt; messageListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory&lt;String, Message&gt; factory =
        new ConcurrentKafkaListenerContainerFactory&lt;&gt;();
    factory.setConsumerFactory(consumerFactory());
    factory.setRecordFilterStrategy(consumerRecord -&gt; consumerRecord.value().getType().contains(&quot;MYFILTER&quot;));
    return factory;
  }

}
</code></pre>
<p><strong>Unit Test</strong></p>
<pre><code>  @Mock
  KafkaProperties kafkaProperties;
  ConsumerConfiguration configuration;
  @Test
  void testMessageListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory&lt;String, Message&gt; actual =
        configuration.messageListenerContainerFactory();
    assertEquals(kafkaProperties.buildConsumerProperties(),
        actual.getContainerProperties().getKafkaConsumerProperties());
  }

</code></pre>
<p>Though this code is good for unit testing, however does not provides the code coverge for Custom RecordFilterStrategy i.e. lambda function, so need help if some one have already done unittest/code coverage for Kafka Listener Container Factory and what is the best approach for handling.</p>
",https://stackoverflow.com/questions/63239177/need-help-unittest-kafka-custom-concurrentkafkalistenercontainerfactory-with,"['java', 'spring', 'unit-testing', 'mockito', 'spring-kafka']",501,False,0,1
How to stub a function that was called on api request in node js using sinon,"<pre><code>//routes.js
app.get('/:id/info',
    UnoController.getGameInfo,
    ...
);

//UnoController.js
async function getGameInfo(req, res) {
    data = await UnoModel.getGameInfo(req.params.id);
    if(data==null) return res.status(404).json({message:'Room Not Found'});
    res.json(data);
}


//UnoModel.js
exports.getGameInfo = async function (id) {
    return await mongodb.findById('uno', id);
}
</code></pre>

<p>I am writing unit testing in node js using sinon. <br>
I want stub the UnoModel.getGameInfo to return <code>{id:'123456789012'}</code>, When i hit <code>/someid/info</code> rest api.</p>

<p>I wrote the test case like below.</p>

<pre><code>//UnoApiTest.js
it('get game info with player payload and invalid room id', function (done) {
    sinon.stub(UnoModel, 'getGameInfo').resolves({ id: '123456789012' });
    request({
        url: 'http://localhost:8080/api/v1/game/uno/123456789012/info',
        headers: { 'x-player-token': jwt.sign({ _id: '123' }) }
    }, function (error, response, body) {
        expect(response.statusCode).to.equal(200);
        done();
    });
});
</code></pre>

<p>But i am receiving the statusCode as 404. <br>
I tried to console the data. Its actually fetching from db. 
It doesn't returns the provided value for stub.<br>
Can anyone help me with this? <br>
Is there any other way to do this?</p>
",https://stackoverflow.com/questions/61172026/how-to-stub-a-function-that-was-called-on-api-request-in-node-js-using-sinon,"['javascript', 'node.js', 'unit-testing', 'integration-testing', 'sinon']",1039,True,0,1
Getting null pointer exception while using var inside mocked class,"<p>I am writing unit tests for my play app. Some data in app is rarely changed needs to be accessed frequently. So, I am fetching it in start and storing it in a hashmap.</p>
<pre><code>var inMemQuestion:Map[Long,QuestionSchema.Question] = {
    println(&quot;Getting all questions from DB.....&quot;)
    Await.result(listAll, Duration.Inf).map(a =&gt; a.id-&gt;a).toMap
  }
</code></pre>
<p>In my methods I'm using data from here instead of db.</p>
<p>But when I try to mock this for unit testing my methods like this:</p>
<pre><code>val sampleQsn = QuestionSchema.Question(9.toLong,&quot;1 or 2&quot;,7.toLong,4.toLong,Some(1.0),Some(false),new java.sql.Timestamp(1599545742),new java.sql.Timestamp(1599552379))
val questionsRepo = mock[QuestionRepository]
when(questionsRepo.inMemQuestion(9)).thenReturn( // null pointer error in this line
  sampleQsn
)
</code></pre>
<p>I'm getting null pointer error. Can anyone help me in resolving that?</p>
",https://stackoverflow.com/questions/63840998/getting-null-pointer-exception-while-using-var-inside-mocked-class,"['scala', 'playframework', 'scalatest']",40,False,0,0
Seperating ConnectionString from source control and be able to perform integrating testing in Azure CI/CD pipeline,"<p>I've a WebAPI project and I'm using Azure CI/CD pipeline to deploy it in azure. The project contains unit testing and integration testing. And for integration testing it needs to access database.  But since I don't want to check in my connectionstring to source control, the build pipeline will always fail.</p>

<p>So, the question is what solutions/features or workaround exist that can help me accomplish this scenario?</p>
",https://stackoverflow.com/questions/61496963/seperating-connectionstring-from-source-control-and-be-able-to-perform-integrati,"['azure', 'azure-devops', 'database-connection', 'azure-pipelines']",248,True,0,2
Test an API call in React Component,"<p>I want to test the API call in my React component and also tried few ways by surfing the net.</p>
<p><strong>MyComponent:</strong></p>
<pre><code>    export const API = {
      getData() {
        return fetch(localStorage.blobUrl).then(res =&gt; res.blob())
      }
    }

    const downloadArchiveFile = () =&gt; {
    localStorage.setItem('blobUrl',bloburl);
    API.getData().then((blob) =&gt; {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement(&quot;a&quot;);
      a.style.display = &quot;none&quot;;
      a.href = url;
      // the filename you want
      a.download = templateName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
    })
  };
</code></pre>
<p><strong>MyComponent.test.js</strong></p>
<pre><code>it('api call', async () =&gt; {
        const fakeUserResponse = {
            'myResponse': {
                'a': '1',
                'b': '2' }
        };
        var apiFunc = jest.spyOn(API, 'getData').mockImplementationOnce(() =&gt; {
            return Promise.resolve({
                json: () =&gt; Promise.resolve(fakeUserResponse)
            })
        })
    })
</code></pre>
<p><strong>Test case is getting passed. But while seeing code coverage this code is not covered.</strong></p>
<p>See the code coverage report</p>
<p><a href=""https://i.stack.imgur.com/CuIGv.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/CuIGv.png"" alt=""enter image description here"" /></a></p>
<p><strong>Links which I refer:</strong></p>
<p><a href=""https://stackoverflow.com/questions/61576450/react-how-do-i-unit-test-an-api-call-in-jest"">React - how do I unit test an API call in Jest?</a></p>
<p><a href=""https://stackoverflow.com/questions/57656523/code-coverage-concern-on-promise-asynchronous-unit-testing-using-nockjs-and-jest"">Code coverage concern on promise/asynchronous unit testing using nockjs and jest</a></p>
",https://stackoverflow.com/questions/64222537/test-an-api-call-in-react-component,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",146,False,0,0
How to write a unit test for a React component that measure its rendering time?,"<p>I'm trying to come up with a solution for measuring my component's rendering time. I know about React Profiler, but I'm looking for something that can be included as part of the component's test suite, not a manual test. I think I could use timers but that seems a bit fragile. Ideally someone would know about something more robust. I use Enzyme + Jest for unit testing.</p>
<p>Thank you</p>
",https://stackoverflow.com/questions/64545566/how-to-write-a-unit-test-for-a-react-component-that-measure-its-rendering-time,"['reactjs', 'jestjs', 'enzyme']",380,True,0,1
How to pass in options to a Dialog when using TestFlow - Azure botframework v4 - C# - Unit Tests,"<p>Using Azure Bot framework v4 - C# ... xunit...</p>
<p>I have the following unit test for testing a Component Dialog that in turn uses an AdaptiveDialog.</p>
<p>As part of unit testing the dialog, I want to pass in options to the dialog - the options that get passed to the OnBeginDialogAsync overload of the Dialog class.</p>
<p>Any thoughts on how we can pass myDialogOptions as the options to the dialog?</p>
<p>Thank you
Regards
Athadu</p>
<pre><code>    public class ConfirmationDialog : ComponentDialog
    {
        public class Options
        {
            public string PromptTemplate { get; set; }
        }

        public ConfirmationDialog()
            : base(&quot;test&quot;)
        {
            
        }

        protected override Task&lt;DialogTurnResult&gt; OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default)
        {
            //
            // Avoiding using BotState here.  Instead ... use options...
            //    do something based on passed in options 
            //
        }
    }

        [Fact]
        public async Task TestMyComponentDialogThatUsesAdaptiveDialog()
        {
            //Arrange
            Setup();
            TestAdapter = (TestAdapter)new TestAdapter(&quot;my&quot;)
                                .UseStorage(memoryStorage)
                                .UseBotState(UserState, ConversationState)
                                .Use(Middlewares[0]);
            var dialogState = ConversationState.CreateProperty&lt;DialogState&gt;(&quot;dialogState&quot;);

            var dialogToTest = new ConfirmationDialog();
            var dialogManager = new DialogManager(dialogToTest);

            var myDialogOptions = new MyOptions { Name = &quot;Jon Doe&quot; };

            await new TestFlow(TestAdapter, async (turnContext, cancellationToken) =&gt;
            {
                &lt;&lt;&lt;&lt;&lt;&lt;  How to pass in Dialog Options myDialogOptions to the dialog - need to access it within OnBeginDialogAsync &gt;&gt;&gt;&gt;&gt;
                &lt;&lt;&lt;&lt;&lt;&lt;  of Dialog class override method OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default)   &gt;&gt;&gt;&gt;&gt;

                var result = await dialogManager.OnTurnAsync(turnContext, cancellationToken);
            })
            //Act
             .SendConversationUpdate()
            //Assert
             .AssertReply(activity =&gt;
                 {
                     var resolvedActivity = activity.AsMessageActivity();
                     resolvedActivity.Text.Should().StartWith(&quot;Some Text&quot;);
                 }, null, 2100)
             .StartTestAsync();
        }

</code></pre>
",https://stackoverflow.com/questions/63582847/how-to-pass-in-options-to-a-dialog-when-using-testflow-azure-botframework-v4,"['c#', 'azure', 'botframework', 'xunit']",220,True,0,1
go-testfixtures fixtures.Load() returns Checksum error,"<p>I was following the sample code <a href=""https://github.com/go-testfixtures/testfixtures/blob/master/README.md"" rel=""nofollow noreferrer"">here</a> to try set up a test MySQL database with fixtures for unit testing. I have the following code.</p>

<pre><code>func prepareTestDatabase() (*sql.DB, error) {
    err := godotenv.Load(""../.env"")
    if err != nil {
        return nil, err
    }

    conn, err := sql.Open(""mysql"", os.Getenv(""MYSQLURL_TEST""))
    if err != nil {
        return nil, err
    }

    fixtures, err := testfixtures.New(
        testfixtures.Database(conn),
        testfixtures.Dialect(""mysql""),
        testfixtures.Files(""fixtures/sampledata.yml""),
    )
    if err != nil {
        return nil, err
    }

    err = fixtures.Load()
    return conn, err
}
</code></pre>

<p>But <code>fixtures.Load()</code> failed and returned error:</p>

<pre><code>sql: Scan error on column index 1, name ""Checksum"": converting NULL to int64 is unsupported
</code></pre>

<p>The YAML file I used was like the following:</p>

<pre><code>- id: 1
  varchar_col: somevarchar
  decimal_col: 9999.99
  int_col: 123456789
  created_at: 2020-05-17 00:01:59

- id: 2
  varchar_col: somevarchar
  decimal_col: 9999.99
  int_col: 987654321
  created_at: 2020-05-17 00:01:59
</code></pre>

<p>So probably the sample data was not inserted into the database? I am sure database connection is fine and I can insert and read data from the test database.</p>
",https://stackoverflow.com/questions/61839875/go-testfixtures-fixtures-load-returns-checksum-error,"['mysql', 'unit-testing', 'go']",436,False,0,1
"TypeError: list indices must be integers or slices, not str on Unit Testing","<p>I have the error as <code>&quot;TypeError: list indices must be integers or slices, not str &quot;</code> while running a unit test on the following function. The following function is used to call the model that is saved in Google AI Platform. However, the data input has to be base64 serialized, hence, I include the get_serialized_example(raw) function within the tfx_test(request). Any help and advice are appreciated. Thanks in advance!</p>
<pre><code>def tfx_test(request):
    
    #User Inputs
    project = request.project
    model = request.model
    signature = request.signature
    version = request.version
    
    #Data inputs Base64 encoder 
    
    def get_serialized_example(raw):
        return tf.train.Example(
                features=tf.train.Features(
                  feature={&quot;value&quot;:
                              tf.train.Feature(bytes_list=tf.train.BytesList(value=[raw]))
                          }
                    )
                ).SerializeToString()


    b64_country_code = base64.b64encode(get_serialized_example(request.country_code)).decode('utf-8')
    
    b64_project_type = base64.b64encode(get_serialized_example(request.project_type)).decode('utf-8')
    
    # ml.googleapis.com
    service = googleapiclient.discovery.build('ml', 'v1')
    name = 'projects/{}/models/{}'.format(project, model)

    if version is not None:
        name += '/versions/{}'.format(version)

    response = service.projects().predict(
        name=name,
        body={
            'signature_name': signature,
            'instances': [
                    {
                       &quot;examples&quot;:{&quot;b64&quot;: b64_country_code,
                                   &quot;b64&quot;: b64_project_type}
                    }]
        }
    ).execute()

    if 'error' in response:
        raise RuntimeError(response['error'])

    return response['predictions']
</code></pre>
<p><strong>UNIT TESTING</strong></p>
<p>def test_safety_kfp_custom(self):</p>
<pre><code>self.request = TestScenario.populated_request(Test.test1)
self.response = tfx_test(self.request)

self.assertEqual(0.35915321111679077, self.response[&quot;predictions&quot;])
</code></pre>
<p><strong>Data Input for tfx_test function</strong></p>
<pre><code>class request():
    project = &quot;xxx&quot;
    model = &quot;xxx&quot;
    signature = &quot;xxx&quot;
    country_code = b&quot;UK&quot;
    project_type = b&quot;PT&quot;
    version = 'xxx'
</code></pre>
",https://stackoverflow.com/questions/62549037/typeerror-list-indices-must-be-integers-or-slices-not-str-on-unit-testing,"['python', 'python-3.x', 'base64']",126,False,0,1
Mediatr pattern unit testing,"<p>I'm trying to setup unit testing for my API controllers. I'm using the mediatr pattern and FakeIteasy.
I have the following code.</p>
<pre><code>public class ChannelGroupChannelsControllerTests
{
    private readonly ChannelGroupChannelsController _controller;
    private readonly IMediator _mediator;

    public ChannelGroupChannelsControllerTests()
    {
        var service = A.Fake&lt;IReadChannelGroupChannel&gt;();
        var mapper = A.Fake&lt;IMapper&gt;();

        var channelGroupChannel = new ChannelGroupChannel
        {
            Id = 1,
            ChannelGroupId = 1,
            ChannelId = 1,
            Channel = new Channel { Name = &quot;Channel Name&quot; }
        };

        _mediator = A.Fake&lt;IMediator&gt;();
        _controller = new ChannelGroupChannelsController(_mediator, mapper);

        A.CallTo(() =&gt; _mediator.Send(A&lt;GetChannelGroupChannelById&gt;._, A&lt;CancellationToken&gt;._)).Returns(channelGroupChannel);
    }


    [Fact]
    public async Task ChannelGroupChannelsController_ById()
    {
        var result = await _controller.ById(1);

        (result.Result as StatusCodeResult)?.StatusCode.Should().Be((int)HttpStatusCode.OK);
        result.Value.Should().BeOfType&lt;ChannelGroupChannelVM&gt;();
    }
}
</code></pre>
<p>Now the problem is that I keep getting NULL as a value.
I think the issue might be that GetChannelGroupChannelById has a constructor that expects the ID. But I'm not sure...</p>
<p>Does anybody know what could be wrong? I'm pretty new with the mocking stuff.</p>
<p>Kind regards</p>
",https://stackoverflow.com/questions/62712643/mediatr-pattern-unit-testing,"['c#', '.net-core-3.1', 'fakeiteasy', 'mediatr']",470,False,0,1
How do I properly mock Amplify for Unit Testing in Jasmine?,"<p>I'm quite new to Unit testing so bear with me</p>

<p>I'm trying to unit test a service that is used to log the user with Amplify in an Angular application.</p>

<p>Right now in the spec file I'm doing:</p>

<pre><code> beforeEach(async () =&gt; {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
            ],
            providers: [
                MyService, Amplify
            ]
        }
      myService = TestBed.get(MyService)
      amplify = TestBed.get(Amplify)
    })

   it('should login', async () =&gt; {
      const objToBeReturned = { signInUserSession: { idToken: { jwtToken: 'tokenValue' } } }
      spyOn(Amplify.Auth, 'signIn').and.returnValue(objToBeReturned)

      await myService.login('username', 'password')
   })

</code></pre>

<p>While in <em>MyService</em> :</p>

<pre><code>  public async login(username: string, password: string) {
    const authUser = await Amplify.Auth.signIn(username.toLowerCase(), password)
    if (authUser.signInUserSession != null) {
      const idToken = authUser.signInUserSession.idToken.jwtToken
      return this.patientLogin(idToken)
    }
   }

  private async patientLogin(idToken?: string): Promise&lt;boolean&gt; {
    await this.sendRequest&lt;LoginResponse&gt;(url, data).pipe(
      tap(response =&gt; {
        if (!isLoginResponse(response)) {
          throw throwErr({ code: 'Generic' })
        }
        this.token = response.token
      })
    ).toPromise()
    return true
  }

</code></pre>

<p>This gives me the error <strong>Async function did not complete within 5000ms</strong></p>

<p>I'm pretty sure it depends on the way I'm mocking Amplify</p>

<p>How do i properly mock it?</p>
",https://stackoverflow.com/questions/60454057/how-do-i-properly-mock-amplify-for-unit-testing-in-jasmine,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1132,True,0,2
Unit testing for service in Angular,"<p>I am trying to create unit testing for service I have import data service in spec file.</p>
<p>Then I am calling  in beforeach Method.</p>
<pre><code> providers: [
    { provide: dataservice}    
  ],
</code></pre>
<p>I am getting this error</p>
<pre><code>TypeError: Cannot read property 'setNumber' of undefined

this.dataService.setNumber(null);
</code></pre>
<p>As per the below user I added</p>
<pre><code>const spyDataService = jasmine.createSpyObj('DataService', ['setNumber '])
</code></pre>
<p>in before each</p>
<p>How to get rid of this error I am trying like below i am getting error and i modifed this into</p>
<pre><code>  it('should be create data service', () =&gt; {    
     expect(DataService).setNumber;
    });

  it('should be create data service', () =&gt; {
    expect(service.setBCNumber).toHaveBeenCalledWith(null);
  }); 
</code></pre>
<p>but still I am getting the same error.</p>
",https://stackoverflow.com/questions/63924847/unit-testing-for-service-in-angular,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",102,False,0,1
Angular 7 Unit testing - PhantomJS has crashed,"<p>I am using Angular 7 for unit testing using karma and phantom JS. While I have run from my local machine, from my MAC --</p>

<pre><code>ng test --watch=false
</code></pre>

<p>Local Machine Output -</p>

<pre><code>ng test
10% building modules 2/2 modules 0 active18 01 2020 14:54:57.990:WARN [karma]: No captured browser, open http://localhost:9876/
18 01 2020 14:54:57.995:INFO [karma-server]: Karma v3.1.4 server started at http://0.0.0.0:9876/
18 01 2020 14:54:57.997:INFO [launcher]: Launching browsers PhantomJS with concurrency unlimited
18 01 2020 14:54:58.011:INFO [launcher]: Starting browser PhantomJS
 10% building modules 5/7 modules 2 active ..._weather_forcast_testing/src/styles.cssBrowserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`
18 01 2020 14:55:05.820:WARN [karma]: No captured browser, open http://localhost:9876/    
18 01 2020 14:55:06.004:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket i77IuK4nefa0HrxhAAAA with id 31463905
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 6 of 6 SUCCESS (1.598 secs / 1.535 secs)
TOTAL: 6 SUCCESS
TOTAL: 6 SUCCESS
</code></pre>

<p>It's working fine. MAC Configuration - </p>

<pre><code>Angular CLI: 7.3.7
Node: 8.9.4
OS: darwin x64
Angular: 7.2.11
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.11.4
@angular-devkit/build-angular     0.11.4
@angular-devkit/build-optimizer   0.11.4
@angular-devkit/build-webpack     0.11.4
@angular-devkit/core              7.1.4
@angular-devkit/schematics        7.3.7
@angular/cdk                      7.3.6
@angular/cli                      7.3.7
@angular/flex-layout              7.0.0-beta.22
@angular/material                 7.3.6
@ngtools/webpack                  7.1.4
@schematics/angular               7.3.7
@schematics/update                0.13.7
rxjs                              6.4.0
typescript                        3.2.2
webpack                           4.23.1
</code></pre>

<p>I deployed the same code in AWS EC2 - Ubuntu 18.04, Try to run the same command - </p>

<pre><code>ng test --watch=false
</code></pre>

<p>Ubuntu machine Output -</p>

<pre><code>ng test
10% building modules 2/2 modules 0 active18 01 2020 09:22:29.639:WARN [karma]: No captured browser, open http://localhost:9876/
    18 01 2020 09:22:29.710:INFO [karma-server]: Karma v3.1.4 server started at http://0.0.0.0:9876/
    18 01 2020 09:22:29.710:INFO [launcher]: Launching browsers PhantomJS with concurrency unlimited
    18 01 2020 09:22:29.831:INFO [launcher]: Starting browser PhantomJS
     10% building modules 7/10 modules 3 active ..._weather_forcast_testing/src/styles.cssBrowserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`
     52% building modules 354/354 modules 0 active18 01 2020 09:23:29.869:WARN [launcher]: PhantomJS have not captured in 60000 ms, killing.
     56% building modules 390/390 modules 0 active18 01 2020 09:23:34.149:INFO [launcher]: Trying to start PhantomJS again (1/2).
     95% emitting CopyPlugin                                                                  

    18 01 2020 09:24:54.635:WARN [launcher]: PhantomJS have not captured in 60000 ms, killing.
    18 01 2020 09:25:24.043:WARN [karma]: No captured browser, open http://localhost:9876/
    18 01 2020 09:25:24.793:INFO [launcher]: Trying to start PhantomJS again (2/2).
    18 01 2020 09:25:25.515:ERROR [karma-server]: { Error: spawn ENOMEM

    Cannot read property 'success' of undefined
    TypeError: Cannot read property 'success' of undefined
        at TestCommand.runSingleTarget (/home/ubuntu/youtube_angular7__weather_forcast_testing/node_modules/@angular/cli/models/packages/angular/cli/models/architect-command.ts:242:21)
        at &lt;anonymous&gt;
        at Immediate._tickCallback (internal/process/next_tick.js:189:7)
        at runCallback (timers.js:810:20)
        at tryOnImmediate (timers.js:768:5)
        at processImmediate [as _immediateCallback] (timers.js:745:5)
</code></pre>

<p>Ubuntu Machine Configuration -</p>

<pre><code>Angular CLI: 7.3.7
Node: 8.17.0
OS: linux x64
Angular: 7.2.11
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.11.4
@angular-devkit/build-angular     0.11.4
@angular-devkit/build-optimizer   0.11.4
@angular-devkit/build-webpack     0.11.4
@angular-devkit/core              7.1.4
@angular-devkit/schematics        7.3.7
@angular/cdk                      7.3.6
@angular/cli                      7.3.7
@angular/flex-layout              7.0.0-beta.22
@angular/material                 7.3.6
@ngtools/webpack                  7.1.4
@schematics/angular               7.3.7
@schematics/update                0.13.7
rxjs                              6.4.0
typescript                        3.2.2
webpack                           4.23.1
</code></pre>

<p>Why the same code and same configuration is working fine in MAC and not working in Ubuntu ?</p>
",https://stackoverflow.com/questions/59799226/angular-7-unit-testing-phantomjs-has-crashed,"['phantomjs', 'angular7', 'karma-jasmine', 'angular-test']",470,False,-1,1
@PostConstruct not running within Spring test,"<p>I have a <code>Service</code> class with a <code>@PostConstruct</code> method that should init a param.</p>
<p>Then a regular method is using this param. Even though in a regular run this works as expected, during the unit testing the <code>@PostConstruct</code> is skipped and the param is not initialized.</p>
<p>I guess this is something really stupid:</p>
<pre><code>@Service
public class MyService {

private String s;

@PostConstruct
public void init(){
    s = &quot;a&quot;;
}

public String append(String a){
    return s+ a;
}
}
</code></pre>
<p>Test class:</p>
<pre><code>import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)  //  &lt;------- tried with and without
public class MyServiceTest {

@Test
public void testXYZ(){
    Assertions.assertThat(new MyService().append(&quot;b&quot;)).isEqualTo(&quot;ab&quot;);
}

}
</code></pre>
<p>Run results (when running from IntelliJ - right click and run test, or when running via console of <code>gradle test</code>):</p>
<pre><code>org.opentest4j.AssertionFailedError: 
Expecting:
   &lt;&quot;nullb&quot;&gt;
to be equal to:
   &lt;&quot;ab&quot;&gt;
but was not.
Expected :&quot;ab&quot;
Actual   :&quot;nullb&quot;
</code></pre>
",https://stackoverflow.com/questions/65201868/postconstruct-not-running-within-spring-test,"['java', 'spring', 'unit-testing', 'spring-test']",1636,True,0,1
How do you testrun your c++/Qt programs/projects with template classes? (Automated unit testing in 2020),"<p>I was confronted with a Think-Cell development position test in which a big part - if not the most important part - was testing the final version of the program one has written that contained a template class. So lots of testing is possible.</p>

<p>In my experience from open source projects the bare minimum is tested to make the program run&amp;done and solve bugs by ""creative users"" that do stuff programmers wouldn't ever come up with. </p>

<p>In the books I red and I learned from was just some minimal input IO handling for int/char/strings but nothing explicitly about testing the program with all/the most possible use cases.</p>

<p>But I really like the idea of writing a test program that covers all events/possible use cases especially a commercial use case and I can Imagine writing one general testing library that fires all kinds of data on the program that covers as much as possible would be handy wouldn't it?</p>

<p>And yes, I already googled and found some <a href=""https://stackoverflow.com/search?q=Unit%20testing%20c%2B%2B"">unit testing posts from '08 '10</a> also <a href=""https://stackoverflow.com/questions/1524390/what-unit-testing-framework-should-i-use-for-qt"">qt unit testing</a>
or <a href=""http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle"" rel=""nofollow noreferrer"">'04</a> and after that <a href=""https://www.youtube.com/watch?v=16FI1-d2P4E"" rel=""nofollow noreferrer"">google test</a> seem to dominate the market but even there one has to come up with all the different test cases that really takes time f.e in case of template classes.
Also the Qt toolkit already has a <a href=""https://doc.qt.io/qt-5/qttestlib-tutorial1-example.html"" rel=""nofollow noreferrer"">Qt unit testing library</a></p>

<p><strong><em>So my question is: How do you / What do you use or do to test your projects/programs in 2020? Do I have to write/come up with my own testing methods/classes redundant for every program/project every time new?
Isn't there already a way to automate the testing in a way errors/warnings are showing up f.e. in the qt creator during the programming process?</em></strong></p>
",https://stackoverflow.com/questions/62157664/how-do-you-testrun-your-c-qt-programs-projects-with-template-classes-automat,"['c++', 'qt', 'unit-testing']",56,False,0,0
Mocking static method in Java,"<p>Is there way to mock for unit test static method in Java without executing the method actual implementation? Actual implementation launches the process that cannot be done in unit test context. </p>

<pre><code>
public class MyExecutor {

    public static int execute(...) {
        Process pr = Runtime.getRuntime().exec(...)
        int status = pr.waitFor();
        return status;
    }


public MyClass {

    public void methodToUnitTest(...){

        MyExecutor.execute(...)

    }

</code></pre>

<p>I want to mock MyExecutor.execute and verify both its invocation and its params when unit testing MyClass.methodToUnitTest but without actual execution of this method.</p>

<p>I read that PowerMockito can mock static method but it does not prevent actual implementation from being  executed.</p>
",https://stackoverflow.com/questions/60589283/mocking-static-method-in-java,"['java', 'unit-testing']",214,False,2,1
Local module import works fine with ipython but fails with python,"<p>I have a package <code>my_package/</code> which contains two modules <code>module1.py</code> and <code>module2.py</code>, where <code>module2.py</code> contains:</p>
<pre><code>import sys
print(sys.path)  # for troubleshooting

from my_package import module1
</code></pre>
<p>Running:</p>
<pre><code>python -c &quot;from my_package import module2&quot;
</code></pre>
<p>from the parent directory works fine. However I would also like to be able to run <code>module2.py</code> for unit testing. Running:</p>
<pre><code>ipython my_package/module2.py
</code></pre>
<p>also works fine. However trying to run with python:</p>
<pre><code>python my_package/module2.py
</code></pre>
<p>fails (<code>ModuleNotFoundError: No module named 'my_package'</code>). In both cases, <code>/home/user/my_project/my_package</code> appears in sys.path. My versions of python and ipython are the same (3.7.4). Adding <code>__init__.py</code> in <code>my_package/</code> did not help.</p>
<p>Why does this happen, and how do I solve this issue?</p>
",https://stackoverflow.com/questions/62559861/local-module-import-works-fine-with-ipython-but-fails-with-python,"['python', 'ipython', 'python-import']",48,False,2,0
Correcty parameterized test class fails in JUnit 5,"<p>I have problem about unit testing using JUnit 5,
namely when I run test method with parameterized annotation it fails but everything is correct, I think. it is JUnit 5 code:</p>
<pre><code>@Test
@ParameterizedTest
@MethodSource(&quot;data&quot;)
public void test(int e){
    System.out.println(&quot;e = &quot; + e);
}

private static Stream data(){
    return Stream.of(
        Arguments.of(1),
        Arguments.of(2)
    );
}
</code></pre>
<p>and it fails:
<a href=""https://i.stack.imgur.com/5dDD0.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5dDD0.jpg"" alt=""enter image description here"" /></a></p>
<p>, I have tried custom parameterize resolver but there comes up another error: it does not return passed value from data() function, but returns default value what is defined in resolveParameter() function in CustomParameterResolver class. How to solve this problem ?</p>
",https://stackoverflow.com/questions/64712366/correcty-parameterized-test-class-fails-in-junit-5,"['junit', 'junit5']",713,True,1,1
HttpClient in a loop,"<p>I am using Apache HttpClient to invoke an API inside a batch (STANDALONE) JAVA program.
Below is the code</p>

<pre class=""lang-java prettyprint-override""><code>HttpClient httpClient = new HttpClient();
httpClient.getParams().setIntParameter(""http.connection.timeout"",5000);
PostMethod postMethod = new PostMethod(""http://localhost:8080/endpoint"");

for (String strRequest:listA) {
    postMethod.setRequestEntity(new StringRequestEntity(strRequest,""application/json"",""UTF-8""));
    postMethod.addRequestHeader(""Content-Type"",""application/json"");
    postMethod.addRequestHeader(""Accept"",""application/json"");
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode !=200) {
        responseBodyStr = postMethod.getResponseBodyAsString();
    } else {
        responseBodyStr = postMethod.getResponseBodyAsString();
    }
    System.out.println(responseBodyStr);
}
</code></pre>

<p>On the second iteration, I get a 400 (Socket timeout) error.
Is there any way to reset the <code>httpClient</code> here, so I can reuse the same object. It will also help with my unit testing. This is the simplified version of the code. Actual code has lot of processing based on the response received from the API.</p>
",https://stackoverflow.com/questions/59633072/httpclient-in-a-loop,"['java', 'apache-commons-httpclient']",969,False,1,1
HttpClient in a loop,"<p>I am using Apache HttpClient to invoke an API inside a batch (STANDALONE) JAVA program.
Below is the code</p>

<pre class=""lang-java prettyprint-override""><code>HttpClient httpClient = new HttpClient();
httpClient.getParams().setIntParameter(""http.connection.timeout"",5000);
PostMethod postMethod = new PostMethod(""http://localhost:8080/endpoint"");

for (String strRequest:listA) {
    postMethod.setRequestEntity(new StringRequestEntity(strRequest,""application/json"",""UTF-8""));
    postMethod.addRequestHeader(""Content-Type"",""application/json"");
    postMethod.addRequestHeader(""Accept"",""application/json"");
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode !=200) {
        responseBodyStr = postMethod.getResponseBodyAsString();
    } else {
        responseBodyStr = postMethod.getResponseBodyAsString();
    }
    System.out.println(responseBodyStr);
}
</code></pre>

<p>On the second iteration, I get a 400 (Socket timeout) error.
Is there any way to reset the <code>httpClient</code> here, so I can reuse the same object. It will also help with my unit testing. This is the simplified version of the code. Actual code has lot of processing based on the response received from the API.</p>
",https://stackoverflow.com/questions/59633072/httpclient-in-a-loop,"['java', 'apache-commons-httpclient']",969,False,1,1
How do you know if loop or double loop is used in a function when unit testing?,"<p>I am new to unit testing, and would like to check if any line of code to contain double loop specifically.</p>
<p>I am currently studying at bootcamp and they somehow check if my solution contains specific loop (like while loop) or if I used nested loop as below.</p>
<pre><code>Test Code
function () {
    expect(DOUBLE_LOOP_EXP.test(funcBody)).to.be.equal(true);
  } 
</code></pre>
<p>To clarify, below is my function that's been tested through above criterion;</p>
<pre><code>function makePermutations(str) {
  let result = '';
  for (let i = 0; i &lt; str.length; i++) {
    for (let j = 0; j &lt; str.length; j++) {
      result += str[i] + str[j] + ',';
    }
  }
  return result.slice(0, result.length - 1);
}
module.exports = makePermutations;

</code></pre>
<p>Unfortunately, there's no way to know whats inside that DOUBLE_LOOP_EXP.test.
Please advise.</p>
",https://stackoverflow.com/questions/63866289/how-do-you-know-if-loop-or-double-loop-is-used-in-a-function-when-unit-testing,"['javascript', 'unit-testing', 'testing', 'jestjs']",108,True,1,1
Getting issue as &quot;SyntaxError: Unexpected token { in JSON at position 40&quot; in while unit testing using mocha and chai,"<p>I am new to unit testing using Mocha and Chai. I am getting issue when I am testing my Rest API using  Mocha and Chai.</p>

<p>test.js </p>

<pre><code>let  chaiHttp = require('chai-http');
let chai = require('chai');
let should = chai.should ();
let expect = chai.expect;
let server = require('../app');
chai.use(chaiHttp)

describe(""Put /api/approvedUser/:id"",() =&gt; {
  it('it should Put the tasks ', (done) =&gt; {
                 const userid = 'farmer.Ak';
                  var userdata = {
                    ROLEID: 1,
                    approved: true 
                   }

                chai.request(server)
                    .put(""/approvedUser/"" + userid)
                    .send(userdata)
                    .end((err, res) =&gt; {
                        const body = res.body;
                        console.log(body);
                        res.should.have.httpstatus(200);                        
                        // res.body.should.be.a('object');
                         res.body.should.be.property('secret');
                        // res.body.should.be.property('ROLEID');
                        // res.body.should.be.property('approved');
                        // res.body.should.be.property('id').eq('dfarm1');
                         done();                  
                    })
                  .catch((err) =&gt; done(err));  
            });
        });     
</code></pre>

<p>API Response </p>

<pre><code> responseSuccessfully registered admin user pc and imported it into the wallet {""secret"":""KwCqRJIIwjKx"",""data"":{""type"":""X509"",""mspId"":""org1MSP"",""certificate"":""-----BEGIN CERTIFICATE-----\nMIICdDCCAhugAwIBAgIUPy8fI7Ul5x4tFKKZTRnthgAYnBgwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMjA2MTMzNTAwWhcNMjEwMjA1MTM0\nMDAwWjAeMQ8wDQYDVQQLEwZjbGllbnQxCzAJBgNVBAMTAnBjMFkwEwYHKoZIzj0C\nAQYIKoZIzj0DAQcDQgAEZi/vji38zbn8tvNVwWY+TaolA6oD5pG3braBh7TOhtVP\nLZsWlP07baSAa0aXnpyz0JDFYeggrY2xoTGg5jXKoaOB4TCB3jAOBgNVHQ8BAf8E\nBAMCB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUXcPkIg5WC2o0nI//LCNeeybk\n2fcwKwYDVR0jBCQwIoAgQNPu+NJFQ7FeXcKiC8WYjVl2gJGm6wZolSTDojNtmNIw\ncgYIKgMEBQYHCAEEZnsiYXR0cnMiOnsiYXBwcm9sZSI6InByb2Nlc3NpbmdDZW50\nZXIiLCJoZi5BZmZpbGlhdGlvbiI6IiIsImhmLkVucm9sbG1lbnRJRCI6InBjIiwi\naGYuVHlwZSI6ImNsaWVudCJ9fTAKBggqhkjOPQQDAgNHADBEAiAVUtW3FCy0rQUq\nbBCVEwMVkl7jw8KvSK1TDhDykRIj6wIgYrl8/s9+TtO9blZSCERMznC6fdQBmXC+\nLHEkr+tge6o=\n-----END CERTIFICATE-----\n"",""privateKey"":""-----BEGIN PRIVATE KEY-----\r\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgbuamIkkqqxjZtIey\r\nn35VYSc8RTaITfVBGY0AflPJp8ShRANCAARmL++OLfzNufy281XBZj5NqiUDqgPm\r\nkbdutoGHtM6G1U8tmxaU/TttpIBrRpeenLPQkMVh6CCtjbGhMaDmNcqh\r\n-----END PRIVATE KEY-----\r\n""},""httpstatus"":200}   
</code></pre>

<p>In above code I am trying to test the put method and sending some userdata which is in json, but I am getting error as "" </p>

<blockquote>
  <p>""SyntaxError: Unexpected token { in JSON at position 40"" 
  please suggest how can I fix this issue??</p>
</blockquote>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/60096553/getting-issue-as-syntaxerror-unexpected-token-in-json-at-position-40-in-whi,"['node.js', 'unit-testing', 'mocha.js', 'chai']",288,False,1,1
Cannot find module &#39;firebase-admin&#39; from &#39;index.cjs.js&#39;,"<p>I was using <code>@firebase/testing</code> on Jest, but since <a href=""https://www.npmjs.com/package/@firebase/testing"" rel=""nofollow noreferrer"">it's deprecated and instructed to use new one</a>, I decided to move to <code>@firebase/rules-unit-testing</code>.</p>
<p>Here is the code where I just switched them.</p>
<pre class=""lang-js prettyprint-override""><code>import { initializeAdminApp } from &quot;@firebase/rules-unit-testing&quot;;
import &quot;babel-polyfill&quot;;

it(&quot;is ok&quot;, async () =&gt; {
  const admin = initializeAdminApp({ projectId: &quot;my-project&quot; });

  try {
    const doc = admin.firestore().collection(&quot;items&quot;).doc(&quot;item-1&quot;);
    await doc.set({ name: &quot;Item 1&quot; });
    const ss = await doc.get();
    expect(ss.data()?.name).toBe(&quot;Item 1&quot;);
  } finally {
    await admin.delete();
  }
});
</code></pre>
<p>When I run this test with emu, it results &quot;Cannot find module 'firebase-admin' from 'index.cjs.js'&quot; error.</p>
<pre><code>Cannot find module 'firebase-admin' from 'index.cjs.js'                      
                                                                                              
      3 |                                       
      4 | it(&quot;is ok&quot;, async () =&gt; {                                                              
    &gt; 5 |   const admin = initializeAdminApp({ projectId: &quot;my-project&quot; });                           
        |                 ^
</code></pre>
<p>It passes if it is the old <code>@firebase/testing</code>.</p>
<p>What did I miss?</p>
<ul>
<li>Node.js v14.8.0</li>
<li>Jest 25.5.4</li>
<li>firebase 7.21.1</li>
<li>firebase-tools 8.11.2</li>
<li>@firebase/testing 0.20.11</li>
<li>@firebase/rules-unit-testing 1.0.4</li>
</ul>
",https://stackoverflow.com/questions/64083363/cannot-find-module-firebase-admin-from-index-cjs-js,"['firebase', 'testing']",1605,True,1,2
Mocking builders in JUnit test,"<p>Let's say if I have a test that uses builders to construct objects. The problem is that the builder() method in the builder class is static.</p>

<p>Generally, mocking a static method is already an indicator of bad design. However, in the case of builders, the builder() methods are always static. What's the best approach to unit testing methods using builders()? Should the builders be refactored into a separate class to facilitate mocking?  </p>

<pre><code>class Service {

    private SqsClient sqsClient;
    private String sqsQueueUrl;

    public Service(String sqsQueueUrl) {
        this.sqsClient = SqsClient.builder().build();
        this.sqsQueueUrl = sqsQueueUrl;
    }

    public SqsClient getClient() {
        return this.client;
    }
    public SqsClient setClient(SqsClient client) {
        this.client = client;
    }

    public String getSqsQueueUrl() {
        return this.sqsQueueUrl;
    }
    public void setSqsQueueUrl(String sqsQueueUrl) {
        this.sqsQueueUrl = sqsQueueUrl;
    }

    public void onEvent(Activity activity) {
        // How to mock builders in unit test?
        DeleteMessageRequest deleteRequest = DeleteMessageRequest.builder().queueUrl(this.sqsQueueUrl).receiptHandle(activity.getReceiptHandle()).build();
        DeleteMessageResponse deleteMessageResponse = this.sqsClient.deleteMessage(deleteRequest);
    }
}


class ServiceTest {
    @Test
    public void testEvent() {

        String sqsQueueUrl = ""http://127.0.0.1"";
        String receiptHandle = ""asdasd"";

        SqsClient sqsClient = EasyMock.mock(SqsClient.class);
        Service service = EasyMock.mock(Service.class);

        // EasyMock expect and replay here.

        service.setClient(sqsClient);
        service.setSqsQueueUrl(sqsQueueUrl);

        Activity activity1 = new Activity();
        activity.setReceiptHandle(receiptHandle);

        service.onEvent(activity);      
    }
}
</code></pre>
",https://stackoverflow.com/questions/60069360/mocking-builders-in-junit-test,"['java', 'junit']",1921,False,1,0
Jest Enzyme Unit Test Not Working For Material UI React Component,"<pre><code>&lt;TextField
  id='firstNameInput'
  onChange={handleChange}
  value={newUser.firstName}
  variant='outlined'
  required
  fullWidth
  label='First Name'
  name='firstName'
/&gt;
</code></pre>
<p>This is the component I am trying to test.</p>
<pre><code>const handleChange = (e) =&gt; {
    const { name, value } = e.target;

    setNewUser((prevValue) =&gt; {
      return {
        ...prevValue,
        [name]: value,
      };
    });
  };
</code></pre>
<p>This is the function that onChange fires, which changes the newUser state, which is just an object of 5 properties, all of which are strings.</p>
<pre><code> it('Test register form first name input field', () =&gt; {
    const component = mount(&lt;RegisterForm /&gt;);

    const wrapper = component.find(TextField).at(0);
    const event = {
      target: { name: 'firstName', value: 'test' },
    };

    expect(wrapper.props().label).toBe('First Name');
    expect(wrapper.props().value).toBe('');

    wrapper.simulate('change', event);
    wrapper.update();

    expect(wrapper.props().value).toBe('test');
  });
</code></pre>
<p>This unit test is very basic obviously, I'm just trying to get off the ground with unit testing, but it doesn't seem to matter how many SO questions, Medium articles, etc. I read but I just can't get it to work.</p>
<p>I am aware that the wrapper needs to be updated, so I've taken care of that, simulate is being passed the appropriate event, I'm accessing the props to get at the label and value. The first two expect assertions pass, so it's finding the component and testing its initial value just fine, but the value is still an empty string after I fire change and it should be &quot;test&quot;.</p>
<p>I know the form is working just fine, I have tested it manually, so the issue is strictly with the unit test. Any idea why the value is not being updated? Apologies if this is a basic question...trying to get the hang of unit testing with React.</p>
",https://stackoverflow.com/questions/64190762/jest-enzyme-unit-test-not-working-for-material-ui-react-component,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",454,False,2,0
"ISetup&lt;IDurableOrchestrationContext, Task&lt;List&lt;string&gt;&gt; does not contain a definition for &#39;ReturnsAsync&#39;","<p>I am starting off with Durable Azure Functions(latest version) and it's unit testing(using x-unit). Below is my trigger function(http triggered):</p>

<pre><code>[FunctionName(""funcEventSubscriber"")]
public async Task&lt;HttpResponseMessage&gt; HttpStart(
    [HttpTrigger(AuthorizationLevel.Function, ""get"")] HttpRequestMessage req,
    [DurableClient] IDurableOrchestrationClient starter,
    ILogger log)
{
    try
    {
        string instanceId = await starter.StartNewAsync(""funcEventOrchestrator"", null);
        log.LogInformation($""Started orchestration with ID = '{instanceId}'."");
        return starter.CreateCheckStatusResponse(req, instanceId);
    }
    catch (System.Exception ex)
    {
        _telemetryHelper.LogException(ex);
        throw;
    }
}
</code></pre>

<p>And this one is my orchestrator function which kicks-off activity functions:</p>

<pre><code>[FunctionName(""funcEventOrchestrator"")]
public async Task&lt;List&lt;string&gt;&gt; RunOrchestrator(
    [OrchestrationTrigger] IDurableOrchestrationContext context)
{
    try
    {
        var outputs = new List&lt;string&gt;();
        var reusultSet = new List&lt;string&gt;();
        outputs = await context.CallActivityAsync&lt;List&lt;string&gt;&gt;(""funcActivityA"", """");
        foreach (var item in outputs)
        {
            var result = await context.CallActivityAsync&lt;List&lt;TableRegionEntity&gt;&gt;(""funcActivityB"", item);
            if (result.Count &gt; 0)
            {
                foreach (var data in result)
                {
                    List&lt;string&gt; inputObject = new List&lt;string&gt;();
                    inputObject.Add(data.Subscriber);
                    inputObject.Add(item);
                    reusultSet.Add(await context.CallActivityAsync&lt;string&gt;(""funcActivityC"", inputObject));
                }
            }
            else
            {
                reusultSet.Add(await context.CallActivityAsync&lt;string&gt;(""funcActivityD"", item));
            }
        }
        return reusultSet;
    }
    catch (System.Exception ex)
    {
        _telemetryHelper.LogException(ex);
        throw;
    }
}
</code></pre>

<p>The unit test method which I've written for my orchestrator function looks something like this:</p>

<pre><code>[Fact]
public async Task Run_returns_list_of_string()
{
    var mockContext = new Mock&lt;IDurableOrchestrationContext&gt;();
    mockContext.Setup(x =&gt; x.CallActivityAsync&lt;List&lt;string&gt;&gt;(""funcActivityA"", """")).ReturnsAsync(funcActivityAOutput);
    mockContext.Setup(x =&gt; x.CallActivityAsync&lt;List&lt;TableRegionEntity&gt;&gt;(""funcActivityB"", inputJsonString)).ReturnsAsync(funcActivityBOutput);
    mockContext.Setup(x =&gt; x.CallActivityAsync&lt;string&gt;(""funcActivityC"", funcActivityCInputObject)).ReturnsAsync(funcActivityCOutput);
    mockContext.Setup(x =&gt; x.CallActivityAsync&lt;string&gt;(""funcActivityD"", inputJsonString)).ReturnsAsync(funcActivityDOutput);

    // Instantiate funcEventSubscriber
    funcEventSubscriber funcEventSubscriberObj = new funcEventSubscriber(telemetryHelperMock.Object);

    // Act
    var result = await funcEventSubscriberObj.RunOrchestrator(mockContext.Object); // call orchestrator fn

    // Assert
    Assert.Equal(3, result.Count);
}
</code></pre>

<p>The way I'm setting up <code>mockContext</code> throws an error. This is the error from the first line of <code>mockContext.Setup</code> i.e </p>

<pre><code>mockContext.Setup(x =&gt; x.CallActivityAsync&lt;List&lt;string&gt;&gt;(""funcActivityA"", """")).ReturnsAsync(funcActivityAOutput);`
</code></pre>

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

<p>Where am I going wrong here?</p>
",https://stackoverflow.com/questions/60679549/isetupidurableorchestrationcontext-taskliststring-does-not-contain-a-defin,"['c#', 'unit-testing', 'azure-functions', 'moq', 'azure-durable-functions']",1856,True,1,1
"UnitTesing with Autofac, Moq - Getting Value cannot be null exception","<p>I'm using EF6. The generated code is something like:</p>
<pre><code>public partial class MyDataContext : DbContext,IMyDataContext 
{
    public MyDataContext() : base(&quot;name=mydata&quot;)
    {
    }

    public virtual DbSet&lt;getProjectsDraft&gt; getProjectsDrafts { get; set; }
}
</code></pre>
<p>and the dbcontext Interface is like below</p>
<pre><code>public interface IxmcmcDbContext: IDisposable
{
   DbSet&lt;getProjectsDraft&gt; getProjectsDrafts { get; set; }
}
</code></pre>
<p>I am using the Autofac for the DI and the registration is done at my global.asax.cs as below</p>
<pre><code>//Entity Registering
builder.RegisterType&lt;MyDataContext&gt;().As&lt;IMyDataContext&gt;();
</code></pre>
<p>All my DI is working fine but when I implemented unit testing using xUnity I am getting below error</p>
<p>Basetest Code:</p>
<pre><code>public class BaseTest
    {
        public static Mock&lt;DbSet&lt;T&gt;&gt; CreateDbSetMock&lt;T&gt;(IEnumerable&lt;T&gt; elements) where T : class
        {
            var elementsAsQueryable = elements.AsQueryable();
            var dbSetMock = new Mock&lt;DbSet&lt;T&gt;&gt;();
            dbSetMock.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Provider).Returns(elementsAsQueryable.Provider);
            dbSetMock.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Expression).Returns(elementsAsQueryable.Expression);
            dbSetMock.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(elementsAsQueryable.ElementType);
            dbSetMock.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(elementsAsQueryable.GetEnumerator());
            return dbSetMock;
        }
    }
</code></pre>
<p>and Project Test</p>
<pre><code>public class Projects_Test : BaseTest
    {
        [Fact]
        public void GetDraftProjectsList()
        {
            // Arrange
            var fixture = new Fixture();
            var draftProjects = new List&lt;getProjectsDraft&gt;
             {
                fixture.Create&lt;getProjectsDraft&gt;()
             };
            var draftMock = CreateDbSetMock(draftProjects);
            var myDataContextMock= new Mock&lt;IMyDataContext&gt;();
            myDataContextMock.Setup(x =&gt; x.getProjectsDrafts).Returns(draftMock.Object);
            var projectService = new ProjectRepo(mediciContextMock.Object);

            // Act
            var draftproject = projectService.GetDraftProjects(true, &quot;test-02&quot;, &quot;Test&quot;);

            // Assert
            Assert.NotNull(draftproject);
        }
    }
</code></pre>
<p>However, I get the <code>&quot;Value cannot be null.\r\nParameter name: source&quot;</code> error on the //Act draftproject.</p>
<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/60707530/unittesing-with-autofac-moq-getting-value-cannot-be-null-exception,"['c#', 'entity-framework', 'unit-testing', 'moq', 'autofac']",2118,True,1,1
How to test my API Controller that accepts Protobuf as request body,"<p>I have a controller that accepts a protobufs as the body. Now, I want to test the functionality(not unit testing) of my controller against a dummy .net console application. I am not able to figure out, how to go about it.</p>
<p>The code is as follows:</p>
<pre><code>public async Task&lt;IActionResult&gt; GetData([FromBody] Request request)
    {
        Response response = new Response();

        if (request == null) {
            return BadRequest(&quot;Request is null&quot;);
        }

        //Do Something.
        return Ok(response);
    }
</code></pre>
<p>I also have a Custom input formatter:</p>
<pre><code>public class CustomInputFormatter : InputFormatter
{
    public string ContentType { get; } = &quot;application/protobuf&quot;;

    public override bool CanRead(InputFormatterContext context)
    {
        var requestContentType = context.HttpContext.Request.ContentType;
        if (string.IsNullOrEmpty(requestContentType))
        {
            context.HttpContext.Request.ContentType = ContentType;
            return true;
        }
        else if (requestContentType.Contains(ContentType, System.StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        return false;
    }

    public override async Task&lt;InputFormatterResult&gt; ReadRequestBodyAsync(InputFormatterContext context)
    {
        var request = context.HttpContext.Request;

        if (request.ContentLength == 0)
        {
            return InputFormatterResult.Failure();
        }

        using (var ms = new MemoryStream())
        {
            await request.Body.CopyToAsync(ms).ConfigureAwait(false);

            try
            {
                var req= Request.Parser.ParseFrom(ms.ToArray());
                return InputFormatterResult.Success(ms.ToArray());
            }
            catch (InvalidProtocolBufferException)
            {
                return InputFormatterResult.Failure();
            }
        }
    }
}
</code></pre>
<p>How can I test the functionality of this Controller? The server is running at <code>https://localhost:8443/api/uriEndpoint</code></p>
<p>Any pointers? Thanks in advance.</p>
",https://stackoverflow.com/questions/63952979/how-to-test-my-api-controller-that-accepts-protobuf-as-request-body,"['.net', 'protocol-buffers']",513,True,1,1
How to mock or setup current_user in sinatra using Pundit for unit testing?,"<p>In my <code>app.rb</code> file i have the following setup for <code>current_user</code></p>

<pre><code>class Application &lt; Sinatra::Base
    include Pundit
    use JWTAuthorization    
    def current_user
        env[:user]
    end

    delete '/users/:user_id' do
      user = User.find(params[:user_id])
      no_data! unless user

      authorize user, :edit?
      user.destroy
      response = {status: 200, data:'success, user deleted.'}
      json response
    end
end
</code></pre>

<p>The problem is I need to setup the <code>current_user</code> for my unit testing. Otherwise the test will throw an error inside <code>authorize user, :edit?</code> or any other <code>Pundit</code> authorization code because <code>current_user</code> will return <code>nill</code>. 
How can I setup <code>env[:user]</code> inside my spec?</p>

<p>Is there a way i can mock <code>env[:user]</code> with a value using rspec or use <code>rack_env={}</code> to setup?</p>

<p>This is what i tried so far in my spec file without success:</p>

<pre><code>  before(:each) do
    @user = User.create(name: 'Oswaldinho',email: 'waldinho@com.com',role: 'user')
  end

  it 'deletes an existing user ' do
      delete ""/users/#{@user.id}"", params={}, rack_env={user: @user}
      expect(last_response).to be_ok
  end 
</code></pre>
",https://stackoverflow.com/questions/60664653/how-to-mock-or-setup-current-user-in-sinatra-using-pundit-for-unit-testing,"['ruby', 'rspec', 'sinatra', 'rack', 'pundit']",248,False,1,0
How should I test this method with JUNIT and Mockito,"<p>I'm new to Junit and Mockito unit testing. I need to unit test the method &quot;processFiles(final File folder)&quot;</p>
<p>When I run the test I get a NullPointerException at &quot;if (!this.studentService.isFileOk(data))&quot;.</p>
<p>Can you help me to how I should be testing this method properly. Thanks a lot in advance.</p>
<p>This is a part of the code from the processFiles method:</p>
<pre><code>@Stateless
public class ListFilesService{
 
  @EJB
  private transient StudentService studentService;
 
 public void processFiles(final File folder)
    {
        File[] fileNames = folder.listFiles();
        List&lt;String&gt; lines = new ArrayList&lt;&gt;();
        
        try
        {
                    List&lt;String&gt; l = readContent(file);
                    l.forEach(i -&gt; lines.add(i));

            String[] data = lines.get(0).trim().split(&quot;;&quot;);
            if (!this.studentService.isFileOk(data))
            {
                LOG.warning(String.format(&quot;File not valid&quot;));
            }
            else
            {
                studentService.storeStudents(lines);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
</code></pre>
<p>And this is how I'm trying to test my processFile method</p>
<pre><code> 

public class TestCases
{
 
 
    @Mock
    ListFilesService listFilesService;
    
    @Mock
    public StudentService studentService;

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();
 
 
 @Test
    public void testWrite2() throws IOException
    {

        final File tempFile1 = temporaryFolder.newFile(&quot;tempFile.txt&quot;);
        final File tempFile2 = temporaryFolder.newFile(&quot;tempFile2.txt&quot;);

        String[] data = {&quot;LastName&quot;, &quot;FirstName&quot;, &quot;Age&quot;};


        listFilesService = new ListFilesService();
        studentService = Mockito.mock(StudentService.class);
        when(studentService.isFileOk(eq(data))).thenReturn(true);


        FileUtils.writeStringToFile(tempFile1, &quot;LastName;FirstName;Age&quot; +
                &quot;\nxxx1;nnnn1;15&quot;, &quot;UTF-8&quot;);
        FileUtils.writeStringToFile(tempFile2, &quot;LastName;FirstName;Age&quot; +
                &quot;\nxxx2;nnnn2;19&quot;, &quot;UTF-8&quot;);


        listFilesService.processFiles(temporaryFolder.getRoot());

    }
</code></pre>
",https://stackoverflow.com/questions/63243937/how-should-i-test-this-method-with-junit-and-mockito,"['java', 'junit', 'mocking', 'mockito', 'junit4']",302,True,1,1
How to migrate postcss.plugin to postCSS 8 format,"<p>I'm trying to migrate old postCSS plugin to a new version to get unit tests to succeed. My index.js looks like this:</p>
<pre class=""lang-js prettyprint-override""><code>const postcss = require('postcss')

const params = require('./lib/params')
const formatAtRules = require('./lib/formatAtRules')
const formatOrder = require('./lib/formatOrder')
const formatRules = require('./lib/formatRules')
const formatComments = require('./lib/formatComments')
const formatSassVariables = require('./lib/formatSassVariables')

const stylefmt = postcss.plugin('stylefmt', function (options) {
  var paramer = params(options)
  return function (root, result) {
    return paramer(root, result).then(function (params) {
      if(params) {
        formatComments(root, params)
        formatAtRules(root, params)
        formatRules(root, params)
        formatSassVariables(root, params)
        // order should be the last to prevent empty line collapse in order rules
        formatOrder(root, params)
      }
    }).catch(function (err) {
      console.error(err.stack)
    })
  }
})

module.exports = stylefmt
</code></pre>
<p>This throws errors like this in console when running <code>tape test/*.js |faucet</code>:</p>
<pre class=""lang-sh prettyprint-override""><code>Error: postcss.plugin was deprecated. Migration guide: https://evilmartians.com/chronicles/postcss-8-plugin-migration 
    ---
      operator: error
      at: &lt;anonymous&gt; (/Users/rolle/Projects/stylefmt/test/cli.js:11:9)
      stack: |-
        Error: postcss.plugin was deprecated. Migration guide:
        https://evilmartians.com/chronicles/postcss-8-plugin-migration
        
            at ChildProcess.&lt;anonymous&gt; (/Users/rolle/Projects/stylefmt/test/cli.js:151:16)
            at ChildProcess.emit (events.js:198:13)
            at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
    ...
</code></pre>
<p>I'm kinda new to postCSS plugins and unit testing in JavaScript side. I have tried using <a href=""https://evilmartians.com/chronicles/postcss-8-plugin-migration"" rel=""nofollow noreferrer"">migration guide</a> with no avail. So, how to convert this piece to postCSS 8 format so the tests would pass? Here's my repo: <a href=""https://github.com/ronilaukkarinen/stylefmt"" rel=""nofollow noreferrer"">https://github.com/ronilaukkarinen/stylefmt</a></p>
",https://stackoverflow.com/questions/64439750/how-to-migrate-postcss-plugin-to-postcss-8-format,"['javascript', 'testing', 'postcss']",3776,True,1,1
this.mobilityService.currentMessage.subscribe is not a function in angular unit testing,"<p>In karma unit testing I'm getting this.mobilityService.currentMessage.subscribe is not a function error</p>

<p>below is the .ts file where I'm trying to get the values from another component through service</p>

<pre><code>  constructor(private projectService: ProjectService, private teamService: TeamserviceService) {this.getData()}

getData(){
this.projectService.currentMessage.subscribe(data =&gt; {
  if(data!=null)
  {
    this.serviceName=data.service_object.serviceName;
    this.serviceId = data.service_object.id})
</code></pre>

<p>this is how my service code looks like -</p>

<pre><code>messageSource = new BehaviorSubject(null);
currentMessage = this.messageSource.asObservable();
getProjectList(messageSource: string[]) {
this.messageSource.next(messageSource);
}
 constructor(private http:HttpClient) {
 getAllProjectService(teamid,serviceid){
 return this.http.get(environment.TEST_AUTOMATION_ENDPOINT+'/api/projects-by-team-and-servicestore? 
teamId='+teamid+'&amp;serviceStoreId='+serviceid+'&amp;access_token='+this.decaccesstoken);
 }
 }
</code></pre>

<p>My .spec file I'm creating a spy object like this - </p>

<pre><code>  const mockProjectService= jasmine.createSpyObj('projectService', ['getAllProjectService','currentMessage']);
</code></pre>

<p>Since 'currentMessage' is not a method inside the service I get this error. Any idea how to subscribe to a variable inside of a service?</p>
",https://stackoverflow.com/questions/60393491/this-mobilityservice-currentmessage-subscribe-is-not-a-function-in-angular-unit,"['angular', 'unit-testing', 'jasmine', 'observable', 'karma-runner']",75,True,-1,1
Postman- Pass dynamic parameters to collection at run-time which is not part of response,"<p>I have created postman collection for unit testing of APIs.
I need to handle below scenario.</p>
<p>My second API generates OTP and sends it over email but its not part of response.
I want to pass that OTP in request body of 3rd API.</p>
<p>I am executing postman collection using Collection Runner.
Is there any way I can pause the execution and set this environment variable and then resume.
Or any other better option. Please suggest.</p>
",https://stackoverflow.com/questions/63345198/postman-pass-dynamic-parameters-to-collection-at-run-time-which-is-not-part-of,"['postman', 'web-api-testing', 'postman-collection-runner', 'postman-pre-request-script']",678,False,3,1
Problems with rendering a twig template on a phpunit test,"<p>I'm currently working on a project that uses &quot;twig&quot; for the first time, so I apologize if this is not very clear.</p>
<p>I have developed a custom function that embeds SVG icons on the twig templates, but for this particular project I am graded more for coverage and unit testing than anything else. Because of this I am trying to use phpunit to test if my function works as intended.</p>
<p>In order to do that I believe I must render an instance of the custom function on the test file, and then compare it with the raw SVG file on my directory. But I am having trouble using the render method. I believe because I don't have a twig environment available in the test.</p>
<p>I have looked for something similar here and I have found this previous question: &quot;https://stackoverflow.com/questions/17026405/twig-template-unit-testing?rq=1&quot;.
The answer to this question recommends using the following:</p>
<pre><code>$twig = self::$kernel-&gt;getContainer()-&gt;get('twig');
    $html = $twig-&gt;render('AppBundle::app/something.html.twig', ['content' =&gt; 'I am some variable value']);
    self::assertEquals($html, $response-&gt;getContent());
</code></pre>
<p>but when I run that I get the following error:</p>
<pre><code>Error: Access to undeclared static property: App\Tests\Templates\Icons\IconsExtensionTest::$kernel
</code></pre>
<p>How can I access the Kernel?</p>
<p>Here is my currently not working test file:</p>
<pre><code>&lt;?php

// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see &lt;http://www.gnu.org/licenses/&gt;.

/**
 * This file test the Macro that Embeds SVG icons.
 *
 * @package   Tests
 *
 * @author    Ângelo D. Moura &lt;up201303828@fe.up.pt&gt;
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

namespace App\Tests\Templates\Icons;

use App\Twig\IconsExtension;
use App\Kernel;
use DirectoryIterator;
use PHPUnit\Framework\TestCase;

class IconsExtensionTest extends TestCase
{
    public function testIconsExtension()
    {

        //Get all Icon files names from &quot;public/assets/icons&quot;
        $icon_file_names = [];
        foreach (new DirectoryIterator('public/assets/icons/') as $file) {
            if ($file-&gt;isDot()) {
                continue;
            }
            $icon_file_names[] = $file-&gt;getFilename();
        }

        //Check if every icon file as a &quot;.svg.twig&quot; extension
        foreach ($icon_file_names as $icon_file_name) {
            static::assertRegExp('#([a-zA-Z0-9\s_\\.\-\(\):])+(.svg.twig)$#', $icon_file_name);
        }



        //Check if the function gives a valid HTML with a class attribute equal to the one passed
        $twig = self::$kernel-&gt;getContainer()-&gt;get('twig');

        /*
        $icon_template_render = $twig-&gt;render('public/icons/logo.svg', ['iconClass' =&gt; 'icon icon-logo']);

        $iconsExtension= new IconsExtension();

        $iconsExtension_render = $iconsExtension-&gt;embedSvgIcon($twig, 'logo', 'logo');

        self::assertEquals($icon_template_render, $iconsExtension_render);

        // Next I need to verify that the $iconsExtension_render is a valid html code (maybe through regex)

        */
    }
}

</code></pre>
<p>Here is my custom function (if needed):</p>
<pre><code>&lt;?php

// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see &lt;http://www.gnu.org/licenses/&gt;.
// }}}

/**
 * GNU social Twig extensions
 *
 * @package   GNUsocial
 * @category  Twig
 *
 * @author    Ângelo D. Moura &lt;up201303828@fe.up.pt&gt;
 * @copyright 2020 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

namespace App\Twig;

use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class IconsExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('icon',
                [$this, 'embedSvgIcon'],
                ['needs_environment' =&gt; true]
            ),
        ];
    }

    /**
     * Renders the Svg Icon template and returns it.
     *
     * @param Environment $twig
     * @param string      $icon_name
     * @param string      $icon_css_class
     *
     * @return string
     *
     * @author Ângelo D. Moura &lt;up201303828@fe.up.pt&gt;
     */
    public function embedSvgIcon(Environment $twig, string $icon_name = '', string $icon_css_class = '')
    {
        try {
            return $twig-&gt;render('@public_path/assets/icons/' . $icon_name . '.svg.twig', ['iconClass' =&gt; $icon_css_class]);
        } catch (LoaderError $e) {
            //return an empty string (a missing icon is not that important of an error)
            return '';
        } catch (RuntimeError $e) {
            //return an empty string (a missing icon is not that important of an error)
            return '';
        } catch (SyntaxError $e) {
            //return an empty string (a missing icon is not that important of an error)
            return '';
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/64667213/problems-with-rendering-a-twig-template-on-a-phpunit-test,"['php', 'symfony', 'twig', 'phpunit']",1040,True,1,1
Use a static readonly field in constructor C#,"<p>Below is my class with a static readonly field :</p>

<pre><code>public class Stats
{
    public static readonly int MinPoints = 900;
    public static readonly int MaxPoints = 1500;

    public int Points { get; }

    private Stats()
    {
    }

    public Stats(int points) : this()
    {
        if (points &lt; Stats.MinPoints || points &gt; Stats.MaxPoints)
        {
            throw new InvalidOperationException();
        }

        Points = points;
    }
}
</code></pre>

<p>When compiling, I don't have any errors. But when I try to instanciate a <code>Stats</code> object, I'm getting a <code>TypeInitializationException</code>. When replacing <code>PlayerStatistics.MaxPoints</code> in the constructor with its proper value, the code works.</p>

<p>Here is the error I get when unit testing the constructor :</p>

<pre><code>Expected a &lt;System.InvalidOperationException&gt; to be thrown, but found &lt;System.TypeInitializationException&gt;: ""
""System.TypeInitializationException with message ""The type initializer for 'League.Domain.Player.Stats' threw an exception.""
     at League.Domain.Player.Stats..ctor(Int32 points) in C:\dev\repos\League\League.Domain\Player\Stats.cs:line 24
     at League.Tests.StatsSpecs.&lt;&gt;c__DisplayClass1_0.&lt;Create_stats_with_incorrect_points_should_throw_exception&gt;b__0() in C:\dev\repos\League\League.Tests\StatsSpecs.cs:line 36
     at FluentAssertions.Specialized.ActionAssertions.InvokeSubject()
     at FluentAssertions.Specialized.DelegateAssertions`1.InvokeSubjectWithInterception()
.
   at FluentAssertions.Execution.XUnit2TestFramework.Throw(String message)
   at FluentAssertions.Execution.TestFrameworkProvider.Throw(String message)
   at FluentAssertions.Execution.DefaultAssertionStrategy.HandleFailure(String message)
   at FluentAssertions.Execution.AssertionScope.FailWith(Func`1 failReasonFunc)
   at FluentAssertions.Execution.AssertionScope.FailWith(Func`1 failReasonFunc)
   at FluentAssertions.Execution.AssertionScope.FailWith(String message, Object[] args)
   at FluentAssertions.Specialized.DelegateAssertions`1.Throw[TException](Exception exception, String because, Object[] becauseArgs)
   at FluentAssertions.Specialized.DelegateAssertions`1.Throw[TException](String because, Object[] becauseArgs)
   at League.Tests.StatsSpecs.Create_stats_with_incorrect_points_should_throw_exception(Int32 points) in C:\dev\repos\League\League.Tests\StatsSpecs.cs:line 38
</code></pre>

<p>And here is my unit test, written with XUnit :</p>

<pre><code>[Theory]
[InlineData(899)]
[InlineData(1501)]
public void Create_stats_with_incorrect_points_should_throw_exception(int points)
{
    Action action = () =&gt; new Stats(points);

    action.Should().Throw&lt;InvalidOperationException&gt;();
}
</code></pre>

<p>Is there a way to still use the static readonly field in the constructor ?</p>
",https://stackoverflow.com/questions/61144904/use-a-static-readonly-field-in-constructor-c,"['c#', 'constructor', 'static', 'field']",262,False,-1,1
JSONDecodeError on response.json() after API GET request on unit test Python,"<p>I am struggling with some unit testing on API requests and I am getting this <code>JSONDecodeError</code> in my unit test which doesn't make sense to me because the response is content-type <code>application/json</code> and it is not empty. At this point I don't have more ideas what is causing that.</p>
<p>My api requests module:</p>
<pre><code>import requests
from netrc_auth import netrc_authentication
from config import HOST


client = requests.session()
user, password = netrc_authentication(HOST)

response = client.get(
        f&quot;https://{HOST}:8000/rest/folder/info?&quot;
        f&quot;name=test-name&quot;,
        auth=(user, password)
    )
response_json = response.json()

if(
    response.status_code == 200
    and response_json[&quot;errors&quot;][0][&quot;desc&quot;] == &quot;No such folder!&quot;
  ):
      client.post(
            f&quot;https://{HOST}:8000/rest/folder/create?&quot;
            f&quot;name=test-name&quot;
            f&quot;&amp;path={BASE_PATH}/test&quot;,
            auth=(user, password),
        )
</code></pre>
<p>unit tests module:</p>
<pre><code>def test_check_folder(monkeypatch, requests_mock, host, credentials):
    client = requests.session()

    if credentials == &quot;&quot;:
        monkeypatch.setattr(netrc_authentication, &quot;netrc_authentication&quot;, mock_authentication)
        user, password = netrc_authentication(HOST)
        requests_mock.get(
            f&quot;https://{HOST}:8000/rest/folder/info?&quot;
            f&quot;name=test-name&quot;,
            text=&quot;Unauthorized&quot;,
            status_code=401,
        )

        response = client.get(
            f&quot;https://{HOST}:8000/rest/folder/info?&quot;
            f&quot;name=test-name&quot;,
            auth=(user, password)
        )
        assert response.status_code == 401
    else:
        user, password = netrc_authentication(host)

        requests_mock.get(
            f&quot;https://{HOST}:8000/rest/folder/info?&quot;
            f&quot;name=test-name&quot;,
            text=&quot;OK&quot;,
            status_code=200,
        )

        response = client.get(
            f&quot;https://{HOST}:8000/rest/folder/info?&quot;
            f&quot;name=test-name&quot;,
            auth=(user, password)
        )
        response_json = response.json()
        if (
            response.status_code == 200
            and response_json[&quot;errors&quot;][0][&quot;desc&quot;]
            == &quot;No such folder!&quot;
        ):
            requests_mock.post(
                f&quot;https://{HOST}:8000/rest/folder/create?&quot;
                f&quot;name=test-name&quot;
                f&quot;&amp;path={BASE_PATH}/test&quot;,
                auth=(user, password),
                text=&quot;OK&quot;,
                status_code=201,
            )

            response = client.post(
                f&quot;https://{HOST}:8000/rest/folder/create?&quot;
                f&quot;name=test-name&quot;
                f&quot;&amp;path={BASE_PATH}/test&quot;,
                auth=(user, password),
            )
            assert response.status_code == 201
        else:
            assert response.status_code == 200
</code></pre>
<p>It fails on the part <code>response_json = response.json()</code> of the unit test with <code>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) </code>.Any ideas what else I can try?</p>
",https://stackoverflow.com/questions/64499695/jsondecodeerror-on-response-json-after-api-get-request-on-unit-test-python,"['python', 'json', 'unit-testing', 'mocking']",452,False,0,0
Is it possible to test if a method was called without using mocking framework,"<p>I am learning now about the topic Unit Testing in Java and interesting came to me a question that if we can test if a method was called without using Mock or Spy from Mocking Framework.
I mean for example if I have a simple class like</p>
<pre><code>class A {
    public void method1(){}
}
</code></pre>
<p>How can I test if <strong>method1</strong> was called from an instance a?
Do you think is it possible and how can I get that?</p>
<p>Thank you very much</p>
",https://stackoverflow.com/questions/63336864/is-it-possible-to-test-if-a-method-was-called-without-using-mocking-framework,"['java', 'mocking']",189,False,0,2
SpringBootTest: Unable to find table in h2 database,"<p>I am unit testing a JPA repository with h2 database.</p>

<p>I have placed following annotations on my unit test class:</p>

<pre><code>@ExtendWith(SpringExtension.class)
@SpringBootTest
</code></pre>

<p>In test, I just call default save method on JPA repository.</p>

<p>Entity is defined with annotations as:</p>

<pre><code>@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Table(name = ""coverage"")
</code></pre>

<p>And in src/test/resources, I have defined application.properties with details:</p>

<pre><code>spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.platform=h2
spring.jpa.properties.hibernate.dialect= org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
spring.h2.console.enabled=true
</code></pre>

<p>I expect SpringBootTest to read my entity class and create the table in h2 database. But I get error as:</p>

<pre><code>Caused by: org.postgresql.util.PSQLException: ERROR: relation ""coverage"" does not exist
</code></pre>

<p>What am I missing here?</p>
",https://stackoverflow.com/questions/62466432/springboottest-unable-to-find-table-in-h2-database,"['spring-boot', 'h2', 'junit5']",3070,False,0,2
Following Android docs on unit testing and failing,"<p>I am trying to run the simple unit test by following the example here:</p>
<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></p>
<pre><code>import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import org.junit.Test;

import static com.google.common.truth.Truth.assertThat;

public class UnitTestSampleJava {
    private static final String FAKE_STRING = &quot;HELLO_WORLD&quot;;
    private Context context = ApplicationProvider.getApplicationContext();

    @Test
    public void readStringFromContext_LocalizedString() {
        // Given a Context object retrieved from Robolectric...
        ClassUnderTest myObjectUnderTest = new ClassUnderTest(context);

        // ...when the string is returned from the object under test...
        String result = myObjectUnderTest.getHelloWorldString();

        // ...then the result should be the expected one.
        assertThat(result).isEqualTo(FAKE_STRING);
    }
}
</code></pre>
<p>I have a brand new project and I set the gradle files as specified, then I created a test with this line:</p>
<pre><code>private Context context = ApplicationProvider.getApplicationContext();
</code></pre>
<p>and I get an exception on that line number stating:</p>
<pre><code>java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
</code></pre>
<p>However, this was listed in the docs as a local unit test and not an instrumented test.</p>
",https://stackoverflow.com/questions/63440421/following-android-docs-on-unit-testing-and-failing,"['android', 'junit4', 'android-unit-testing']",467,True,0,1
How to check the unit test coverage for the new code on local,"<p>My company is going to force a new code unit testing coverage to allow the code merged. We have this number available on SonarQube after we commit and push to the remote branch. I was wondering if there is any tool/way for me to have a clue about this &quot;new code&quot; unit test coverage before I commit and push. Otherwise, I might end up with too many commits. Please advise. Thanks.</p>
",https://stackoverflow.com/questions/65230150/how-to-check-the-unit-test-coverage-for-the-new-code-on-local,"['unit-testing', 'sonarqube', 'code-coverage', 'sonarlint', 'sonarlint-intellij']",630,False,0,0
How to partially extract a JSON string to get a specific object by name,"<p>I have the following json string:</p>

<pre><code> ""{""\""itemList\"":[{\""id\"":1,\""name\"":\""Item 1 Name\""},{\""id\"":2,\""name\"":\""Item 2 Name\""}],""listInfo"":{""info1"":1,""info2"":""bla""}}""
</code></pre>

<p>How can I extract specific objects into a string?  For example, I want to get a new string out of it that looks like this: </p>

<p><code>[{\""id\"":1,\""name\"":\""Item 1 Name\""},{\""id\"":2,\""name\"":\""Item 2 Name\""}]</code></p>

<p>and another string that looks like this: </p>

<p><code>{""info1"":1,""info2"":""bla""}</code>. </p>

<p>The first string represents the <code>itemList</code> object (which holds an array) and the second string represents the <code>listInfo</code> object.</p>

<p>My objective is to compare these strings to other other objects that I plan to serialize for unit testing.</p>
",https://stackoverflow.com/questions/60370045/how-to-partially-extract-a-json-string-to-get-a-specific-object-by-name,"['c#', 'json', 'unit-testing', 'deserialization', 'mstest']",149,True,-2,1
Flutter command to export Unit testing Result,"<p>I am able to export unit testing report from Android Studio IDE. We have button to export in Android studio as below image</p>

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

<p>After clicking export button I will get a new dialog to select location of export and file type like below image</p>

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

<p>I need terminal command to do the export . </p>

<p>Terminal Command ""flutter test"" is just executing my test cases. I want to know the command for exporting unit test cases.</p>
",https://stackoverflow.com/questions/61955000/flutter-command-to-export-unit-testing-result,"['unit-testing', 'flutter', 'terminal']",594,True,0,1
"New to unit testing, would like some input on this unit test","<p>I'm fairly new to unit-testing and would like some input on good test implementations on some functions I have.</p>
<p>For methods that takes some input, and return an output, without knowing the expected return value, how would I properly test it? I have an example below...</p>
<pre><code>int add(int a, int b) {
     return a + b;
}

int actual = add(1,2);
int expect = 1 + 2; 

TEST_ASERT_EQUAL_INT(expect, actual);
</code></pre>
<p>Assuming I'm naive and does not know <code>1 + 2 = 3</code>. Would performing the same arithmetic as the function i'm testing to get the expected value consider good practice?</p>
",https://stackoverflow.com/questions/62902600/new-to-unit-testing-would-like-some-input-on-this-unit-test,['unit-testing'],151,True,0,1
Data-Driven Unit Test with MSTest : How to read and validate records from CSV file?,"<p>I use the MsTest and Data Driven approach for unit testing. </p>

<p>So far I have a Data.csv file with 5 rows added in my Unit Test project and I want to validate and output the UserId for each corresponding orgId and username.</p>

<p>For example, for Orgid <code>'80010'</code> and username <code>'Malika'</code> - expected <code>userid = 0000000047</code></p>

<p><a href=""https://i.stack.imgur.com/SHJvG.png"" rel=""nofollow noreferrer"">data.csv file</a></p>

<p>How can I set up the data driven test method to read and validate the correct userId from the .CSV file?</p>

<p><code>C# Code:</code></p>

<pre><code>using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AuthenticationServiceTest
{
    [TestClass]
    public class UT_GetUserIdFromUserName
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        [DataSource(""Microsoft.VisualStudio.TestTools.DataSource.CSV"", @""Data\Data.csv"", ""Data#csv"", 
        DataAccessMethod.Sequential)]
        public void TestMethod1()
        {
            // Arrange
            int ExpUserId = Convert.ToInt32(TestContext.DataRow[""0000000047""]);
            int orgId = Convert.ToInt32(TestContext.DataRow[1]);
            int username = Convert.ToInt32(TestContext.DataRow[2]);



            // Act
            string UserId = string.Empty;

            // Assert
            Assert.AreEqual(ExpUserId, UserId);
            Console.WriteLine(""Expected UserId: "" + ExpUserId);
            Console.WriteLine(""Actual UserId: "" + UserId);

        }

    }
    }
</code></pre>
",https://stackoverflow.com/questions/60826256/data-driven-unit-test-with-mstest-how-to-read-and-validate-records-from-csv-fi,"['csv', 'mstest', 'data-driven']",3288,True,0,1
How to convert desearilize boolean in MockMVC?,"<p>Hi I have a boolean variable in my class and I was trying to post this class in my spring boot testing.</p>
<p>However I encountered error as below:</p>
<pre><code>2020-07-21 03:42:11.590  WARN 11660 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'spbrResponse' on field 'isSuccess': rejected value [null]; codes [typeMismatch.spbrResponse.isSuccess,typeMismatch.isSuccess,typeMismatch.boolean,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spbrResponse.isSuccess,isSuccess]; arguments []; default message [isSuccess]]; default message [Failed to convert value of type 'null' to required type 'boolean'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to type [@com.fasterxml.jackson.annotation.JsonProperty boolean] for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type]]
</code></pre>
<p>The boolean field is called isSuccess and I already have getter and setter method:</p>
<pre><code>public class SpbrResponse&lt;T&gt; {
    private boolean isSuccess;
    private T result;
    private String error;

    public void setIsSuccess(boolean isSuccess) {
        this.isSuccess = isSuccess;
    }    

    public boolean getIsSuccess() {
        return isSuccess;
    }
}
</code></pre>
<p>In unit testing I use ObjectMapper to convert object into JSON:</p>
<pre><code>    ReportGenerationResponse response = new ReportGenerationResponse(1, 1, 1, 1, &quot;xx&quot;, &quot;yy&quot;, &quot;zz&quot;);
    SpbrResponse&lt;ReportGenerationResponse&gt; wrappedResponse = new SpbrResponse&lt;&gt;(true, response, &quot;&quot;);

    mockMvc.perform(
            post(&quot;/ReportComplete&quot;)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(objectMapper.writeValueAsString(wrappedResponse))
    )
    .andExpect(status().isOk());
</code></pre>
<p>I also tried to use</p>
<ol>
<li>@JsonProperty</li>
<li>Rename setter method to setSuccess()</li>
</ol>
<p>but all failed. Any help is highly appreciated.</p>
",https://stackoverflow.com/questions/63010873/how-to-convert-desearilize-boolean-in-mockmvc,"['spring-boot', 'spring-boot-test']",430,True,0,1
How can I test axios itself with mocking it?,"<p>I've just started learning react unit testing and the whole mock thing is confusing for me and I couldn't understand it .</p>
<p>I'm using axios to fetch data and display it in app component here :</p>
<pre><code>const [ data, setData ] = React.useState(null);

    useEffect(
        () =&gt; {
            const url = '/url';
            axios.get(url).then((res) =&gt; setData(res.data)).catch((err) =&gt; {
                console.log('error happened' + err);
            });
        },
        [ data ]
    );

    return (
        &lt;div&gt;
            {data ? &lt;p data-testid=&quot;name&quot;&gt;{data.name}&lt;/p&gt; : &lt;p data-testid=&quot;loading&quot;&gt;Loading...&lt;/p&gt;}
        &lt;/div&gt;
    );
</code></pre>
<p>And I test the whole loading and name thing in app.test.js :</p>
<pre><code>afterEach(cleanup);

describe('App', () =&gt; {
    test('Render app', async () =&gt; {
        render(&lt;App /&gt;);
        expect(screen.getByTestId('loading')).toBeInTheDocument();
        const name = await waitForElement(() =&gt; screen.getByTestId('name'));
        expect(name).toBeInTheDocument();
        expect(screen.queryByTestId('loading')).toBeNull();
    });
});

</code></pre>
<p>And all these tests pass successfully.</p>
<p>What I want to achieve is how can I test the axios itself by mocking it in app.test.js the easiest way ?</p>
",https://stackoverflow.com/questions/62517381/how-can-i-test-axios-itself-with-mocking-it,"['javascript', 'reactjs', 'unit-testing', 'react-testing-library', 'react-test-renderer']",189,True,0,1
how to mock private variable in RestController class,"<p>I am doing some web unit testing with Spring. is there a way I can mock the instance of <code>MyProcessor</code> which get set in <code>@PostConstruct</code>? I tried with <code>@MockBean</code> but it gets set as null and getting null pointer exception?</p>
<p>I am using a factory to instantiate <code>MyProcessor</code> based on some boolean flag. But if there is a different approach altogether that would make my test cleaner, I am open to ideas.</p>
<p>Please Note I am using Junit 5.</p>
<pre><code>public class Controller {

    private final AProcessorFactory factory;

    @Value(&quot;${tt.f.processor.async}&quot;)
    private boolean isAsync;

    private MyProcessor myProcessor;

    public Controller(final AProcessorFactory factory) {
        this.factory= factory;
    }

    @PostConstruct
    public void init() {
        myProcessor = factory.getInstance(isAsync);
    }

}


@WebMvcTest(Controller.class)
public class ControllerTest{

    @MockBean
    private MyProcessor processor;


    @MockBean
    private AProcessorFactory factory;

    @Autowired
    private MockMvc mockMvc;


    @Test
    public void test() throws Exception {           

        when(processor.process(any(Request.class), any(String.class)))
                .thenReturn(new TestResponse(&quot;123&quot;, SUCCESS, &quot;&quot;, &quot;&quot;));

}
</code></pre>
",https://stackoverflow.com/questions/63708547/how-to-mock-private-variable-in-restcontroller-class,"['java', 'spring', 'junit', 'mockito']",847,True,0,1
NgXs selectSnapshot not working in unit test,"<p>This describes pretty clearly how to write a unit test using NgXs
<a href=""https://www.ngxs.io/recipes/unit-testing"" rel=""nofollow noreferrer"">https://www.ngxs.io/recipes/unit-testing</a></p>

<p>So mimicking that I wrote a state with a SetLocale action:</p>

<pre><code>export class SetLocale {
  static readonly type = '[Internationalization] SetLocale';
  constructor(public value: string) { }
}

export class InternationalizationStateModel {
  locale: string;
}

@State&lt;InternationalizationStateModel&gt;({
  name: 'internationalization',
  defaults: {
    locale: null
  }
})
@Injectable({
  providedIn: 'root'
})
export class InternationalizationState {

  @Selector()
  static getLocale(state: InternationalizationStateModel): string {
    return state.locale;
  }

  @Action(SetLocale)
  setLocale(ctx: StateContext&lt;InternationalizationStateModel&gt;, { value }: SetLocale) {
    ctx.setState(
      patch({
        locale: value
      })
    );
  }
}
</code></pre>

<p>Nothing special there, and this works fine when used in the code. Next a unit test was added:</p>

<pre><code>  let store: Store;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [NgxsModule.forRoot([InternationalizationState])],
    });
    store = TestBed.inject(Store);
  });

  it('should process locale', () =&gt; {
    store.dispatch(new SetLocale('xx-XX'));
    const locale = store.selectSnapshot(s =&gt; s.locale);
    expect(locale).toBe('xx-XX');
  });
</code></pre>

<p>As far as I can see this is exactly how the guide suggests it, but this test fails with the fact the locale is undefined. </p>

<p>Why?</p>
",https://stackoverflow.com/questions/62167513/ngxs-selectsnapshot-not-working-in-unit-test,"['unit-testing', 'ngxs']",511,True,0,1
Unit Testing in React JS using Jest,"<p>I trying to do unit testing in a react application in which I want to test only one component.</p>
<p>What is the command for running the test of particular component?</p>
<p>I am doing this way for testing.</p>
<pre><code>npm test -- --testPathPattern components
</code></pre>
<p>I have all the <code>*.test.js</code> inside the components folder.</p>
<p>Above command will run the test cases for all the test files under the components folder but I want to run the tests only for the specific component.</p>
",https://stackoverflow.com/questions/64183721/unit-testing-in-react-js-using-jest,"['reactjs', 'jestjs']",220,True,0,2
Force Cmake to use system include path first,"<p>Im tring to build sources for unit testing with are part of bigger project.</p>

<p>Im using CmakeList inside which i point to directories where include headers are placed. </p>

<p>Somehow side by side with proper include header is placed string.h header made by someone with is causing problems. </p>

<p>How can i force Cmake to use string.h from /user/include first instead string.h from someModule/include?</p>

<p>When i delete string.h from someModule/include everything builds successfully.</p>
",https://stackoverflow.com/questions/59563474/force-cmake-to-use-system-include-path-first,"['unit-testing', 'cmake', 'googletest']",319,False,0,0
How do I parse Python Script(py) file into Java POJOs?,"<p>My java code generates Python file from XML input. In order to validate this translation, I would like to go through Python output file and check its content. Right now I am just using String contains method but I think if I could parse Python code into Java POJO, that would make this testing easy. If you think, there is another way to perform this unit testing. Kindly suggest. Thanks in advance.</p>
",https://stackoverflow.com/questions/60335154/how-do-i-parse-python-scriptpy-file-into-java-pojos,"['java', 'python', 'unit-testing', 'parsing', 'junit']",391,True,0,1
Testing Flink-Kafka integration,"<p>How to set up a unit testing environment where I can create Kafka topics, write to them using FlinkKafkaProducer and read from them using FlinkKafkaConsumer?</p>
<p>It seems like the functionality is there, but is not well-documented.</p>
<p>The farthest I was able to get is the following</p>
<pre><code>val server = new KafkaTestEnvironmentImpl()
server.prepare(KafkaTestEnvironment.createConfig().setKafkaServersNumber(1))
server.createTestTopic(&quot;my.test.topic&quot;, 1, 1)
server.shutdown()
</code></pre>
<p>But this throws an error <code>java.lang.NoClassDefFoundError: kafka/admin/RackAwareMode</code>. I am not sure if trying to resolve this error is the best course of action or whether there is a simpler solution.</p>
",https://stackoverflow.com/questions/63224206/testing-flink-kafka-integration,"['apache-flink', 'flink-streaming']",480,True,0,1
Why does overwriting datetime.datetime in function a affect the execution of function b?,"<p>I'm currently writing an article about patching for unit testing in Python and I got confused why the following works. When I execute <code>pytest</code> in that directory, the test succeeds although my system time is not in 1990.</p>
<p>I thought that the <code>datetime.datetime = NewDate</code> would only have an effect within the <code>test_example.py</code>. I think I need a better understanding of where Python stores the name / pointers to the imported modules. Can somebody please explain this?</p>
<h2>example.py</h2>
<pre class=""lang-py prettyprint-override""><code># Core Library modules
import datetime


def generate_filename():
    return f&quot;{datetime.datetime.now():%Y-%m-%d}.png&quot;
</code></pre>
<h2>test_example.py</h2>
<pre class=""lang-py prettyprint-override""><code># Core Library modules
import datetime
from unittest import mock

# First party modules
from mock_example import generate_filename


class NewDate(datetime.datetime):
    @classmethod
    def now(cls):
        return cls(1990, 4, 28)


def test_generate_filename():
    datetime.datetime = NewDate
    assert generate_filename() == &quot;1990-04-28.png&quot;

</code></pre>
",https://stackoverflow.com/questions/62646803/why-does-overwriting-datetime-datetime-in-function-a-affect-the-execution-of-fun,"['python', 'unit-testing', 'scope', 'patch']",45,True,0,2
Should I check implementation details or use class public API only in a unit test?,"<p>Consider the following example:</p>
<pre><code>public class Foo {

    protected List&lt;Integer&gt; arr = new ArrayList&lt;&gt;();

    void add(int i) { arr.add(i); }

    int size() { return 0; }
}

public class FooTest {

    Foo foo = new Foo();

    @Test
    void checkAdd() {
        foo.add(1);
        assertEquals(1, foo.size()); // fail
        assertEquals(1, foo.arr.size()); // pass
    }
}
</code></pre>
<p>Sorry, I have a lame question but still unable to find an answer. Is it considered as a bad practice to check implementation details as a part unit testing? Obviously testing one part of public API via another part of public API may (and most likely will) lead to incorrect results. On the other side implementation can be very complicated, just imagine if you want to test HashMap.</p>
",https://stackoverflow.com/questions/64156618/should-i-check-implementation-details-or-use-class-public-api-only-in-a-unit-tes,"['java', 'unit-testing']",46,True,0,2
Laravel mocking is not executing,"<p>I have been trying too mock a service class in my Laravel 6 unit testing, but the call is moving to the real method rather than mocked response. Here is the People class that I am trying to mock -</p>

<pre><code>class People
{ 
    public static function checkCredentials($username, $password) {
        // some code, which is not supposed to execute while unit testing. 
    }
}
</code></pre>

<p>The controller responsible to execute this is -</p>

<pre><code>class AuthController extends Controller {
    public function login(Request $request) {
        $auth = People::checkCredentials($request-&gt;username, $request-&gt;password);
        dd($auth);  // I am expecting mocked response here i.e., ['abc'].
    }
}
</code></pre>

<p>Here is my test class -</p>

<pre><code>class LoginTest extends TestCase {
    /** @test */
    public function a_user_can_login() {
         $this-&gt;mock(People::class, function ($mock) {
            $mock-&gt;shouldReceive('checkCredentials')
                    -&gt;withArgs(['username', 'password'])
                    -&gt;once()
                    -&gt;andReturn(['abc']);
        });
        $this-&gt;assertTrue(true);
    }
}
</code></pre>

<p>The dump in controller is returning the real response rather than mocked one. I need help to understand what I am doing wrong. Thanks.</p>
",https://stackoverflow.com/questions/60417679/laravel-mocking-is-not-executing,"['laravel', 'unit-testing', 'mocking', 'laravel-6', 'mockery']",414,True,0,1
AWS Laravel Unit Testing - The security token included in the request is invalid,"<p>I am doing unit testing for my AWS Cloudfront code using <code>phpunit</code>, if I am not testing the code in the command line, my code works perfectly fine. But if I am testing it in the command line, I am getting this error: <code>The security token included in the request is invalid.</code> I read somewhere that i need to work on <a href=""https://laravel.com/docs/8.x/mocking"" rel=""nofollow noreferrer"">Laravel &quot;mock&quot;</a>, but I can't seem to make that work.</p>
<p>Here is my code:</p>
<pre><code>$this-&gt;instance(CloudFrontService::class, \Mockery::mock(CloudFrontService::class, function ($mock) {
    $mock-&gt;shouldReceive('invalidate')-&gt;with(&quot;test.txt&quot;)-&gt;once();
}));

$r = app(CloudFrontService::class)-&gt;invalidate(&quot;test.txt&quot;);

$this-&gt;assertTrue($r);
</code></pre>
<p>Any guidance is greatly appreciated. Thank you!</p>
",https://stackoverflow.com/questions/64981138/aws-laravel-unit-testing-the-security-token-included-in-the-request-is-invalid,"['php', 'laravel', 'amazon-web-services', 'phpunit', 'amazon-cloudfront']",352,False,0,0
Unit test Keypress event directive in angular,"<p>I have a directive that prevents users from entering the alphabets. for unit testing I planned to execute that I will trigger a keypress event and if its number it will be there in the text box if not it should not. when I run the test, the event and char code is matching and the function returning true but I am not able to see the value in the text box.</p>
<p>Directive</p>
<pre><code>  @HostListener('keypress', ['$event']) onKeyPress(event: any) {
    let enteredChar: number;
    enteredChar = parseInt(event.charCode, 10);
    return enteredChar &gt;= 47 &amp;&amp; enteredChar &lt;= 57;
  }
</code></pre>
<p>Unit test</p>
<pre><code>@Component({
  template: `
    &lt;input PreventSpecialCharacters id=&quot;testComp&quot; type=&quot;text&quot; /&gt;
  `
})
class TestSpecialCharComponent {
  constructor(private el: ElementRef) {}
}

fdescribe('PreventSpecialCharactersDirective', () =&gt; {
  let fixture: ComponentFixture&lt;TestSpecialCharComponent&gt;;
  let inputEl: HTMLInputElement;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        TestSpecialCharComponent,
        PreventSpecialCharactersDirective
      ]
    });
    fixture = TestBed.createComponent(TestSpecialCharComponent);
    inputEl = fixture.nativeElement.querySelector('#testComp');
  });

  fit('should allow the input', () =&gt; {
    fixture.detectChanges();
    inputEl.dispatchEvent(makeKeyPressEvent('Digit1', 49, 49));
    expect(inputEl.value).toEqual('1');
  });
</code></pre>
",https://stackoverflow.com/questions/63030908/unit-test-keypress-event-directive-in-angular,"['angular', 'karma-jasmine', 'angular-directive', 'keyboard-events', 'angular-unit-test']",1044,True,0,1
Using Visual Studio native C++ unit testing framework with strings instead of wide strings,"<p>Is there a way to configure Visual Studio native C++ unit testing framework to work with <strong>std::string</strong> instead of <strong>std::wstrings</strong> ?</p>
<pre><code>Assert::Equal&lt;class T&gt;(const T &amp; t1,const T &amp;t2)
</code></pre>
<p>requires the function</p>
<pre><code>template&lt;class T&gt; std::wstring ToSring&lt;class T&gt;(const T &amp; t) /* note the wstring here */
</code></pre>
<p>to be written/specialized by the test writer for the object to be tested (of type T). I already have this function:</p>
<pre><code>ostream &amp; operator&lt;&lt;(ostream &amp; o, const T &amp; t) /* note the ostream vs wostream */
</code></pre>
<p>I would like to re-use (build uppon a third party narrow strings library), but I don't have the wostream equivalent, and don't want to rewrite one.</p>
<p>What are my options ?</p>
",https://stackoverflow.com/questions/65415332/using-visual-studio-native-c-unit-testing-framework-with-strings-instead-of-wi,"['c++', 'unit-testing', 'visual-studio-2019', 'vs-unit-testing-framework']",438,True,3,1
Develop React Module without compiling the entire project,"<p>I'm fairly new to React development and one of my projects is getting pretty large. I was wondering if there was any way to develop modules without the need of compiling and running the rest of the project. I know there is unit testing and jest but I'm struggling in how to develop UI on a module w/o compiling the entire project. The project in question is built on ReactJS, Redux, and Firebase.</p>
",https://stackoverflow.com/questions/62293660/develop-react-module-without-compiling-the-entire-project,"['reactjs', 'redux']",26,False,0,0
How do I inject dependencies in a Moq for a Unit Test,"<p>I have a DbContext that I am unit testing with Moq. The DbContext has two dependencies that I Inject with Autofac in my main program. When I unit test Moq tells me it cannot find a parameterless constructor. I add a parameterless constructor in my DbContext and the unit tests pass. Is there not a way to inject the DbContext dependencies with Autofac like I do in my main program?</p>
<p>Here is my unit test:</p>
<pre><code>    [TestMethod]
    public void GetAllPersons_orders_by_name()
    {
        var data = new List&lt;Person&gt;
        {
            new Person { FirstName = &quot;John&quot;, LastName = &quot;Doe&quot;},
            new Person { FirstName = &quot;Bill&quot; , LastName = &quot;Smith&quot;},
            new Person { FirstName = &quot;Fred&quot; , LastName = &quot;Williams&quot;}
        }.AsQueryable();

        var mockSet = new Mock&lt;DbSet&lt;Person&gt;&gt;();
        mockSet.As&lt;IQueryable&lt;Person&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider);
        mockSet.As&lt;IQueryable&lt;Person&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        mockSet.As&lt;IQueryable&lt;Person&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        mockSet.As&lt;IQueryable&lt;Person&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

        var mockContext = new Mock&lt;MyContext&gt;();

        mockContext.Setup(c =&gt; c.People).Returns(mockSet.Object);

        var service = new PeopleService(mockContext.Object);
        var people = service.GetAllPeople();

        Assert.AreEqual(3, people.Count);
        Assert.AreEqual(&quot;John&quot;, people[0].FirstName);
        Assert.AreEqual(&quot;Bill&quot;, people[1].FirstName);
        Assert.AreEqual(&quot;Fred&quot;, people[2].FirstName);
    }
</code></pre>
",https://stackoverflow.com/questions/63606862/how-do-i-inject-dependencies-in-a-moq-for-a-unit-test,"['c#', 'unit-testing', 'moq', 'autofac']",788,True,0,1
Unit Testing NodeJs Controller with Axios,"<p>I have a controller and a request file that look like this, making the requests with axios(to an external API), and sending the controller response to somewhere else, my question is, how to apply Unit Testing to my controller function (getInfoById), how do I mock the axiosRequest since it's inside the controller?. I am using Jest and only Jest for testing(might need something else, but I'm not changing)</p>

<pre><code>file: axiosFile.js

  import axios from ""axios""

  export const axiosRequest = async (name) =&gt; {
    const { data } = await axios.get(""url"")
    return data
  }


file: controllerFile.js

  import { axiosRequest } from ""./axiosFile""

  export const getInfoById = async (name) =&gt; {
    try {
      const response = await axiosRequest(name)
      return { status: 200, ...response }
    } catch {
      return { status: 500, { err: ""Internal ServerError"" } }
    }
  }
</code></pre>

<p>Thanks in advance.
PS: It's a Backend in NodeJs</p>
",https://stackoverflow.com/questions/60421207/unit-testing-nodejs-controller-with-axios,"['node.js', 'unit-testing', 'mocking', 'jestjs', 'axios']",410,False,2,1
How to test if view is able to create a new entity in the db?,"<p>I have to do basic unit testing in order to get my code coverage higher. I do not need to do anything fancy. Just the bare minimum is required. So, in this case if I am able to hit my view successfully, then that is all I need to do. 
Agile team is nested under Team as you can see in the models.py.</p>

<p>models.py - </p>

<pre><code>class Organization(models.Model):
    orgname = models.CharField(max_length = 100, blank=True)

    def __str__(self):
        return str(self.orgname)

class Team(models.Model):
    teamID = models.AutoField(primary_key=True)
    teamName = models.CharField(max_length = 100, blank=True)
    org = models.ForeignKey(Organization, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.teamName)

class AgileTeam(models.Model):
    agileTeamID = models.AutoField(primary_key=True)
    agileTeamName = models.CharField(max_length = 100, blank=True)
    team = models.ForeignKey(Team,  on_delete=models.CASCADE)

    def __str__(self):
        return str(self.agileTeamName)
</code></pre>

<p>views.py - </p>

<pre><code>@csrf_exempt
def newATeam(request):
    if request.method == 'POST':
        param = json.loads(request.body)
        agileteam = param.get('agileteam')
        teamname = param.get('teamname')
        team = Team.objects.get(teamName = teamname)
        AgileTeam.objects.create(agileTeamName=agileteam, team=team)
        return JsonResponse(status = 200, data = {})
</code></pre>

<p>urls.py - </p>

<pre><code>path('ajax/newATeam/', views_admin.newATeam, name='ajax_newATeam'),
</code></pre>

<p>test_views.py - </p>

<pre><code>class TestViews(TestCase):
@classmethod
    def setUpTestData(self):
        # set-up org
        ORG_NAMES = ['REVCYCSCH', 'DIABLO', 'BROTHERHOOD']
        for org in ORG_NAMES:
            Organization.objects.create(orgname=org)

        # set-up team
        orgModels = Organization.objects.all()
        TEAM_NAMES = ['Blitzkrieg ', 'Hammerheads', 'Mercenaries']
        for i in range(len(TEAM_NAMES)):
            Team.objects.create(teamName=TEAM_NAMES[i], org=orgModels[i])

        # set-up agileteam
        teamModels = Team.objects.all()
        AGILE_TEAM_NAMES = ['Barons', 'Exterminators ', 'Mavericks', 'Renegades', 'Stratosphere', 'Trojans ']
        index = 0
        for team in teamModels:
            for _ in range(2):
                AgileTeam.objects.create(agileTeamName=AGILE_TEAM_NAMES[index], team=team)
                index = index + 1

        self.client = Client()

        def test_newATeam(self):
            params = {'agileteam': 'Barons', 'teamname': 'Blitzkrieg'}
            response = self.client.post(path = '/ajax/newATeam/', data = params, content_type = 'application/json')
            self.assertEqual(response.status_code, 200) 
</code></pre>

<p>However, I get this error - 
<a href=""https://i.stack.imgur.com/zG8Wv.png"" rel=""nofollow noreferrer"">Error</a></p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/60987939/how-to-test-if-view-is-able-to-create-a-new-entity-in-the-db,"['python', 'django', 'unit-testing']",39,False,2,2
What&#39;s is the best way to unit test this function in Python?,"<p>I am new to Python unit testing and just trying to get a hang of it. Say I am trying to test the <code>get_diagonals</code> function. What would be the best test case for this? </p>

<p>The following is my test case: 
I am literally copying over the output and asserting. What would be some good test cases here? I have used assertNotEqual here to make it match for this example. </p>

<pre><code>import unittest
import Connect4_second as ConnectFour

class TestConnect4(unittest.TestCase):
    height, width  = 4,4

    items_obj = ConnectFour.ConnectFour(height,width)
    def test_diagonals(self):
        diagonals = [['0', '0'],
                     ['0', '1', '0', ' '],
                     ['0', '1', ' ', '0', '1', ' '],
                     ['0', '1', ' ', ' ', '0', '1', ' ', ' '],
                     [' ', ' ', ' ', '1', ' ', ' '],
                     [' ', ' ', ' ', ' '],
                     [' ', ' '],
                     [],
                     [],
                     [],
                     [],
                     [],
                     [],
                     []]
        self.items_obj.startGame(self.items_obj)
        expectedDiagonals = self.items_obj.get_diagonals()
        diagonalsInARow = ['0','0','0','0']
        self.assertNotEqual(diagonals, expectedDiagonals, ""Diagonal check"")

</code></pre>

<p>The following is my full implementation of the game:</p>

<pre><code>class ConnectFour():
    """"""
    Class for creating a connect four game
    """"""
    def __init__(self, height, width):
        self.height = height
        self.width = width
        self.board = [[' ' for x in range(width)] for i in range(height)]

    def get_column(self, index):
        """"""
        Returns a column at the specified index

        :param index: Index at which column will be returned
        """"""
        return [i[index] for i in self.board]

    def get_row(self, index):
        """"""
        Returns a row at the specified index

        :param index: Index at which row will be returned
        """"""
        return self.board[index]

    def get_diagonals(self):
        """"""
        Returns all the diagonals in the game
        """"""
        # TODO set global variable for diagonals
        diagonals = []
        #TODO negative slope (Top right 3,0 -&gt; 0,3 bottom ledt)
        for i in range(self.height + self.width - 1):
            diagonals.append([])
            for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)):
                diagonals[i].append(self.board[self.height - (i - j + 1)][j])
        #TODO positive slope (Top left 0,0 -&gt; bottom right 3,3)
        for i in range(self.height + self.width - 1):
            diagonals.append([])
            for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)):
                diagonals[i].append(self.board[i - j][j])

        return diagonals

    def make_move(self, team, col):
        """"""
        Simulates a move and puts a 0/1 in the specified column
        """"""
        if ' ' not in self.get_column(col):
            return self.board
        i = self.height - 1
        while self.board[i][col] != ' ':
            i -= 1
        self.board[i][col] = team
        return self.board

    def check_win(self):
        """"""
        Checks self.board if either user has four in a row
        """"""
        four_in_a_row = [['0', '0', '0', '0'], ['1', '1', '1', '1']]

        #Check rows
        for i in range(self.height):
            for j in range(self.width - 3): #Focus on just 1 row
                if self.get_row(i)[j:j + 4] in four_in_a_row:
                    return self.board[i][j]

        #Check columns
        for i in range(self.width):
            for j in range(self.height - 3): #Focus on just 1 col
                if self.get_column(i)[j:j + 4] in four_in_a_row:
                    return self.board[j][i]

        #Check diagonals
        for i in self.get_diagonals():
            for j, _ in enumerate(i):
                if i[j:j + 4] in four_in_a_row:
                    return i[j]
        return None

# def start_game(height, width):
    """"""
    Starts a game of ConnectFour
    """"""
    def startGame(self, game):
        while True:
            for i in game.board:
                print(i)
            if game.check_win() is not None:
                break

            col = int(input('Team 0 choose column: ')) - 1
            game.make_move('0', col)

            for i in game.board:
                print(i)
            if game.check_win() is not None:
                break

            col = int(input('Team 1 choose column: ')) - 1
            game.make_move('1', col)

        return f'Team {game.check_win()} has won. Thank you for playing!!!'



if __name__ == '__main__':
    height = 5
    width = 5
    game = ConnectFour(height, width)

    game.startGame(game)
</code></pre>
",https://stackoverflow.com/questions/61092281/whats-is-the-best-way-to-unit-test-this-function-in-python,"['python', 'python-3.x', 'pygame', 'python-unittest']",544,True,2,1
How do I unit test a URL.openConnection() without network connection?,"<p>I'm unit testing a block of code that instantiates a new URL object and calls .openConnection, gets and inputStream them maps using a jackson ObjectMapper.</p>
<pre><code>try {
      url = new URL(uriString);
      URLConnection urlConnection = url.openConnection();
      urlConnection.setDoInput(true);
      InputStream inputStream = urlConnection.getInputStream();
      String contentString = IOUtils.toString(inputStream);
      Object = objectMapper.readValue(contentString, Object.class);
    } catch (IOException e) {
      throw new InternalErrorRequestException(ERROR_MESSAGE, e);
    }
</code></pre>
<p>Mocking the objectMapper.readValue is easy enough.  But how can I handle the the new URI object and the resulting uriConnection without an internet connection?  Assuming that I cannot modify the source.  And I cannot add any new dependency.</p>
<p>Is there a way to capture the <code>new URL</code> object and pass in a mock without using PowerMock's <code>whenNew()</code> ?</p>
",https://stackoverflow.com/questions/62704223/how-do-i-unit-test-a-url-openconnection-without-network-connection,"['java', 'unit-testing', 'junit', 'mocking', 'mockito']",464,True,2,1
How do I hide the Jest types so I can use Mocha?,"<p><strong>Question:</strong></p>
<p>How do I get the Jest types to not come up automatically? They're creating a false positive for me since I'm actually running the unit tests with Mocha.</p>
<p><strong>Context:</strong></p>
<p>I'm looking to use TSDX but to run the tests in the browser. Unfortunately, TSDX comes pre-installed with Jest which doesn't test in a browser. So that makes Mocha the correct choice for a unit testing library (since it has high popularity and runs in a browser).</p>
",https://stackoverflow.com/questions/64669892/how-do-i-hide-the-jest-types-so-i-can-use-mocha,"['typescript', 'mocha.js']",217,True,2,1
unit testing angular component with @input,"<p>I have an angular component which has an @input attribute and processes this on the <code>ngOnInit</code>.  Normally when unit testing an @input I just give it as <code>component.inputproperty=value</code> but in this case I cannot since its being used on the <code>ngOnInit</code>.  How do I provide this input value in the <code>.spec.ts</code> file.  The only option I can think of is to create a test host component, but I really don't want to go down this path if there is an easier method.</p>
",https://stackoverflow.com/questions/63839249/unit-testing-angular-component-with-input,"['angular', 'unit-testing', 'input']",6820,True,2,1
Correct way to unit test/mock shared export function using props from components - React,"<p>In my React project, I have a shared exported function:</p>

<pre><code>//shared_functions.js
export function buildEndpoint(region, methodName) {
   return (region in this.props.regionalEndpointsMap ? this.props.regionalEndpointsMap[region] : this.props.regionalEndpointsMap[""default""]) + ""/"" + methodName;
}
</code></pre>

<p>that's used and imported in multiple components such as:</p>

<pre><code>//SomeComponent.jsx
import { buildEndpoint } from 'src/util/shared_functions';
....
handleSubmit = async event =&gt; {
   let response = await fetch(buildEndpoint(this.state.region, 'methodName'), {
....
</code></pre>

<p>The problem is I'm having trouble unit testing this function due to this.props.regionalEndpointsMap in the buildEndpoint function. </p>

<p>My question is what would be the correct way to unit test this function following best practices? Unit test it independently of any component that uses it? Test it from a component that uses it? Haven't been able to find a way to mock this.props.regionalEndpoints when trying to test the function independently, and when trying to test it from a component, the function is unrecognized:</p>

<pre><code>//test.jsx
....
//props contains regionalEndpointsMap
wrapper = shallow(&lt;SomeComponent {...props} /&gt;);
wrapper.instance().buildEndpoint('region', 'method')
//buildEndpoint is unrecognized
</code></pre>

<p>And as another question that may make the above a moot point, okay to try and access a property (props) in an exported function even though it's not guaranteed to have that property in a component it's used in? Or is it frowned upon? Would it be better to create a base component class with this function and make it the parent to the component classes that use it?</p>

<p>Sorry if these sound like dumb questions, new to React and unit testing with jest and enzyme.</p>
",https://stackoverflow.com/questions/60892199/correct-way-to-unit-test-mock-shared-export-function-using-props-from-components,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",186,False,0,1
How to override JPA @PrePersist behaviour for a unit test,"<p>I have the following JPA entity:</p>
<pre class=""lang-java prettyprint-override""><code>@Entity
@Builder
@Table(name = &quot;My_Table&quot;)
public class MyTableEntity {

    @Column(name = &quot;id&quot;)
    private long id;

    @Column(name = &quot;creationdatetime&quot;)
    private LocalDateTime creationDateTime;

    @Column(name = &quot;updatedatetime&quot;)
    private LocalDateTime updateDateTime;

    @PrePersist
    protected void onCreate() {
    this.creationDateTime = LocalDateTime.now();
        this.updateDateTime = LocalDateTime.now();
    }
}
</code></pre>
<p>I have a unit test where I am doing this:</p>
<pre class=""lang-java prettyprint-override""><code>   LocalDateTime creationDate = LocalDateTime.now().minusDays(100);
   MyTableEntity entity = 
   MyTableEntity.builder()
           .id(1)
           .build();
   entity.setCreationDateTime(creationDate)
   entity.setUpdateDateTime(creationDate)
</code></pre>
<p>However, later on in my unit test, the value I'm setting for creation date time and update date time  is magically getting changed as per what is defined in the <code>@PrePersist</code> method in my JPA entity.</p>
<p>Solely for the purpose of unit testing, how can I stop <code>@PrePersist</code> from overriding values I'm explicitly setting during the unit test?</p>
<p>(If it, helps I am using Mockito.)</p>
",https://stackoverflow.com/questions/65088896/how-to-override-jpa-prepersist-behaviour-for-a-unit-test,"['java', 'unit-testing', 'jpa']",1512,True,2,1
Comparing LocalDate using Hamcrest in Junit Test Case,"<p>I am my unit testing my REST Controller, one of whose field is LocalDate in my Test Case. Code below: </p>

<pre><code>@Test
 public void getByExternalTransactionId() throws Exception {
        EquityFeeds equityFeeds = new EquityFeeds(423,""SAPEXTXN1"", ""GS"", ""ICICI"", ""BUY"", LocalDate.of(2013, 11, 22), 101.9f, ""BLO"", ""Y"",0);
        when(equityFeedsService.findByExternalTransactionId(""SAPEXTXN1"")).thenReturn(equityFeeds);
        mockMvc.perform(MockMvcRequestBuilders.get(""/equityFeeds/getByExternalTransactionId/{externalTransactionId}"", ""SAPEXTXN1""))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(jsonPath(""$.*"", Matchers.hasSize(10)))
                .andExpect(jsonPath(""$.id"", Matchers.is(423)))
                .andExpect(jsonPath(""$.externalTransactionId"", Matchers.is(""SAPEXTXN1"")))
                .andExpect(jsonPath(""$.clientId"", Matchers.is(""GS"")))
                .andExpect(jsonPath(""$.securityId"", Matchers.is(""ICICI"")))
                .andExpect(jsonPath(""$.transactionType"", Matchers.is(""BUY"")))
//                .andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDate.of(2013, 11, 22))))
                .andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDate.of(2013, Month.NOVEMBER, 22))))
//                .andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDateMatchers.isDay(2013, Month.NOVEMBER,22))))
//                .andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDateMatchers.sameDay(LocalDate.of(2013, 11, 22)))))
//                .andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDateMatchers.within(1, ChronoUnit.DAYS, LocalDate.of(2013,11,22)))))
                .andExpect(jsonPath(""$.marketValue"", Matchers.is(101.9f)))
                .andExpect(jsonPath(""$.sourceSystem"", Matchers.is(""BLO"")))
                .andExpect(jsonPath(""$.priorityFlag"", Matchers.is(""Y"")))
                .andExpect(jsonPath(""$.processingFee"", Matchers.is(0)));
        verify(equityFeedsService, times(1)).findByExternalTransactionId(""1"");
        verifyNoInteractions(equityFeedsService);
    }
</code></pre>

<p>Issue: </p>

<p>I have tried Matching LocalDate as per the below code:</p>

<pre><code>.andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDate.of(2013, 11, 22))))
.andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDate.of(2013, Month.NOVEMBER, 22))))
</code></pre>

<p>These give me the below Assertion Error: </p>

<pre><code>java.lang.AssertionError: JSON path ""$.transactionDate""
Expected: is &lt;2013-11-22&gt;
     but: was &lt;[2013,11,22]&gt;
Expected :is &lt;2013-11-22&gt;
Actual   :&lt;[2013,11,22]&gt;
</code></pre>

<p>The other code which I have tried is: </p>

<pre><code>.andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDateMatchers.isDay(2013, Month.NOVEMBER,22))))
.andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDateMatchers.sameDay(LocalDate.of(2013, 11, 22)))))
.andExpect(jsonPath(""$.transactionDate"", Matchers.is(LocalDateMatchers.within(1, ChronoUnit.DAYS, LocalDate.of(2013,11,22)))))
</code></pre>

<p>Each of these is giving me the below exceptions: </p>

<pre><code>java.lang.ClassCastException: class net.minidev.json.JSONArray cannot be cast to class java.time.LocalDate (net.minidev.json.JSONArray is in unnamed module of loader 'app'; java.time.LocalDate is in module java.base of loader 'bootstrap')
</code></pre>

<p>How do I compare my LocalDate which is set in the constructor as: LocalDate.of(2013, 11, 22) with the Matchers statement?.</p>
",https://stackoverflow.com/questions/61184154/comparing-localdate-using-hamcrest-in-junit-test-case,"['java', 'unit-testing', 'junit5', 'hamcrest', 'localdate']",663,False,2,1
Using strategy pattern along with Dependency injection,"<p>I'm going through Strategy pattern listed out in <a href=""https://en.wikipedia.org/wiki/Strategy_pattern"" rel=""nofollow noreferrer"">https://en.wikipedia.org/wiki/Strategy_pattern</a> and trying to understand how this would work when you want to use Dependency injection as well and make it easy for unit testing.</p>
<p>So the interface is:</p>
<pre><code>interface BillingStrategy {
    // Use a price in cents to avoid floating point round-off error
    int getActPrice(int rawPrice);
}
</code></pre>
<p>There are two implementations:</p>
<pre><code>@Component
NormalHours implements BillingStrategy {
    public int getActPrice(int rawPrice) {
       return rawPrice;
    }

}

@Component
HappyHours implements BillingStrategy {
    public int getActPrice(int rawPrice) {
       return rawPrice/2;
    }

}
</code></pre>
<p>Now there is a customer object for whom I want to keep track of how the total price:</p>
<pre><code>class Customer {
    private final List&lt;Integer&gt; drinks = new ArrayList&lt;&gt;();
    private BillingStrategy strategy;

    public Customer(BillingStrategy strategy) {
        this.strategy = strategy;
    }

    public void add(int price, int quantity) {
        this.drinks.add(this.strategy.getActPrice(price*quantity));
    }

    // Payment of bill
    public int getBill() {
        int sum = this.drinks.stream().mapToInt(v -&gt; v).sum();
        
        this.drinks.clear();
        return sum;
    }

    // Set Strategy
    public void setStrategy(BillingStrategy strategy) {
        this.strategy = strategy;
    }
}
</code></pre>
<p>Now say I've a file which I've which has information about purchases made during each hour of the day, and I need to compute the final bill for the customer.</p>
<pre><code>@Component 
public class Calculator {
   
public int calculate(File file) {
   //pseudo code here
   Customer customer = new Customer();
   for(line in file) {
      //parse price, strategy and quantity from line
      customer.setStrategy(strategy);
      customer.add(price, quantity);
     
   }

   return customer.getBill();
}


}
</code></pre>
<p>Obviously this doesn't work great for unit testing as a new object is created within the method and by using just regular Mockito it's going to be hard to mock the values returned for the strategies in Calculator class. Is there a different way to model the Customer &amp; Calculator class to ensure ease of testing and use DI as much as possible?</p>
<p>I know one way is let the caller of Calculator pass in the object Customer, but however with the way the wiki has explained this particular Customer class we cannot make it as a Singleton and the same problem will exist.</p>
",https://stackoverflow.com/questions/63369649/using-strategy-pattern-along-with-dependency-injection,"['java', 'dependency-injection', 'strategy-pattern']",150,True,0,1
Mocking Database for API Test,"<p>I'm new to C# and .Net and trying to get into Unit Testing my API.
I created a project consisting of an actual Database, a controller for data access, a business layer and a REST-API.</p>
<p>I need some kind of test database to test my POST- and my GET-Methods.
And I would like to initialize this test database with some test data for the GET-Methods.</p>
<p>I already tried to solve the problem following a Microsoft tutorial about mocking databases, but the test database is interfering with my actual database constructor in the controller and the tutorial only works with a mocked database.</p>
<p>Here is my controller with its DB constructor</p>
<pre><code>namespace TSM_Programm.Controllers
{
    public class ItemController : ControllerBase
    {

        //Constructor for DB usage 
        private TSMContext _context;

        public ItemController(TSMContext context)
        {
            _context = context;
        }

        // Get all items
        public List&lt;Item&gt; Getitems()
        {

            return _context.items.ToList();
        }

       //and so on...
</code></pre>
<p>And in my API those controller methods get called with the typical Http features and a business layer constructor</p>
<pre><code>    [ApiController]
    public class APIController : Controller
    {

        private readonly BusinessController _business;

        public UserController(BusinessController business)
        {
            _business = business;
        }

        //GET Itemlist
        [HttpGet(&quot;AllItems&quot;)]
        public List&lt;Item&gt; GetAllItems()

        {
           return List&lt;Item&gt; newlist = _business.GetAllItems().ToList();

        }
</code></pre>
<p>I already created a second database class which is a interface, but i do not know how to put it in my controller, so i can use it for unit testing.</p>
<p>for reference:</p>
<pre><code>namespace TSM_Programm.Data
{
    public interface ITestDatabase : IDisposable
    {

        DbSet&lt;Item&gt; Items { get; set; }     
        DbSet&lt;MoreItem&gt; MoreItems { get; set; }
        DbSet&lt;SomeMoreItem&gt; SomeMoreItems{ get; set; }

        int SaveChanges();
    }
}
</code></pre>
<p>And my actual DB class</p>
<pre><code>namespace TSM_Programm.Data
{
    public class TSMContext : DbContext, ITestDatabase
    {

        public TSMContext(DbContextOptions&lt;TSMContext&gt; options) : base(options){ }
        
        DbSet&lt;Item&gt; Items { get; set; }     
        DbSet&lt;MoreItem&gt; MoreItems { get; set; }
        DbSet&lt;SomeMoreItem&gt; SomeMoreItems{ get; set; }
    }
}
</code></pre>
<p>Can you give me a hint what I'm doing wrong?
Are there any tutorials that fit my problem?</p>
",https://stackoverflow.com/questions/62743534/mocking-database-for-api-test,"['c#', 'api', 'unit-testing', 'asp.net-core', 'mocking']",3233,True,0,2
PHP testing multiple forms,"<p>I have some problem with PHP Unit testing. I'm using Laravel as framework and I'm writing tests for first time.
I have created test that should register the user, and it does, but the problem is it's returning 500 as an error (when unit testing), and I will explain why.
First this is how my register form looks like:</p>
<pre><code>public function setRegister(Request $request)
    {
        $validator = Validator::make($request-&gt;all(), [
            'name' =&gt; 'required|string|max:255',
            'email' =&gt; 'required|string|email|max:255|unique:users',
            'password' =&gt; 'required|string|min:6|confirmed',
        ]);

        if ($validator-&gt;fails())
        {
            return response(['response' =&gt; false, 'message' =&gt; $validator-&gt;errors()-&gt;all()], 422);
        }

        $request['remember_token'] = Str::random(10);
        
        $user = User::create(['name' =&gt; $request-&gt;name, 'email' =&gt; $request-&gt;email, 'password' =&gt; Hash::make($request['password']), 'register_ip' =&gt; Log::getIp(), 'last_activity' =&gt; Carbon::now() ]);

        $tokenResult = $user-&gt;createToken($user-&gt;name);

        $token = $tokenResult-&gt;token;

        $tokenResult-&gt;token-&gt;save();

        UserDevices::create([
            'user_id' =&gt; $user-&gt;id, 
            'token_id' =&gt; $token-&gt;token_id, 
            'system' =&gt; Secure::getOS(), 
            'ip_address' =&gt; Secure::getIP(), 
            'browser' =&gt; Secure::browser(), 
            'device' =&gt; Secure::getDevice(), 
            'mac_address' =&gt; Secure::getMac(), 
            'full_http_client' =&gt; Secure::getUserAgent()
            ]);


        return response()
            -&gt;json(['result' =&gt; true, 'message' =&gt; 'Register successful', 'data' =&gt; $user, 'token' =&gt; $tokenResult-&gt;accessToken ]);
    }
</code></pre>
<p>The problem is with UserDevices (or Secure class), It should take every info from the HTTP_USER_AGENT, and Secure class looks like:</p>
<pre><code>class Secure
{
    public static function getUserAgent() {
        return  $_SERVER['HTTP_USER_AGENT'];
    }

    public static function getIP() {

        if (!empty($_SERVER['HTTP_CLIENT_IP']))   
        {
            $ip_address = $_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
        {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        elseif (!empty($_SERVER['HTTP_FORWARDED_FOR']))  
        {
            $ip_address = $_SERVER['HTTP_FORWARDED_FOR'];
        }
        elseif (!empty($_SERVER['HTTP_FORWARDED']))  
        {
            $ip_address = $_SERVER['HTTP_FORWARDED'];
        }
        elseif (!empty($_SERVER['REMOTE_ADDR']))  
        {
            $ip_address = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip_address = 'NO IP';
        }

        return $ip_address;
    }

    public static function getOS() {

        $user_agent = self::getUserAgent();
        $os_platform    =   &quot;Unknown OS Platform&quot;;
        $os_array       =   array(
            '/windows nt 10/i'      =&gt;  'Windows 10',
            '/windows nt 6.3/i'     =&gt;  'Windows 8.1',
            '/windows nt 6.2/i'     =&gt;  'Windows 8',
            '/windows nt 6.1/i'     =&gt;  'Windows 7',
            '/windows nt 6.0/i'     =&gt;  'Windows Vista',
            '/windows nt 5.2/i'     =&gt;  'Windows Server 2003/XP x64',
            '/windows nt 5.1/i'     =&gt;  'Windows XP',
            '/windows xp/i'         =&gt;  'Windows XP',
            '/windows nt 5.0/i'     =&gt;  'Windows 2000',
            '/windows me/i'         =&gt;  'Windows ME',
            '/win98/i'              =&gt;  'Windows 98',
            '/win95/i'              =&gt;  'Windows 95',
            '/win16/i'              =&gt;  'Windows 3.11',
            '/macintosh|mac os x/i' =&gt;  'Mac OS X',
            '/mac_powerpc/i'        =&gt;  'Mac OS 9',
            '/linux/i'              =&gt;  'Linux',
            '/ubuntu/i'             =&gt;  'Ubuntu',
            '/iphone/i'             =&gt;  'iPhone',
            '/ipod/i'               =&gt;  'iPod',
            '/ipad/i'               =&gt;  'iPad',
            '/android/i'            =&gt;  'Android',
            '/blackberry/i'         =&gt;  'BlackBerry',
            '/webos/i'              =&gt;  'Mobile'
        );

        foreach ($os_array as $regex =&gt; $value) {
            if (preg_match($regex, $user_agent)) {
                $os_platform    =   $value;
            }
        }   
        return $os_platform;
    }

    public static function browser() {

        $user_agent= self::getUserAgent();

        $browser        =   &quot;Unknown Browser&quot;;

        $browser_array  =   array(
            '/msie/i'       =&gt;  'Internet Explorer',
            '/Trident/i'    =&gt;  'Internet Explorer',
            '/firefox/i'    =&gt;  'Firefox',
            '/safari/i'     =&gt;  'Safari',
            '/chrome/i'     =&gt;  'Chrome',
            '/edg/i'        =&gt;  'Edge',
            '/edge/i'       =&gt;  'Edge',
            '/opera/i'      =&gt;  'Opera',
            '/opr/i'        =&gt;  'Opera',
            '/netscape/i'   =&gt;  'Netscape',
            '/maxthon/i'    =&gt;  'Maxthon',
            '/konqueror/i'  =&gt;  'Konqueror',
            '/ubrowser/i'   =&gt;  'UC Browser',
            '/SamsungBrowser/i' =&gt; 'Samsung Internet',
            '/CriOS/i' =&gt; 'iPhone Chrome',
            //'/mobile/i'     =&gt;  'Handheld Browser'
        );

        foreach ($browser_array as $regex =&gt; $value) {

            if (preg_match($regex, $user_agent)) {
                $browser    =   $value;
            }

        }

        return $browser;

    }

    public static function  getDevice(){

        $tablet_browser = 0;
        $mobile_browser = 0;

        if (preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
            $tablet_browser++;
        }

        if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
            $mobile_browser++;
        }

        if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') &gt; 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
            $mobile_browser++;
        }

        $mobile_ua = strtolower(substr(self::getUserAgent(), 0, 4));
        $mobile_agents = array(
            'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
            'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
            'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
            'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
            'newt','noki','palm','pana','pant','phil','play','port','prox',
            'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
            'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
            'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
            'wapr','webc','winw','winw','xda ','xda-');

        if (in_array($mobile_ua,$mobile_agents)) {
            $mobile_browser++;
        }

        if (strpos(strtolower(self::getUserAgent()),'opera mini') &gt; 0) {
            $mobile_browser++;
                //Check for tablets on opera mini alternative headers
            $stock_ua = strtolower(isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])?$_SERVER['HTTP_X_OPERAMINI_PHONE_UA']:(isset($_SERVER['HTTP_DEVICE_STOCK_UA'])?$_SERVER['HTTP_DEVICE_STOCK_UA']:''));
            if (preg_match('/(tablet|ipad|playbook)|(android(?!.*mobile))/i', $stock_ua)) {
                $tablet_browser++;
            }
        }

        if ($tablet_browser &gt; 0) {
               // do something for tablet devices
            return 'Tablet';
        }
        else if ($mobile_browser &gt; 0) {
               // do something for mobile devices
            return 'Mobile';
        }
        else {
               // do something for everything else
            return 'Computer';
        }   
    }
    
    public static function getMac()
    {
        $ipAddress=$_SERVER['REMOTE_ADDR'];
        $macAddr=false;

        $arp=`arp -a $ipAddress`;
        $lines=explode(&quot;\n&quot;, $arp);

        foreach($lines as $line)
        {
            $cols=preg_split('/\s+/', trim($line));
            if ($cols[0]==$ipAddress)
            {
                    $macAddr=$cols[1];
            }
        }

        return $macAddr;
    }
</code></pre>
<p>I know, it's not beautiful but it's working, I will need to rewrite all of it.
So when I'm running tests on signup form, I'm receiving 500 first time, and if I run it again it will give 422, because User is already created. If I comment in UserController line for adding device or UserDevices class it will work perfectly.</p>
<p>The test looks like:</p>
<pre><code>/** @test */
    public function user_register_fail_test()
    {

    $userData = [
        &quot;name&quot; =&gt; &quot;John Doe&quot;,
        &quot;email&quot; =&gt; &quot;doe@example.com&quot;,
        &quot;password&quot; =&gt; &quot;demo12345&quot;,
        &quot;password_confirmation&quot; =&gt; &quot;demo12345&quot;
    ];

    $response = $this-&gt;withHeaders([
        'Accept' =&gt; 'application/json',
        'Content-Type' =&gt; 'application/json', 
        'HTTP_USER_AGENT' =&gt; 'Mozilla/5.0 (Linux; Android 10; SM-N975F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.120 Mobile Safari/537.36'
    ])-&gt;json('POST', '/api/auth/signup', $userData);

    $response
        -&gt;assertStatus(422)
        -&gt;assertJson([
            'created' =&gt; true,
        ]);
    }
</code></pre>
<p>As you see I'm passing every needed Headers (I think) and it should work by my logic. Where it could be a problem? Is it headers actually? I have tested everything on postman and works fine.</p>
<p>Now I catched Exception for UserDevices, and it says that</p>
<blockquote>
<p>Undefined index: HTTP_USER_AGENT</p>
</blockquote>
",https://stackoverflow.com/questions/64064027/php-testing-multiple-forms,"['php', 'laravel']",55,False,0,0
Unit testing for appconfig service which gets json file in angular 9,"<p>I have recently started learning unit testing in angular and currently trying to write tests for appconfig service.</p>

<p>The Code which I want to unit test for appservice config is as below, which gets the environments from the json file:</p>

<pre><code>public loadEnvironment(): Observable&lt;AppSettings&gt; {
    if (!this.configuration$) {
      this.configuration$ = this.http.get&lt;AppSettings&gt;(`/environment`).pipe(
        shareReplay(1)
      );
    }
    return this.configuration$;
  }
</code></pre>

<p>For this, I tried to write below test but somehow I am not able to figure out how I can mock the json file get here?</p>

<pre><code>describe('AppConfigService', () =&gt; {
  let appConfigService: AppConfigService;
  let httpMock: HttpTestingController;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      providers: [
        AppConfigService
      ],
    });

    appConfigService = TestBed.get(AppConfigService);
    httpMock = TestBed.get(HttpTestingController);
  });

  it(`should fetch enviornment as an Observable`, async(inject([HttpTestingController, AppConfigService],
    (httpClient: HttpTestingController, appConfigService: AppConfigService) =&gt; {

      appConfigService.loadEnvironment().subscribe();

      let req = httpMock.expectOne('/environment');
      expect(req.request.method).toBe(""GET"");

      httpMock.verify();
    })));
});
</code></pre>

<p>As I said I am very new so please consider that.</p>
",https://stackoverflow.com/questions/61439105/unit-testing-for-appconfig-service-which-gets-json-file-in-angular-9,"['angular', 'unit-testing', 'angular9']",596,False,2,0
"Type &#39;{}&#39; is missing the following properties from type &#39;Request&#39;: get, header, accepts, acceptsCharsets, and 67 more","<p>I'm testing my endpoints in offline mode mocking/faking all the data. Based on the <a href=""https://firebase.google.com/docs/functions/unit-testing#testing_http_functions"" rel=""nofollow noreferrer"">Firebase Unit testing of Cloud functions docs</a>, they use it as following:</p>

<pre><code>const req = { query: {text: 'input'} };
const res = {
  redirect: (code, url) =&gt; {
    assert.equal(code, 303);
    assert.equal(url, 'new_ref');
    done();
  }
};

// Invoke addMessage with our fake request and response objects
myFunctions.addMessage(req, res);
</code></pre>

<p>My code is similar:</p>

<pre><code>const req = {

}

const res = {

}

updateUser(req, res)

// and this is 'updateUser()' function in another file
export default functions.https.onRequest(async (req, res) =&gt; { ... }
</code></pre>

<p>So I'm getting the following error:</p>

<p><strong>Argument of type '{}' is not assignable to parameter of type 'Request'.
Type '{}' is missing the following properties from type 'Request': get, header, accepts, acceptsCharsets, and 67 more.</strong></p>

<p>How can I avoid putting all the 67 properties? I just want to provide 'method', 'query' or 'body' properties.</p>
",https://stackoverflow.com/questions/60862339/type-is-missing-the-following-properties-from-type-request-get-header,"['node.js', 'typescript', 'express', 'google-cloud-functions']",2584,True,4,2
vue js jest.spyOn mounted function call not working in unit test on class component,"<p>I am new to unit testing and I am trying to test a function being called when the component is mounted. Below is the component code I am testing:</p>

<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;div class=""grid""&gt;
      &lt;Card
        class=""grid_layout_col""
        @showItemDetail=""showDetails(index)""
        @openEditModal=""editItem(index)""
      /&gt;
    &lt;/div&gt;
    &lt;!-- fab --&gt;
    &lt;Fab ref=""fabBtn"" @addItem=""showModal"" /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
// @ is an alias to /src
import { Component, Prop, Vue, Watch } from ""vue-property-decorator"";
import router from ""../router"";
import { store, actions, mutations } from ""@/store/store"";
import Card from ""@/components/Card.vue"";
import Fab from ""@/components/Fab.vue"";

@Component({
  components: {
    Card,
    Fab
  }
})
export default class Home extends Vue {
  itemData: Array&lt;object&gt;;

  constructor() {
    super();
    this.itemData = [];
  }

  convertBlobURL(imageData: string) {}

  showDetails(val: number) {}

  addItem() {}

  editItem(val: string) {}

  showModal() {}

  resetHeader() {}

   mounted() {
    // load the card data
    actions.loadData();

  }
}
</code></pre>

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

<pre><code> export const actions = {
  loadData(){
    store.loadData();
  },
  getDelStoreLength(): number {
    return store.delStore.length;
  },
  getStoreLength(): number {
    return store.dataStore.data.length; 
  }
};
</code></pre>

<p>The problem I am facing is when I run the jest test below:</p>

<pre><code>import { shallowMount, mount } from ""@vue/test-utils"";
import Home from ""@/views/Home.vue"";

//
const factory = (propsData: object) =&gt; {
  return shallowMount(Home, {
    propsData: {
      ...propsData
    },
    stubs: {

    },
    mocks: {

    }
  });
};
it(""should call actions.loadData function on mounted"", () =&gt; {
  const wrapper = factory({});
  let spyIt = jest.spyOn(Home as any, 'actions.loadData');
  expect(spyIt).toHaveBeenCalled();
});
</code></pre>

<p>I get the below:</p>

<p><strong>Cannot spy the actions.loadData property because it is not a function; undefined given instead</strong></p>

<p>Does anyone know what this is and how to fix it?</p>
",https://stackoverflow.com/questions/60317421/vue-js-jest-spyon-mounted-function-call-not-working-in-unit-test-on-class-compon,"['unit-testing', 'vue.js']",1605,True,1,1
"How to provide int[,] and int values to test method, C#","<p>I need this method for unit testing. There is matrix and method that calculate matrix trace which is integer. So i need to provide simple matrix (int[,]) and expected trace:</p>

<pre><code>[DynamicData(nameof(TestDataMethod), DynamicDataSourceType.Method)]
public void TestReturnTrace(int[,] simpleMatrix, int expected)
{
    var mock = new Mock&lt;IMatrixGenerator&gt;();

    mock.Setup(a =&gt; a.GenerateRandomMatrix()).Returns(simpleMatrix);

    MatrixBase matrix = new MatrixBase(mock.Object);

    int actual = matrix.ReturnTrace();

    Assert.AreEqual(expected, actual);
}
</code></pre>

<p>How can i create simple 2D array and integer value and return it?</p>

<p>My best attempt is:</p>

<pre><code>    static IEnumerable&lt;object[], int&gt; TestDataMethod()
    {
        int[,] array2d = new int[,] { { 1, 0 }, { 0, 1 } };
        int myInteger = 2;

        return (new[] { 
            new[] { array2d }, 
            myInteger )
        };
    }
</code></pre>

<p>but the error is ""No best type found for implicitly-typed array"", like if I try to create array, but I just pair two values in parentheses. Where am I wrong?</p>
",https://stackoverflow.com/questions/59932654/how-to-provide-int-and-int-values-to-test-method-c,"['c#', '.net', 'unit-testing', 'mstest']",435,True,1,1
How to assert an integer is within range by using Unittest in Python?,"<p>I have a file to validate the label </p>

<pre><code>#configmanager.py

class FunctionNode(object):
    def __validate_func_label(self, func_label):
        pattern = re.compile('^fn[1-9][0-9]{0,1}$')
        if not pattern.match(func_label):
            raise Exception(
                f""Invalid value {func_label} for function label in function config."")

</code></pre>

<p>and I have to write a test case for it using Unit Testing. Test case will check if user enters <code>fn</code> is between 1 and 99, it will pass. Otherwise if <code>fn</code> out of range such as <code>fn0</code> or <code>fn100</code> then it fail. I writed a TestClass</p>

<pre><code>#test__validate_func_label.py

import unittest
from configmanager import FunctionNode

class TestValidateFuncLabel(unittest.TestCase):
    def setUp(self):
        pass

    def test_fn_within_range(self):
        for i in range(1,99):
            self.assertEqual(fn(i),output[i])

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

<p>But I feel like I'm not on the right track.
Is there any way i can assert <code>fn</code> is within range from 1 to 99?</p>

<p>Any help is appreciated.</p>
",https://stackoverflow.com/questions/60295571/how-to-assert-an-integer-is-within-range-by-using-unittest-in-python,"['python', 'python-unittest']",2082,True,1,2
How to perform unit testing with databases in PHP Unit 8.0 or greater,"<p>I am running a PHP project and I am using PHPUnit for unit testing. Up until recently I used PHPUnit 4.0 with DBUnit as an extension for database testing. I changed now to PHPUnit 8.0 but could not find a suitable database testing extension to test my backend functions with a test database connected. Also the documentation of PHPUnit does not contain any hint for database testing.</p>

<p>What module/extension replaces DBUnit for PHPUnit 8.0 or higher?</p>

<p>Thanks</p>

<p>Christian</p>
",https://stackoverflow.com/questions/61975330/how-to-perform-unit-testing-with-databases-in-php-unit-8-0-or-greater,"['database', 'phpunit', 'dbunit']",195,False,1,0
Mocking Laravel custom validation rule class not working,"<p>I'm implementing a new custom validation rule in form submit. But I want to bypass the validation rule in unit testing. Below is the simplified of the validation rule and unit test class. What am I missing?</p>

<pre><code>namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Captcha implements Rule
{
    public function passes($attribute, $value)
    {
        // assuming will always return false in testing
        // works fine when true
        return false; 
    }

    public function message()
    {
        return 'Captcha error! Try again later or contact site admin.';
    }
}
</code></pre>

<pre><code>use Tests\TestCase;
use App\Rules\Captcha;

class RegistrationTest extends TestCase {

    public test_user_registration()
    {
        $this-&gt;mock(Captcha::class, function ($mock) {
            $mock-&gt;shouldReceive('passes')-&gt;andReturn(true);
        });

        $response = $this-&gt;post(route('tenant.register'), [
            'g-recaptcha-response' =&gt; 1,
            'email' =&gt; 'user@example.com',
            'password' =&gt; 'secret',
        ]);

        $this-&gt;assertEquals(1, User::all()-&gt;count());
     }
} 
</code></pre>

<p>EDIT: included <code>FormRequest</code> and <code>Controller</code> file as well</p>

<pre><code>namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\Captcha;

class NewUserRequest extends FormRequest {

    public function rules()
    {
        return [
            'name' =&gt; ['required', new Captcha]
        ];
    }
}
</code></pre>

<pre><code>...

public function postRegister(NewUserRequest $request) {

...
</code></pre>

<p>EDIT II: seems like a bug in Laravel itself;</p>

<ul>
<li><a href=""https://github.com/laravel/framework/issues/28468"" rel=""nofollow noreferrer"">https://github.com/laravel/framework/issues/28468</a></li>
<li><a href=""https://github.com/laravel/framework/issues/19450"" rel=""nofollow noreferrer"">https://github.com/laravel/framework/issues/19450</a></li>
<li><a href=""https://github.com/laravel/framework/issues/25041"" rel=""nofollow noreferrer"">https://github.com/laravel/framework/issues/25041</a></li>
</ul>

<p>tried the provided solutions but still not working</p>
",https://stackoverflow.com/questions/59853235/mocking-laravel-custom-validation-rule-class-not-working,"['laravel-5', 'phpunit']",1570,True,1,2
How to run flow with minimal configuration in mosaic,"<p>I'm developing some ETL jobs using Mosaic Decisions. While running the job, it's submitting the job to Spark using the default configurations. This default configuration is really huge and I don't need that much for development (as I am using less number of records for unit testing while development).</p>
<p>Is there a way I can instruct Mosaic to use less Spark resources for my development? So that I won't unnecessarily block the resources of the cluster?</p>
",https://stackoverflow.com/questions/63136645/how-to-run-flow-with-minimal-configuration-in-mosaic,['mosaic-decisions'],27,True,1,1
Jest Unit Test for chained function calls,"<p>Its been a while I am struggling with this. New to Unit testing.. I am trying to mock a unit test case for -</p>

<pre><code>fetchFooter() {
    client.items().type('footer_link')
            .depthParameter(10)
            .toObservable()
            .subscribe((response) =&gt; {
                this.setState({
                    resFooter: response.items,
                    resFooterLinked: response.linkedItems,
                });
            });
}
</code></pre>

<p>Where client is </p>

<pre><code>import { DeliveryClient } from '@kentico/kontent-delivery';

const client = new DeliveryClient({
  projectId: &lt;projectKey&gt;,
  enableAdvancedLogging: false,
});
</code></pre>

<p>This is what I have written till now, but doesn't seem to work. </p>

<pre><code>const sample = {
  items: {},
  linkedItems: {}
};//this is my response object

describe(""testing client"", () =&gt; {
  const mockClient = {
    items: jest.fn().mockReturnThis(),
    type: jest.fn().mockReturnThis(),
    depthParameter: jest.fn().mockReturnThis(),
    toObservable: jest.fn().mockReturnThis(),
    subscribe: jest.fn().mockReturnThis(),
  };

  const mockProps = {
    client: mockClient,
  };
  const component = mount(
    &lt;Footer mockProps={mockProps} resFooter={true} resFooterLinked={true} /&gt;
  );

  describe(""Component"", () =&gt; {
    describe(""#componentDidMount"", () =&gt; {
      it(""should mount the component and set state correctly"", () =&gt; {
        const mockedResponse = sample;
        mockClient.subscribe.mockImplementationOnce((handler) =&gt; handler(sample));
        // tslint:disable-next-line: no-string-literal
        component[""setState""] = jest.fn();
        component.instance().fetchFooter();
        expect(
          mockClient.items().type().depthParameter().toObservable().subscribe
        ).toBeCalledWith(""footer_link"");
        // tslint:disable-next-line: no-string-literal
        expect(component[""setState""]).toBeCalledWith(sample);
      });
    });
  });
});
</code></pre>

<p>I am getting an error as - </p>

<pre><code>    expect(jest.fn()).toBeCalledWith(...expected)

    Expected: ""footer_link""

    Number of calls: 0
</code></pre>

<p>Maybe I am missing some basics here. I searched for a solution for this, but unfortunately didn't find one which can work for me.
Can anyone help with this? Thanks in advance</p>
",https://stackoverflow.com/questions/62323143/jest-unit-test-for-chained-function-calls,"['reactjs', 'ecmascript-6', 'jestjs', 'enzyme', 'kentico']",4055,True,1,1
TypeError: Failed to execute &#39;createObjectURL&#39; on &#39;URL&#39;: No function was found that matched the signature provided,"<p>I have a angular 8 application and I do some unit testing with jasmine karma. So this is the component.ts:</p>
<pre><code>export class DossierPersonalDataComponent implements OnInit {
  dossier: DossierDto;
  editDossierForm: FormGroup;
  formBuilder = new FormBuilder();
  globalEditDossierErrors: ValidationErrors;
  dossierItems: DossierItemDto[] = [];
  profileImagefile: File;
  profileImageNeedsUpload = false;

  constructor(
    private dossierService: DossierService,
    private route: ActivatedRoute,
    private sanitizer: DomSanitizer,
    private dossierFileService: DossierFileService,
    private errorProcessor: ErrorProcessor,
    private dialog: MatDialog
  ) {
    this.dossierItems = this.route.snapshot.data.dossierItems;
    this.editDossierForm = this.formBuilder.group({});
    this.editDossierForm.disable();

    this.dossier = this.route.snapshot.data.dossier;
    this.dossierItems = route.snapshot.data.dossierItems;
    this.profileImagefile = this.route.snapshot.data.profileImage;

    this.editDossierForm = this.formBuilder.group({
      firstName: this.formBuilder.control(this.dossier.firstName, [Validators.required, Validators.maxLength(255)]),
      lastName: this.formBuilder.control(this.dossier.lastName, [Validators.required, Validators.maxLength(255)]),
      mobile: this.formBuilder.control(this.dossier.mobile, [Validators.maxLength(255)]),
      company: this.formBuilder.control(this.dossier.company, [Validators.maxLength(255)]),
      buddy: this.formBuilder.control(this.dossier.buddy, [Validators.maxLength(255)]),
      supervisor: this.formBuilder.control(this.dossier.supervisor, [Validators.maxLength(255)]),
      dateOfBirth: this.formBuilder.control(this.dossier.dateOfBirth)
    });
  }
  ngOnInit(): void {
    this.editDossierForm.disable();
  }

  editName() {
    this.editDossierForm.enable();
  }

  get profileImageUrl() {
    return this.profileImagefile === null
      ? '/assets/placeholder.jpg'
      : this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.profileImagefile));
  }
}
</code></pre>
<p>and this is the spec file:</p>
<pre><code>
describe('DossierPersonalDataComponent', () =&gt; {
  let component: DossierPersonalDataComponent;
  let fixture: ComponentFixture&lt;DossierPersonalDataComponent&gt;;

  beforeEach(async(() =&gt; {


    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, DossierModule, BrowserModule],
      declarations: [DossierPersonalDataComponent],
      providers: [
          DossierFileService,
          ErrorProcessor,
          {
            provide: ActivatedRoute,
            useValue: {
              snapshot: {
                data: {
                  dossier: {
                    firstName: 'hello',
                    lastName: 'world',
                    mobile: '111-111-1111',
                    company: 'carapax',
                    buddy: 'bud',
                    supervisor: 'super',
                    dateOfBirth: '1900-01-01',
                  },
                  dossierItems: [], // mock
                  profileImage: '',
                }
              }
            }
          },
        {
          provide: DomSanitizer,
          useValue: {
            sanitize: () =&gt; 'safeString',
            bypassSecurityTrustHtml: () =&gt; 'safeString'
          }
        }
      ]
    })
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(DossierPersonalDataComponent);
        component = fixture.componentInstance;
      });
  }));


  it('should create', () =&gt; {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  }); 
});
</code></pre>
<p>But so when I run the tests, I get this error:</p>
<pre><code>DossierPersonalDataComponent &gt; should create
TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
</code></pre>
<p>And in the coverage file I see this as yellow:</p>
<pre><code>get profileImageUrl() {
    return this.profileImagefile === null
      ? '/assets/placeholder.jpg'
      : this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.profileImagefile));
  }
</code></pre>
<p>so this is the yellow part</p>
<pre><code>? '/assets/placeholder.jpg'
</code></pre>
<p>branche not covered.</p>
<p>So what I have to change?</p>
<p>Thank you</p>
<p>And I am using google chrome</p>
<p>I changed to this:</p>
<pre><code>provide: ActivatedRoute,
            useValue: {
              snapshot: {
                data: {
                  dossier: {
                    firstName: 'hello',
                    lastName: 'world',
                    mobile: '111-111-1111',
                    company: 'carapax',
                    buddy: 'bud',
                    supervisor: 'super',
                    dateOfBirth: '1900-01-01',
                  },
                  dossierItems: [], // mock
                  profileImagefile: null,
                }
              }
            }
</code></pre>
<p>But no change</p>
",https://stackoverflow.com/questions/63897319/typeerror-failed-to-execute-createobjecturl-on-url-no-function-was-found-t,"['javascript', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",1268,True,1,1
Angular “Cannot read property &#39;subscribe&#39; of undefined” in Unit Test,"<p>I am using Jest to unit test my Angular app, and I keep getting this error
<code>TypeError: Cannot read property 'subscribe' of undefined</code>
No solution online seems to make sense or work properly. Here's some code:</p>

<p>page-view.component.ts</p>

<pre><code>  @Input() gotPlot!: Observable&lt;void&gt;;
  ...
  ngOnInit() {
    this.initialiseColumnDefs();
    this.gotPlot.subscribe((response) =&gt; { //ERROR is occurring on this line
      this.gotPlotValues(response);
    });
  }
</code></pre>

<p>page.component.ts</p>

<pre><code>@Component({
  selector: 'page',
  template: `
    &lt;page-view
      [gotPlot]=""gotPlotSubject.asObservable()""
    &gt;
    &lt;/page-view&gt;
  `,
})

export class PageComponent implements OnInit {
  ...
  public gotPlotSubject: Subject&lt;void&gt; = new Subject&lt;void&gt;();
  ...

  async get_plot(arr: any): Promise&lt;any[]&gt; {

    //This function calls a service and gets 'plotValues'
    (await this.service.get_plot(input)).subscribe((data: any) =&gt; {

      //plotValues is set to values gotten from the service here     

      this.gotPlotSubject.next(plotValues);
    });
  }
}
</code></pre>

<p>page-view.component.spec.ts</p>

<pre><code>@Component({
  selector: 'page',
  template: `
    &lt;page-view *ngIf=""gotPlotSubject.asObservable()"" [gotPlot]=""gotPlotSubject.asObservable()""&gt;
    &lt;/page-view&gt;
  `,
})
class PageMock {
  public gotPlotSubject: Subject&lt;void&gt; = new Subject&lt;void&gt;();
  constructor() {}
  ngOnInit() {
    let plotValues: any = [];
    plotValues[0] = 1;
    plotValues[1] = [1, 2, 3];
    plotValues[2] = [2, 3, 4];
    this.gotPlotSubject.next(plotValues);
  }
}

describe('ViewComponent', () =&gt; {
  let spectator: Spectator&lt;ViewComponent&gt;;

  const createComponent = createComponentFactory({
    component: ViewComponent,
    declarations: [
      ViewComponent,
      PageMock,
    ],
    imports: [TranslateModule.forRoot(), MaterialModule, AgGridModule, FormsModule],
    providers: [HttpClient, HttpHandler, NGXLogger, NGXMapperService, HttpBackend, NGXLoggerHttpService, LoggerConfig],
    schemas: [NO_ERRORS_SCHEMA],
  });

  beforeEach(() =&gt; {
    spectator = createComponent();
  });

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

</code></pre>

<p>Is my PageMock wrong? How do I mock the observable/subscribe correctly? Is there an easier way to do this without using observables or subscribe? Subscribe and Observables seem to make Unit Testing way more of a pain than it should be.</p>
",https://stackoverflow.com/questions/59740352/angular-cannot-read-property-subscribe-of-undefined-in-unit-test,"['angular', 'typescript', 'unit-testing', 'mocking', 'observable']",1246,True,1,1
C# Convert physical file to iformfile,"<p>I am trying to read a physical excel file to a IFormFile but the content is always empty when I am reading the file it keep shows byte 0. I am trying to test a method that will read the content of the excel file. Is there anyone that did testing that manage to read an excel file to a iformfile or how do I write unit testing that is reading the file using epplus?</p>
<p><strong>ServiceTest.cs</strong></p>
<pre><code>    [Fact]
    public async Task saveFile_test()
    {
        string rootPath = Directory.GetCurrentDirectory();
        string testAssetsFolder = @&quot;Assets\&quot;;
        string testFile = &quot;test.xlsx&quot;;
        string testFilePath = Path.Combine(rootPath, testAssetsFolder, testFile);

        // Arrange.
        var fileMock = new Mock&lt;IFormFile&gt;();
        var physicalFile = new FileInfo(testFilePath);
        var ms = new MemoryStream();
        var writer = new StreamWriter(ms);
        using (FileStream fs = physicalFile.OpenRead())
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b, 0, b.Length) &gt; 0)
            {
                writer.WriteLine(temp.GetString(b));
            }
        }
        writer.Flush();
        ms.Position = 0;
        var fileName = physicalFile.Name;
        //Setup mock file using info from physical file
        fileMock.Setup(_ =&gt; _.FileName).Returns(fileName);
        fileMock.Setup(_ =&gt; _.Length).Returns(ms.Length);
        fileMock.Setup(m =&gt; m.OpenReadStream()).Returns(ms);
        fileMock.Setup(m =&gt; m.ContentDisposition).Returns(string.Format(&quot;inline; filename={0}&quot;, fileName));
        //...setup other members as needed

        List&lt;IFormFile&gt; files = new List&lt;IFormFile&gt;();
        files.Add(fileMock.Object);

        await _service.saveFile(files, &quot;directory&quot;, &quot;subDirectory&quot;, default);
    }
</code></pre>
<p><strong>Service.cs</strong></p>
<pre><code>    public async Task saveFile(List&lt;IFormFile&gt; files, string directory, string subDirectory, CancellationToken cancellationToken)
    {
        subDirectory = subDirectory ?? string.Empty;
        var target = Path.Combine(directory, subDirectory);

        Directory.CreateDirectory(target);

        foreach (IFormFile file in files)
        {
            if (file.Length &lt;= 0) return;
            var filePath = Path.Combine(target, file.FileName);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream, cancellationToken);
                try
                {
                    // add to read encoded 1252 values
                    using (var package = new ExcelPackage(stream))
                    {

                        // Express worksheet
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[&quot;Express&quot;];
                        int colCount = worksheet.Dimension.End.Column;  //get Column Count
                        int rowCount = worksheet.Dimension.End.Row;

                        ....
</code></pre>
",https://stackoverflow.com/questions/62707237/c-convert-physical-file-to-iformfile,"['c#', 'unit-testing', '.net-core', 'epplus']",1638,False,1,1
"NullPointerException when running JUnit4 test, with MockitoHint &quot;Unused...&quot; and &quot;args ok?&quot;","<p>I'm trying to run this JUnit 4 test for checking for correct  <code>LiveData</code> values of an object called <code>dbState</code>:</p>
<pre><code>    @Test
fun `saveNoteToDb - correct DB states`() {
    val dbStatus = SUT.dbState?.testObserver()
    val githubUser = GithubUser(&quot;&quot;, &quot;&quot;)

    `when`(insertUserUseCase.insert(githubUser))
        .thenReturn(Completable.complete())

    SUT.saveNoteToDb(&quot;&quot;, &quot;&quot;)

    Truth.assert_()
        .that(dbStatus?.observedValues)
        .isEqualTo(listOf(DB_SAVING, NOTE_SAVED))
}
</code></pre>
<p>But I am getting a <code>NullPointerException</code>, with Mockito adding a few hints not very helpful:</p>
<pre><code>[MockitoHint] ProfileViewModelTest.saveNoteToDb - correct DB states (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -&gt; at com.something.someapp.ui.profile.ProfileViewModelTest.saveNoteToDb - correct DB states(ProfileViewModelTest.kt:88)
[MockitoHint]  ...args ok? -&gt; at com.something.someapp.ui.profile.ProfileViewModel.saveNoteToDb(ProfileViewModel.kt:54)


java.lang.NullPointerException
    at com.something.someapp.ui.profile.ProfileViewModel.saveNoteToDb(ProfileViewModel.kt:55)
    at com.something.someapp.ui.profile.ProfileViewModelTest.saveNoteToDb - correct DB states(ProfileViewModelTest.kt:91)
    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:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
</code></pre>
<p>The function being tested looks like this:</p>
<pre><code>    fun saveNoteToDb(userName: String, note: String) {
        compositeDisposable += insertUserUseCase.insert(GithubUser(userName, note))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { _dbState.value = DB_SAVING }
            .subscribeBy(
                onComplete = { _dbState.value = NOTE_SAVED },
                onError = {
                    _dbState.value = it.message?.let { msg -&gt; DB_ERROR(msg) }
                    it.printStackTrace()
                }
            )
    }
</code></pre>
<p>I'm new to unit testing and I'm completely baffled with this, especially since a similar test I made passed. This tests another <code>LiveData</code> object called <code>uiState</code></p>
<pre><code>    @Test
    fun `fetchUserDetails - correct UI states`() {
        val uiStatus = SUT.uiState?.testObserver()

        `when`(searchUserUseCase.searchForUser(&quot;username&quot;)).thenReturn(Single.just(
            SearchUserResponse()
        ))

        SUT.fetchUserDetails(&quot;username&quot;)

        Truth.assert_()
            .that(uiStatus?.observedValues)
            .isEqualTo(listOf(LOADING, SUCCESS))
    }
</code></pre>
<p>Here is the function being tested by the previous successful test:</p>
<pre><code>    fun fetchUserDetails(userName: String) {
        compositeDisposable += searchUserUseCase.searchForUser(userName)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { _uiState.value = LOADING }
            .subscribeBy(
                onSuccess = {
                    followers.set(it.followers.toString())
                    following.set(it.following.toString())
                    name.set(it.name)
                    location.set(it.location)
                    _uiState.value = SUCCESS
                },
                onError = { error -&gt;
                    error.printStackTrace()
                    _uiState.value = error.message?.let {
                        ERROR(it)
                    }
                }
            )
    }
</code></pre>
<p>The <code>testObserver</code> looks like this, for reference:</p>
<pre><code>open class TestObserver&lt;T&gt; : Observer&lt;T&gt; {

    val observedValues = mutableListOf&lt;T?&gt;()

    override fun onChanged(value: T?) {
        observedValues.add(value)
    }
}

fun &lt;T&gt; LiveData&lt;T&gt;.testObserver() = TestObserver&lt;T&gt;().also {
    observeForever(it)
}
</code></pre>
",https://stackoverflow.com/questions/63297299/nullpointerexception-when-running-junit4-test-with-mockitohint-unused-and,"['android', 'unit-testing', 'mockito', 'junit4', 'android-livedata']",560,True,0,1
Force setters to a class. To populate values in test methods,"<p>I would like to set value to an object that does not have setters in them. This is purely to generate a an object for unit testing. This class is in a library which I cannot change.</p>
<pre><code>public class Animal {
    protected String name;
    public Animal() {}
    public String getName() {
        return this.name;
    }
}
</code></pre>
<p>Lets say I have to create an object for Animal and set name and test different cases from them.</p>
<p>I have updated the code. This is snippet is close to the implementation. The variable is 'protected' and the class is 'public'</p>
",https://stackoverflow.com/questions/63333150/force-setters-to-a-class-to-populate-values-in-test-methods,"['java', 'spring-boot', 'junit4', 'powermock']",101,True,0,1
How can I add support for angular unit tests in dotnet core angular template of Visual Studio,"<p>I have my angular project in the ASP.NET Core Angular template of Visual Studio. And I have integrated this project to Azure DevOps. Now, the issue is, at the unit testing step in the Azure pipeline, it runs <code>dotnet test</code> command to run the unit tests. But I have my unit test in the angular project which is run by Karma. How can I run the angular unit tests with the same setup which I have right now?</p>
",https://stackoverflow.com/questions/62191667/how-can-i-add-support-for-angular-unit-tests-in-dotnet-core-angular-template-of,"['angular', 'unit-testing', 'asp.net-core', 'azure-devops', 'azure-pipelines']",706,True,-1,1
Mochawesome report is not opening in browser?,"<p>I'm doing unit testing using mocha chai. I want to see the reports in browser. Using mochawesome-report I'm able to generate test cases report in a folder mochawesome-report. In that I could see mochawesome.json and mochawesome.html. But unable to open the mochawesome.html file in browser. Kindly help.</p>
<p>Is there any other module to see the report generation in the browser or how can I see the test result in the browser which is displaying in console ?</p>
",https://stackoverflow.com/questions/64592007/mochawesome-report-is-not-opening-in-browser,"['mocha.js', 'chai', 'mochawesome']",1165,True,0,2
How do I test a function that calls another function in jest?,"<p>I have a function that converts an array of 8 bit integers into a x-bit integer. This function has extensive unit tests in Jest. This function is called <code>convertArrayIntoInt()</code>.</p>
<p>I have another functions that relies on <code>convertArrayIntoInt()</code> called <code>getSignature()</code>.</p>
<pre class=""lang-js prettyprint-override""><code>/**
 * @param {Uint8Array} fileContents The file contents
 * @param {number} position The position in the file where the signature is.
 * @return {number} the 32 bit signature
 */
function getSignature(fileContents, position) {
    let signature = fileContents.slice(position, position + 4);
    signature = convertArrayIntoInt(signature);
    for(let s in Enums.Signatures) {
        if(signature === parseInt(s)) {
            return signature;
        }
    }
    return Enums.Signatures.BAD_SIGNATURE;
}
</code></pre>
<p>I want to write a test for this function that tests whether <code>Uint8Array.of(0x04, 0x03, 0x4b, 0x50), 0)</code> returns <code>0x04034b50</code> or <code>Enums.BAD_SIGNATURE</code>. I heard that with unit testing, you don't want to test a function that relies on the output of another function. How do I go about doing this in Jest?</p>
",https://stackoverflow.com/questions/63872226/how-do-i-test-a-function-that-calls-another-function-in-jest,"['javascript', 'jestjs']",1885,True,3,3
How to test an angular component that uses primeng component,"<p>I'll try to keep the code as minimal as possible. I've just started watching lectures on Pluralsight on Unit testing. I've a <code>TimeselectorComponent</code>, on click it should open an overlay with some hard coded text. That overlay is actually <code>p-overlayPanel</code> from <code>primeng</code>. I just want to write a unit test using Jasmine and Karma that when I click on <code>TimeselectorComponent</code> then the overlay should come up. Here's the code:</p>

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

<pre><code>&lt;div (click)=""op.toggle($event)""&gt;
    Click to see the text
&lt;/div&gt;

&lt;div class=""timeselector""&gt;
  &lt;p-overlayPanel #op&gt;
    &lt;div&gt;
      &lt;p&gt;Hello world!&lt;/p&gt;
    &lt;/div&gt;
   &lt;/p-overlayPanel&gt;
&lt;/div&gt;
</code></pre>

<p>Here's my spec file:</p>

<pre><code>import { TestBed, ComponentFixture, async } from ""@angular/core/testing""
import { TimeselectorComponent } from './timeselector.component'
import { Component, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
...

describe('TimeselectorComponent', () =&gt; {
    let fixture: ComponentFixture&lt;TimeselectorComponent&gt;;

    @Component({
        selector: 'p-overlayPanel',
        template: '&lt;div&gt;&lt;/div&gt;'
    })
    class FakePOverlayPanel {
    }

    beforeEach(async(()=&gt;{
        TestBed.configureTestingModule({
            imports: [
                FormsModule
            ],
            providers: [

            ],
            declarations: [
                TimeselectorComponent,
                FakePOverlayPanel
            ]
        });
        fixture = TestBed.createComponent(TimeselectorComponent);

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

    it('should apply filters across dashboards', () =&gt; {
        // assert

        // expect
    })
})
</code></pre>

<p>Please correct me. Is it even testable ? Please help me.</p>
",https://stackoverflow.com/questions/61712214/how-to-test-an-angular-component-that-uses-primeng-component,"['angular', 'karma-jasmine', 'primeng']",1662,True,3,1
Testing function which checks if cookies are enabled with Qunit,"<p>I have the following function which checks if cookies are enabled in a user's browser:</p>
<pre><code>CookiesEnabled: function() {
    var cookieEnabled = navigator.cookieEnabled;
    if (!cookieEnabled) {
        document.cookie = &quot;test_cookie&quot;;
        cookieEnabled = document.cookie.indexOf(&quot;test_cookie&quot;) != -1;
    }

    return cookieEnabled;
},
</code></pre>
<p>I want to unit test that this works using Sinon/Qunit but am unsure of how to approach this properly as I am not very experienced using Sinon or QUnit. Here is my attempt at putting together a test:</p>
<pre><code>QUnit.test(&quot;CookiesEnabled - returns true if user has enabled cookies in their browser&quot;, function (assert) {
    sinon.stub(CookieHelper, &quot;CookiesEnabled&quot;)
         .callsFake(function () {});

    var result = CookieHelper.CookiesEnabled();

    Assert.Equal(result, true);

    CookieHelper.CookiesEnabled.restore();
});
</code></pre>
<p>Please can anyone point me in the right direction for unit testing this method using Qunit and Sinon? Thank you.</p>
<p><strong>UPDATED ATTEMPT:</strong></p>
<pre><code>QUnit.test(&quot;CookiesEnabled - returns true if user has enabled cookies in their browser&quot;, function (assert) {
    sinon.stub(navigator, &quot;cookieEnabled&quot;).callsFake(function () {
        return true;
    });

    var result = CookieHelper.CookiesEnabled();

    assert.equal(result, true);

});
</code></pre>
",https://stackoverflow.com/questions/63471777/testing-function-which-checks-if-cookies-are-enabled-with-qunit,"['javascript', 'unit-testing', 'sinon', 'qunit']",190,True,0,1
Share variable value between tests in Xunit test,"<p>I'm new to unit testing and XUnit. I'm trying to write two test cases. One test is creating an item and the other test is deleting the item.</p>

<pre><code>public class MyTests
{
    string id = string.Empty;

    [Fact]
    public void TestCreate()
    {
        id = MethodToCreateItem();
        Assert.NotNull(id);
    }

    [Fact]
    public void TestDelete()
    {
        bool success = MethodToDeleteItem(id);
        Assert.True(success);
    }
}
</code></pre>

<p>The <code>TestCreate()</code> runs fine. The <code>id</code> is set and the test is successful. However, the test <code>TestDelete()</code> doesn't work. When it gets to that test the value of <code>id</code> is empty.</p>

<p>How can I make it so that the second test has access to the value of <code>id</code> after the first test has ran?</p>
",https://stackoverflow.com/questions/60749741/share-variable-value-between-tests-in-xunit-test,"['c#', 'unit-testing', 'xunit.net']",372,False,0,0
how to rename function after definition,"<p>I want to implement unit testing using the <code>-Wl,--wrap</code> trick, however this doesn't work for functions within the same file. One solution is to rename the function (after it has been defined) to the wrapped one, as suggested here: <a href=""https://stackoverflow.com/a/11758777/526568"">https://stackoverflow.com/a/11758777/526568</a></p>
<p>I came up with the following macro to avoid having to manually define <code>__wrap_foo</code>:</p>
<pre><code>#define UNIT_TEST_SYMBOL(x) \
    typeof(x) __wrap_##x __attribute__((weak, alias(#x)))

void foo(void) {
    /* function body */
}
UNIT_TEST_SYMBOL(foo);

#define foo __wrap_foo

void bar(void) {
    foo();
}
</code></pre>
<p>I then compile with <code>-Wl,--wrap=foo</code>.</p>
<p>Is it possible to avoid having to manually define <code>foo</code> to <code>__wrap_foo</code>? Can this be somehow part of the <code>UNIT_TEST_SYMBOL</code>?</p>
",https://stackoverflow.com/questions/65025583/how-to-rename-function-after-definition,"['c', 'unit-testing', 'gcc', 'linker']",190,False,0,0
Unit testing a Python Azure timer function,"<p>Azure <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#unit-testing"" rel=""nofollow noreferrer"">provide documentation for unit testing HTTP and Queue Python functions</a>. This is done by creating a mock <a href=""https://learn.microsoft.com/de-de/python/api/azure-functions/azure.functions.queuemessage?view=azure-python"" rel=""nofollow noreferrer"">QueueMessage</a> or <a href=""https://learn.microsoft.com/de-de/python/api/azure-functions/azure.functions.httprequest?view=azure-python"" rel=""nofollow noreferrer"">HTTPRequest</a>. However, there is no documentation for creating a unit test for <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=python"" rel=""nofollow noreferrer"">Timer functions</a>.</p>
<p>There is a <a href=""https://learn.microsoft.com/en-us/python/api/azure-functions/azure.functions.timerrequest?view=azure-python"" rel=""nofollow noreferrer"">TimerRequest class</a>, but creating a new instance of it fails with the following error:</p>
<pre><code>req = func.TimerRequest()
</code></pre>
<blockquote>
<p>TypeError: Can't instantiate abstract class TimerRequest with abstract
methods past_due</p>
</blockquote>
<p>What is the correct approach for creating a unit test for a Python Azure timer function?</p>
",https://stackoverflow.com/questions/63355115/unit-testing-a-python-azure-timer-function,"['python', 'azure', 'unit-testing', 'azure-functions']",831,True,0,1
Can there be more abstract unit test cases in Jest?,"<p>I recently started learning unit testing with Jest. I started with the classic FizzBuzz problem. The tutorials I'm seeing, all of them test for specific inputs.</p>
<p>i.e. :</p>
<pre><code>it('returns Fizz for multiples of 3', () =&gt; {
expect(fizzbuzz(6)).toBe('Fizz');
expect(fizzbuzz(9)).toBe('Fizz');
}) 
</code></pre>
<p>And after these 2-3 <code>expect</code> statements, they declare the 'test case handled'.</p>
<p>Question is: Could we write something like this below, for a more abstract approach?</p>
<pre><code>it('returns Fizz for multiples of 3', (num) =&gt; {
if (num % 3 === 0){
expect(fizzbuzz(num)).toBe('Fizz');
}
})
</code></pre>
<p>I tried it and it gives me some errors. It's either myself or this is not a good approach.</p>
<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/63374208/can-there-be-more-abstract-unit-test-cases-in-jest,"['javascript', 'testing', 'jestjs']",36,False,0,0
Karma opens local harddrive path instead of localhost,"<p>We use Karma (Jasmine) for unit-testing our application. 
I am the only one in our dev-team having the problem, that when running the test, a wrong url is opened. Therefore I cannot use the --headless flag as well.</p>

<p>Workaround right now is, to manually replace the url by localhost... </p>

<p>Hours of internet research did not even bring up one similar case.</p>

<p>Reinstalling karma did not change a thing.</p>

<p>Any ideas what else I can do?</p>

<p><a href=""https://i.stack.imgur.com/wPYVh.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wPYVh.png"" alt=""Image showing the url opened""></a></p>
",https://stackoverflow.com/questions/59712805/karma-opens-local-harddrive-path-instead-of-localhost,"['karma-jasmine', 'karma-runner']",42,True,0,1
Angular Unit Testing : Expect undefined to equal true,"<p>I am new in programming and this is the first time im asked to do unit testing in Angular and im a lil bit confused...
I want to test this method in my component.ts:</p>

<pre><code>isInputHidden = true;

showInput(){this.isInputHidden = false;}
</code></pre>

<p>spec.ts : </p>

<pre><code>it('should show the input', () =&gt; {
component.isInputHidden == false;
let showInput = component.showInput();
expect(showInput).toBe(true);
</code></pre>

<p>})</p>

<p>When i run this test i get these errors : In jasmine ==> Expect undefined to equal true.
In Terminal ==>  Argument of type 'true' is not assignable to parameter of type 'Expected'.
Someone can help me to figure out what should i change? </p>
",https://stackoverflow.com/questions/61248430/angular-unit-testing-expect-undefined-to-equal-true,"['angular', 'typescript', 'unit-testing']",2202,True,0,1
How to resolve error in unit testing when we have Date comparison in Codable,"<p>I tried to use custom date strategy in json decoding using <code>Codable</code> as describe in <a href=""https://stackoverflow.com/a/28016692/3477974"">https://stackoverflow.com/a/28016692/3477974</a> . Here is the simplified implementation code:</p>

<pre><code>public extension Formatter {
    static let iso8601: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: ""en_US_POSIX"")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = ""yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX""
        return formatter
    }()
}

public extension Date {
    var iso8601: String {
        return Formatter.iso8601.string(from: self)
    }
}


public extension JSONDecoder.DateDecodingStrategy {
    static let iso8601withFractionalSeconds = custom {
        let container = try $0.singleValueContainer()
        let string = try container.decode(String.self)
        guard let date = Formatter.iso8601.date(from: string) else {
            throw DecodingError.dataCorruptedError(in: container,
                  debugDescription: ""Invalid date: "" + string)
        }
        return date
    }
}


public extension JSONEncoder.DateEncodingStrategy {
    static let iso8601withFractionalSeconds = custom {
        var container = $1.singleValueContainer()
        try container.encode(Formatter.iso8601.string(from: $0))
    }
}
</code></pre>

<p>However, when it comes to unit testing it fails although the error message shows equal value used by <code>description</code> method of date:</p>

<pre><code>    func test_jsonCodable_iso8601() {
        let dates = [Date()] // [""Feb 9, 2020 at 12:55:24 PM""]

        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601withFractionalSeconds
        let data = try! encoder.encode(dates)

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601withFractionalSeconds
        let decodedDates = try! decoder.decode([Date].self, from: data) // [""Feb 9, 2020 at 12:55:24 PM""]

        XCTAssertEqual(dates, decodedDates)
        // fails with error message: [2020-02-09 12:55:24 +0000]"") is not equal to (""[2020-02-09 12:55:24 +0000]""
    }
</code></pre>

<p>Do you have any idea what is the issue and how we can resolve it?</p>

<p>By the way, the actual decodable object is the following one where <code>publishedAt</code> is of type date:</p>

<pre><code>public struct NewsItem: Equatable {
    public let id: UUID
    public let author: String
    public let title: String
    public let description: String
    public let urlToImage: URL?
    public let publishedAt: Date
    public let content: String

    public init(id: UUID,
                author: String,
                title: String,
                description: String,
                urlToImage: URL?,
                publishedAt: Date,
                content: String) {

        self.id = id
        self.author = author
        self.title = title
        self.description = description
        self.urlToImage = urlToImage
        self.publishedAt = publishedAt
        self.content = content
    }
}

extension NewsItem: Decodable {}
</code></pre>
",https://stackoverflow.com/questions/60136982/how-to-resolve-error-in-unit-testing-when-we-have-date-comparison-in-codable,"['swift', 'unit-testing', 'date', 'codable']",617,False,-1,1
How do I unit test Spring Batch partition worker steps?,"<p>I'm familiar with unit testing Spring Batch job steps (and entire jobs), but am wondering if there is a way to unit test a ""worker"" step for a partition (without testing the whole partition step).</p>

<p>The thing I'm puzzling over is that typically a unit test for a step would call:</p>

<p><code>JobLauncherTestUtils.launchStep(stepName, jobParameters, jobExecutionContext)</code></p>

<p>But, this being a worker step within a partition, I need some way of also passing in a StepExecutionContext. Is there a way to do that?</p>
",https://stackoverflow.com/questions/61122058/how-do-i-unit-test-spring-batch-partition-worker-steps,"['unit-testing', 'spring-batch']",474,True,0,1
how to mock aws service in unit tests in loopback4,"<p>I want to mock AWS service in unit tests , we already have aws service used in controller but how to make mock service of aws and replace the working of actual service to mock service to get values on which my entity depends in unit tests</p>

<pre><code>async create(entity: Template, options?: Options): Promise&lt;Template&gt; {
    await this.businessUnitRepository.findById(entity.businessUnitId);
    entity.body = _.unescape(entity.body);
    const response = await this.pinpointService
      .saveEmailTemplate(
        entity.name,
        entity.subject,
        entity.body,
        entity.description ?? '',
      )
      .catch(error =&gt; {
        throw error;
      });
    let key;
    try {
      key = await this.lambdaService.saveEmailTemplate(
        `${entity.name}-v1`,
        TemplateService.getPDFContent(entity.subject, entity.body),
      );
    } catch (LambdaError) {
      await this.pinpointService.deleteEmailTemplate(entity.name);
      throw LambdaError;
    }
    try {
      if (response.CreateTemplateMessageBody.Arn) {
        entity.arn = response.CreateTemplateMessageBody.Arn;
      }
      if (key) {
        entity.key = key;
      }
      entity.version = '1';
      return await this.templateRepository.create(entity, options);
    } catch (error) {
      if (error.code === DbErrorsEnum.Conflict) {
        throw new HttpErrors.Conflict(ErrorKeys.NameAlreadyExist);
      }
      await this.s3Service.deleteEmailTemplate(key);
      await this.pinpointService.deleteEmailTemplate(entity.name);
      throw error;
    }
  }
</code></pre>

<p>Create function uses 2 AWS services pinpoint and lambda which returns ARN and KEY , but how to get these values in unit testing , as while testing aws can't be mocked</p>
",https://stackoverflow.com/questions/61254269/how-to-mock-aws-service-in-unit-tests-in-loopback4,"['unit-testing', 'amazon-s3', 'aws-lambda', 'loopback4', 'aws-pinpoint']",135,False,0,0
jasmine stub to throw an object instead of a string,"<p>I'm unit testing a component on Angular. Here I'm calling a function from an external service and artificially throwing an error in order to test how the component handles the error.</p>

<p>To do so, I need my error to be something like that 
<code>{ statusCode: 401, code: 'LOGIN_FAILED' }</code></p>

<p>However, the Jasmine throwError method only throws a single string passed as an argument. Is there a workaround or a method I don't know so I can throw an object?</p>

<p>Here is my code so far:</p>

<pre><code>fit('should display error message if login failure', () =&gt; {
    // should throw ({ statusCode: 401, code: 'LOGIN_FAILED' });
    const spyLogin = spyOn(appUserApi, 'loginUser').and.throwError('test');  
    fillForm('toto@gmail.com', '1234');
    submitForm();
    // expect stuff here
  });
</code></pre>
",https://stackoverflow.com/questions/59756035/jasmine-stub-to-throw-an-object-instead-of-a-string,"['angular', 'jasmine', 'karma-jasmine']",207,True,0,1
Unable to override MockStore,"<p>I used provideMockStore for unit testing more than one selector. I need to override the MockStore for one of the test cases. Code is as follows. It is not overriding the store. I have seen documentation there it is mentioned that mockStore = TestBed.inject(MockStore). It throws error that reads ""Property 'inject' doesn't exist on type 'TestBedStatic'
""@angular/cli"": ""~8.2.1"",
    ""@ngrx/core"": ""^1.2.0"",
        ""@ngrx/effects"": ""^8.2.0"",
        ""@ngrx/entity"": ""^8.2.0"",
        ""@ngrx/router-store"": ""^8.2.0"",
        ""@ngrx/schematics"": ""^8.2.0"",
        ""@ngrx/store"": ""^8.2.0"",</p>

<pre><code>beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [
                RegisteredOwnerContainerComponent,
                RegisteredOwnerComponent,
                AddVehicleTitleComponent,
                SidePanelContentComponent,
                ExplanationComponent
            ],
            imports: [
                FlexLayoutModule,
                FormsModule,
                ReactiveFormsModule,
                MaterialModule,
                HttpClientTestingModule,
                BrowserAnimationsModule,
                LoggerModule.forRoot({ level: NgxLoggerLevel.INFO, disableConsoleLogging: false })
            ],
            providers: [
                { provide: ActivatedRoute, useValue: mockActivateRoute },
                { provide: Router, useValue: mockRouter },
                {
                    provide: EndorsementStateService,
                    useValue: {
                        navigateToNextStep: jasmine.createSpy('navigateToNextStep')
                    }
                },
                provideMockStore({
                    selectors: [
                        { selector: currentPolicySelector, value: currentPolicy },
                        { selector: currentVehicleSelector, value: currentVehicle }
                    ],
                }),
                CookieService
            ],
        }).compileComponents();
    }));

    beforeEach(async(() =&gt; {
        fixture = TestBed.createComponent(RegisteredOwnerContainerComponent);
        component = fixture.componentInstance;
        mockedStore = TestBed.get(Store);
        mockService = TestBed.get(EndorsementStateService);

        // mockedStore.select = jasmine.createSpy('select');
    }));

it('should return empty driver array if no PNI and SNI exist', fakeAsync(() =&gt; {
        mockedStore.overrideSelector(currentPolicySelector, currentPolicyWithoutPNIAndWithoutSNI);
        fixture.detectChanges();
    }));
</code></pre>
",https://stackoverflow.com/questions/60672156/unable-to-override-mockstore,"['angular', 'ngrx']",1198,True,0,1
How to override a selector with multiples observables instead of one in order to distinct?,"<p>I have an effect that is using the latest from a selector that is returning an object, but I want to pass the unit testing loading multiples observables from a selector that only retrieve one selector.</p>

<pre><code> public uniqueMovies$ = createEffect(() =&gt;
   this.actions$.pipe(
      ofType(loadSavedMovies),
      combineLastest(
          this.store.pipe(
              select(getSaveMoviesSelector),
              distinctUntilChanged((prev, curr) =&gt; prev.SKU === curr.SKU)
          )
      )
      switch(([_action, currentMovies]) =&gt; {
          return this.moviesServices.getUniqueData(currentMovies.SKU)
      }),
      map( movie =&gt; loadUniqueMovie(movie))
   )
 )

</code></pre>

<p>The current unit test only accepts one object, I need to retrieve a <strong>from[{ SKU: 'QMO3434O'}, { SKU: 'QMO3434O'}, { SKU: 'ZOP3434O'}]</strong> with <strong>from</strong> operator in order to pass the <strong>distinctUntilChanged</strong>.</p>

<pre><code>   mockStore.overrideSelector(getSaveMoviesSelector, { SKU: 'QMO3434O'} as CurrentMovie)
   moviesServicesSpy.getUniqueData.and.returnValue(of({ SKU: 'QMO3434O', name: 'Matrix' } as Movie))

   action$ = hot('a', {
     a: loadSavedMovies()
   })

   const exp = cold( 'z',  {
     z: loadUniqueMovie({ SKU: 'QMO3434O', name: 'Matrix' } as Movie)
   })

   expect(effect.uniqueMovies$).toBeObservable(exp)

</code></pre>

<p>What is the better way to return multiples observables from the selector.</p>
",https://stackoverflow.com/questions/62210644/how-to-override-a-selector-with-multiples-observables-instead-of-one-in-order-to,"['javascript', 'angular', 'unit-testing', 'rxjs', 'ngrx-effects']",254,True,0,1
Exclude SwiftUI previews from code coverage?,"<p>I'm having trouble getting my code coverage up to min. 90% because XCode takes the PreviewProvider into account.</p>
<p>What should I do? Remove all the SwiftUI previews? Or is there a way I can exclude some lines with 'PreviewProvider' keywords etc.</p>
<p>Xcode ver 12.0
Jenkins for CI
slather &amp; cobertura for code coverage</p>
<p>Side question, there is no official test suite available for unit testing SwiftUI components. Do you guys not test them at all, or use third party libraries? I've been using ViewInspector but i dislike that to track the updated state of the component, I need to include testing code in the actual codebase itself.</p>
",https://stackoverflow.com/questions/64604164/exclude-swiftui-previews-from-code-coverage,"['swift', 'xcode', 'swiftui', 'cobertura']",2480,True,19,1
Unit testing using Jest and Enzym in React Native,"<p>How can I find element inside component with jest and enzyme?</p>

<p>Let say, I have 1 component parent (Login) and 2 child component (Title and Form), so in component Login, I want to find is there TextInput element inside Form component or something else maybe another element inside Form Component, with jest and enzyme, then how can I get that just with 1 unit testing (Login.test.js)?</p>

<p>This is my login component for the ilustration</p>

<pre><code>&lt;Login&gt;
  &lt;Title title='Login Page' /&gt;
  &lt;Form 
     email={this.state.email}
     password={this.state.password}
  /&gt;
&lt;/Login&gt;
</code></pre>

<p>Title Component</p>

<pre><code>&lt;Text&gt;{this.props.title}&lt;/Text&gt;
</code></pre>

<p>Form Component</p>

<pre><code>&lt;View&gt;
  &lt;TextInput value={this.props.email} placeHolder=""Your Email"" /&gt;
  &lt;TextInput value={this.props.password} placeHolder=""Your Password"" /&gt;
&lt;/View&gt;
</code></pre>

<p>This is my current Login.test.js</p>

<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import Login from './Login';
import renderer from 'react-test-renderer';

describe('Login', () =&gt; {
  const wrapper = shallow(&lt;Login /&gt;);
  const instaceOf = wrapper.instance();

  it('renders correctly', () =&gt; {
    const rendered = renderer.create(&lt;Login /&gt;).toJSON();
    expect(rendered).toBeTruthy();
  });

  it('should render the Text Input Element', () =&gt; {
    let form = wrapper.find('Form');
    expect(form.find('TextInput""]')).toHaveLength(2);
  });
});
</code></pre>
",https://stackoverflow.com/questions/59798888/unit-testing-using-jest-and-enzym-in-react-native,"['react-native', 'jestjs', 'enzyme']",759,False,2,1
Python Unittest: Unit test the message passed in raised exception,"<p>I am unit testing the radius of the circle using unittest framework in Python. If the radius is not a numeric value, then I raise and exception with a custom message.</p>

<p>File: circle.py</p>

<pre><code>class Circle():

    def __init__(self, radius):
        if not isinstance (radius, (int,float)):
            raise TypeError('radius must be a number')
        else:
            self.radius = radius
</code></pre>

<p>File: test_circle.py</p>

<pre><code>import unittest
from circle import Circle

class CircleTest(unittest.TestCase):

    def test_radius(self):
        c1 = Circle(2.5)
        self.assertEqual(c1.radius, 2.5)

    def test_radius_type(self):
        self.assertRaises(TypeError, Circle, 'hello')

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

<p>Now, I can check the raised exception. But, I also want to find if the message passed in the exception is the exact message or not. Could anyone please guide me how to test and check the message passed in the exception in unittest in Python?</p>
",https://stackoverflow.com/questions/61061723/python-unittest-unit-test-the-message-passed-in-raised-exception,"['python', 'unit-testing', 'python-unittest']",4798,True,2,1
Should I avoid try catch in every single async/await on Node js?,"<p>This is a design question that came up to me while unit testing.
Let's dive into the example:</p>
<p>Imagine this:</p>
<pre class=""lang-js prettyprint-override""><code>async function foo() {
    try {
        return apiCall()
    }
    catch (e) {
        throw new CustomError(e);
    } 
}



async function bar() {
    return foo()
}



async function main() {
    try {
        await bar()
    }catch(e) {
        console.error(e)
    }
}

main()
</code></pre>
<p>What do we see here? That the only function that hasn't got a try-catch block is bar.
But if foo fails, it should get catched by the main catch.</p>
<p>While unittesting this like</p>
<pre class=""lang-js prettyprint-override""><code>describe('testing bar', () =&gt; {
    it('foo should throw', () =&gt; {
        foo.mockImplementantion(() =&gt; { throw new CustomError('error')});
        bar()
        .then((result) =&gt; console.log(result))
        .catch((err) =&gt; { exepect(err).toBeInstanceOf(CustomError)}) // this is what we are testing
    })
})
</code></pre>
<p>The output we see is that an <strong>Unhandled promise rejection</strong> is logged in the console.</p>
<p>So, my question is... even if I know that the <code>main()</code> will catch the error, should I use try-catch block inside all async functions?</p>
",https://stackoverflow.com/questions/63251622/should-i-avoid-try-catch-in-every-single-async-await-on-node-js,"['javascript', 'node.js', 'async-await', 'jestjs']",8202,True,7,3
Jest coverage report in html missing coverage values,"<p>I am unit testing my ReactJS app with Jest and have added configuration to get the code coverage. The coverage works well on cli but when I try to export coverage report as html the values corresponding to each file are not shown in the report. Here is my jest.config.json:</p>

<pre><code>{
    ""roots"": [
        ""test""
    ], 
    ""collectCoverage"": true,
    ""coverageReporters"": [""text"",""html""],
    ""coverageDirectory"": ""&lt;rootDir&gt;/coverage/""
}
</code></pre>

<p>And here is my report generated in coverage folder inside index.html file:</p>

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

<p>As can be seen the numbers are missing. What coud be the reason when the text report has correct values shown as well. It happens only with html report.</p>
",https://stackoverflow.com/questions/59807568/jest-coverage-report-in-html-missing-coverage-values,"['reactjs', 'unit-testing', 'jestjs', 'code-coverage']",3206,True,7,1
Angular Unit testing - Reactive Form value not updating,"<p>I am new to angular unit testing. 
Test Scenario: The form view value in the html is equal to the component form value.
The email value is retrieved by a shared value and being used in the component registration form. I could retrieve the email value from the component using the reactive forms, but when trying to access via the native element, it gives empty. 
Below is the component.ts</p>

<pre><code>ngOnit(public serviceEmail) {
    this.assignEmailAvailable();
    this.createRegistration();

    }
assignEmailAvailable() {
 if(service.email){
    this.email = serviceEmail.email;
  }
 }   
createRegistration() {
   this.registerForm = new FormGroup({
       email:new FormControl({value:this.email})
    })
}
</code></pre>

<p>In the component.spec.ts, I am gonna call this function and check whether both values are same.
component.spec.ts</p>

<pre><code> beforeEach(() =&gt; {
    fixture = TestBed.createComponent(RegisterComponent);
    component = fixture.componentInstance;
    service = TestBed.get(serviceEmail);
  });
it('Registration Form Creation', fakeAsync(() =&gt; {
    service.email = ""dsf@gmail.com"";

    fixture.detectChanges();

    component.assignEmailAvailable();
    component.createRegisterForm();

    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
    const email = fixture.debugElement.query(By.css('input[id=""email""]')).nativeElement;
//The value is empty even after creating the form using the component function
    expect(email.value).toBe(component.emailValue);
    });
//THis returns me the value set
    expect(component.registerForm.get('email').value).toBe(component.emailValue);
  }));
</code></pre>
",https://stackoverflow.com/questions/59638229/angular-unit-testing-reactive-form-value-not-updating,"['angular', 'unit-testing', 'karma-jasmine', 'angular-reactive-forms']",8462,True,4,2
How can I unit test Android resources in feature modules?,"<p>My app is using feature modules. One of the feature modules declares a bunch of strings in an xml resource, and then accesses them from my kotlin code: e.g. <code>getString(R.string.dialog_title)</code>.  I want to run Junit tests to prove that the correct string content is retrieved.</p>
<p>The <a href=""http://robolectric.org/androidx_test/"" rel=""nofollow noreferrer"">Robolectric documentation page</a> suggests using the function <code>getApplicationContext&lt;MyApplication&gt;()</code>.  However, you don't have access to the  Application when unit testing a feature module.  I guess that's because feature modules exist separately to the application?</p>
<p>Any help appreciated. :)</p>
",https://stackoverflow.com/questions/64929137/how-can-i-unit-test-android-resources-in-feature-modules,"['android', 'unit-testing', 'android-resources', 'androidx', 'robolectric']",362,False,1,1
Right way to implement mongo go driver interfaces,"<p>I'm trying to write interfaces for mongo go driver to write unit test for my post_repo.go, but have this error:</p>
<pre><code>cannot use redditclone (type *mongo.Database) as type newPosts.DatabaseHelper in argument to newPosts.NewPostsDatabase:
    *mongo.Database does not implement newPosts.DatabaseHelper (wrong type for Client method)
        have Client() *mongo.Client
        want Client() newPosts.ClientHelper
</code></pre>
<p>my interface file, took it from this post <a href=""https://medium.com/better-programming/unit-testing-code-using-the-mongo-go-driver-in-golang-7166d1aa72c0"" rel=""nofollow noreferrer"">https://medium.com/better-programming/unit-testing-code-using-the-mongo-go-driver-in-golang-7166d1aa72c0</a>:</p>
<pre><code>package newPosts

import (
    &quot;context&quot;
    &quot;rc/pkg/config&quot;

    // &quot;localhost/medium-mongo-go-driver/config&quot;

    &quot;go.mongodb.org/mongo-driver/mongo&quot;
    &quot;go.mongodb.org/mongo-driver/mongo/options&quot;
)

type DatabaseHelper interface {
    Collection(name string) CollectionHelper
    Client() ClientHelper
}

type CollectionHelper interface {
    FindOne(context.Context, interface{}) SingleResultHelper
    InsertOne(context.Context, interface{}) (interface{}, error)
    DeleteOne(ctx context.Context, filter interface{}) (int64, error)
}

type SingleResultHelper interface {
    Decode(v interface{}) error
}

type ClientHelper interface {
    Database(string) DatabaseHelper
    Connect() error
    StartSession() (mongo.Session, error)
}

type mongoClient struct {
    cl *mongo.Client
}
type mongoDatabase struct {
    db *mongo.Database
}
type mongoCollection struct {
    coll *mongo.Collection
}

type mongoSingleResult struct {
    sr *mongo.SingleResult
}

type mongoSession struct {
    mongo.Session
}

func NewClient(cnf *config.Config) (ClientHelper, error) {
    c, err := mongo.NewClient(options.Client().SetAuth(
        options.Credential{
            Username:   cnf.Username,
            Password:   cnf.Password,
            AuthSource: cnf.DatabaseName,
        }).ApplyURI(cnf.URL))

    return &amp;mongoClient{cl: c}, err

}

func NewDatabase(cnf *config.Config, client ClientHelper) DatabaseHelper {
    return client.Database(cnf.DatabaseName)
}

func (mc *mongoClient) Database(dbName string) DatabaseHelper {
    db := mc.cl.Database(dbName)
    return &amp;mongoDatabase{db: db}
}

func (mc *mongoClient) StartSession() (mongo.Session, error) {
    session, err := mc.cl.StartSession()
    return &amp;mongoSession{session}, err
}

func (mc *mongoClient) Connect() error {
    // mongo client does not use context on connect method. There is a ticket
    // with a request to deprecate this functionality and another one with
    // explanation why it could be useful in synchronous requests.
    // https://jira.mongodb.org/browse/GODRIVER-1031
    // https://jira.mongodb.org/browse/GODRIVER-979
    return mc.cl.Connect(nil)
}

func (md *mongoDatabase) Collection(colName string) CollectionHelper {
    collection := md.db.Collection(colName)
    return &amp;mongoCollection{coll: collection}
}

func (md *mongoDatabase) Client() ClientHelper {
    client := md.db.Client()
    return &amp;mongoClient{cl: client}
}

func (mc *mongoCollection) FindOne(ctx context.Context, filter interface{}) SingleResultHelper {
    singleResult := mc.coll.FindOne(ctx, filter)
    return &amp;mongoSingleResult{sr: singleResult}
}

func (mc *mongoCollection) InsertOne(ctx context.Context, document interface{}) (interface{}, error) {
    id, err := mc.coll.InsertOne(ctx, document)
    return id.InsertedID, err
}

func (mc *mongoCollection) DeleteOne(ctx context.Context, filter interface{}) (int64, error) {
    count, err := mc.coll.DeleteOne(ctx, filter)
    return count.DeletedCount, err
}

func (sr *mongoSingleResult) Decode(v interface{}) error {
    return sr.sr.Decode(v)
}
</code></pre>
<p>my post_repo.go file:</p>
<pre><code>package newPosts

import (
    &quot;context&quot;
    // &quot;localhost/medium-mongo-go-driver/models&quot;
)

const collectionName = &quot;posts&quot;

// PostsDatabase user database representation to find, update, delete users
type PostsDatabase interface {
    FindOne(context.Context, interface{}) (*Post, error)
    Create(context.Context, *Post) error
    DeleteByUsername(context.Context, string) error
}

type postsDatabase struct {
    // db *mongo.Database
    db DatabaseHelper
}

// NewPostsDatabase creates new user database instance
func NewPostsDatabase(db DatabaseHelper) PostsDatabase {
    return &amp;postsDatabase{
        db: db,
    }
}

func (u *postsDatabase) FindOne(ctx context.Context, filter interface{}) (*Post, error) {
    user := &amp;Post{}
    err := u.db.Collection(collectionName).FindOne(ctx, filter).Decode(user)
    if err != nil {
        return nil, err
    }
    return user, nil
}

func (u *postsDatabase) Create(ctx context.Context, usr *Post) error {
    _, err := u.db.Collection(collectionName).InsertOne(ctx, usr)
    return err
}

func (u *postsDatabase) DeleteByUsername(ctx context.Context, username string) error {
    // In this case it is possible to use bson.M{&quot;username&quot;:username} but I tend
    // to avoid another dependency in this layer and for demonstration purposes
    // used omitempty in the model
    author := &amp;Author{Username: username}
    post := &amp;Post{
        Author: author,
    }
    _, err := u.db.Collection(collectionName).DeleteOne(ctx, post)
    return err
}
</code></pre>
<p>My posts_repo_test.go tests works fine, but only if I pass newPosts.DatabaseHelper in function newPosts.NewPostsDatabase(). I guess I need to pass *mongo.Database for my program works.</p>
<p>Maybe I misunderstanding how works unit tests.
Any help</p>
",https://stackoverflow.com/questions/65108509/right-way-to-implement-mongo-go-driver-interfaces,"['mongodb', 'unit-testing', 'go', 'mocking', 'mongo-go-driver']",666,False,1,0
Creating mocks for unit test - retrofit,"<p>There is commandline app to show tomorrow's forecast using a public API</p>
<p>Sample output could be as follows:</p>
<pre><code>Tomorrow (2019/05/01) in city XYZ:
Clear
Temp: 26.5 °C
Wind: 7.6 mph
Humidity: 61%
</code></pre>
<p>Question : How will you create a test case such that tests should not touch the real service and work without the Internet.</p>
<p>I tried creating the junit test for the same and its working fine till the time i am using the api directly.</p>
<p>Can someone please help how can i create a mock for my unit testing.</p>
<p>App.java</p>
<pre><code>import api.ForecastServiceImpl;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.time.LocalDate;

public class App {

    public static void main(String[] args) throws IOException {
        if (args.length &lt; 1) {
            System.out.println(&quot;Pass city name as an argument&quot;);
            System.exit(1);
        }

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(&quot;https://www.metaweather.com&quot;)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        LocalDate tomorrow = LocalDate.now().plusDays(1);

        ForecastServiceImpl service = new ForecastServiceImpl(retrofit);
        System.out.println(service.getForecast(args[0], tomorrow));
    }
}
</code></pre>
<p>ForecastServiceImpl.java</p>
<pre><code>package api;

import model.City;
import model.Forecast;
import retrofit2.Call;
import retrofit2.Retrofit;
import util.PathDate;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

public class ForecastServiceImpl {

    private Retrofit retrofit;

    public ForecastServiceImpl(Retrofit retrofit) {
        this.retrofit = retrofit;
    }

    public String getForecast(String cityName, LocalDate date) throws IOException {
        PathDate pathDate = new PathDate(date);

        ForecastService service = retrofit.create(ForecastService.class);
        Call&lt;List&lt;City&gt;&gt; findCityCall = service.findCityByName(cityName.toLowerCase());
        City city = Objects.requireNonNull(findCityCall.execute().body())
                .stream()
                .findFirst()
                .orElseThrow(() -&gt; new RuntimeException(String.format(&quot;Can't find city id for %s&quot;, cityName)));

        Call&lt;List&lt;Forecast&gt;&gt; forecastCall = service.getForecast(city.getWoeid(), pathDate);
        Forecast forecast = Objects.requireNonNull(forecastCall.execute().body())
                .stream()
                .findFirst()
                .orElseThrow(() -&gt; new RuntimeException(String.format(&quot;Can't get forecast for %s&quot;, cityName)));

        return String.format(&quot;Weather on (%s) in %s:\n%s&quot;, pathDate, city.getTitle(), forecast);
    }
}
</code></pre>
<p>ForecastService.java</p>
<pre><code>package api;

import model.City;
import model.Forecast;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import util.PathDate;

import java.util.List;

public interface ForecastService {

    @GET(&quot;/api/location/{city_id}/{date}/&quot;)
    Call&lt;List&lt;Forecast&gt;&gt; getForecast(@Path(&quot;city_id&quot;) Long cityId, @Path(&quot;date&quot;) PathDate date);

    @GET(&quot;/api/location/search/&quot;)
    Call&lt;List&lt;City&gt;&gt; findCityByName(@Query(&quot;query&quot;) String city);
}
</code></pre>
<p>City.java</p>
<pre><code>package model;

public class City {

    private String title;
    private Long woeid;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Long getWoeid() {
        return woeid;
    }

    public void setWoeid(Long woeid) {
        this.woeid = woeid;
    }
}
</code></pre>
<p>Forecast.java</p>
<pre><code>package model;

import com.google.gson.annotations.SerializedName;

public class Forecast {

    private Long id;
    @SerializedName(&quot;weather_state_name&quot;)
    private String weatherState;
    @SerializedName(&quot;wind_speed&quot;)
    private Double windSpeed;
    @SerializedName(&quot;the_temp&quot;)
    private Double temperature;
    private Integer humidity;

    public Long getId() {
        return id;
    }

    public Forecast setId(Long id) {
        this.id = id;
        return this;
    }

    public String getWeatherState() {
        return weatherState;
    }

    public Forecast setWeatherState(String weatherState) {
        this.weatherState = weatherState;
        return this;
    }

    public Double getWindSpeed() {
        return windSpeed;
    }

    public Forecast setWindSpeed(Double windSpeed) {
        this.windSpeed = windSpeed;
        return this;
    }

    public Double getTemperature() {
        return temperature;
    }

    public Forecast setTemperature(Double temperature) {
        this.temperature = temperature;
        return this;
    }

    public Integer getHumidity() {
        return humidity;
    }

    public Forecast setHumidity(Integer humidity) {
        this.humidity = humidity;
        return this;
    }

    @Override
    public String toString() {
        return String.format(&quot;%s\nTemp: %.1f °C\nWind: %.1f mph\nHumidity: %d%%&quot;,
                weatherState, temperature, windSpeed, humidity);
    }
}

</code></pre>
<p>PathDate.java</p>
<pre><code>package util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class PathDate {

    private final LocalDate date;

    public PathDate(LocalDate date) {
        this.date = date;
    }

    @Override public String toString() {
        return date.format(DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd&quot;));
    }
}
</code></pre>
<p>Utils.java</p>
<pre><code>package util;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Utils {

    public static byte[] readResourceFileToBytes(String filename) {
        byte[] fileBytes = new byte[0];
        try {
            Path path = Paths.get(Utils.class.getClassLoader().getResource(filename).toURI());
            fileBytes = Files.readAllBytes(path);
        } catch (URISyntaxException|IOException|NullPointerException e) {
            e.printStackTrace();
        }

        return fileBytes;
    }
}

</code></pre>
",https://stackoverflow.com/questions/64181410/creating-mocks-for-unit-test-retrofit,"['java', 'api', 'mocking', 'retrofit']",485,True,1,1
How do I make my vue-unit-test trigger a click event on v-btn in Vuetify?,"<p>I am creating some unit test for my component, but the test keeps failing, since the button I'm testing
keeps not getting triggerd by a click-event.</p>

<p>I've used the docs as a foundation for my test: <a href=""https://vuetifyjs.com/sv-SE/getting-started/unit-testing/"" rel=""nofollow noreferrer"">https://vuetifyjs.com/sv-SE/getting-started/unit-testing/</a></p>

<p>I've also tried some of the suggestions mentioned here: <a href=""https://forum.vuejs.org/t/how-to-trigger-an-onchange-event/11081/4"" rel=""nofollow noreferrer"">https://forum.vuejs.org/t/how-to-trigger-an-onchange-event/11081/4</a></p>

<p>But it seems like I'm missing something, anyone who can help me out?</p>

<p>My test:</p>

<pre><code>test('If you can click on the Test button', () =&gt; {
        const wrapper = shallowMount(myComponent, {
            localVue,
            vuetify,

        });

        const event = jest.fn();
        const button = wrapper.find({name: 'v-btn'})

        expect(button.exists()).toBe(true) //this works

         wrapper.vm.$on('v-btn:clicked', event)

        expect(event).toHaveBeenCalledTimes(0)

         button.trigger('click')

         expect(event).toHaveBeenCalledTimes(1)

    })
</code></pre>

<p>myComponent:</p>

<pre><code>&lt;template&gt;

&lt;v-btn class=""primary-text"" @click.native=""methodForTesting($event)""&gt;Test&lt;/v-btn&gt;

&lt;template&gt;

&lt;script&gt;
methods: {

methodForTesting(){
  console.log('button clicked!')
}
&lt;/script&gt;
</code></pre>
",https://stackoverflow.com/questions/60852274/how-do-i-make-my-vue-unit-test-trigger-a-click-event-on-v-btn-in-vuetify,"['jestjs', 'vuetify.js', 'vue-test-utils']",4519,True,1,1
Correct usage of assertRaises in Python unit tests,"<p>I'm trying to figure out how to correctly use <code>assertRaises()</code> in Python unit testing. I have a <code>ValueError</code> in my function that gets raised. However, when testing in my unit tests, I'm getting mixed results with two different ways of using `assertRaises().</p>

<p>When I write the test like this, it works:</p>

<pre><code>import unittest

class MyTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        pass

    def test_error(self):
        with self.assertRaises(ValueError):
            func(a)
</code></pre>

<p>However, if I write my test like below, it does not work even though the <code>ValueError</code> gets raised:</p>

<pre><code>    def test_error(self):
        self.assertRaises(ValueError, func(a))
</code></pre>

<p>Does anyone have any insight as to why one way would work and the other wouldn't?</p>
",https://stackoverflow.com/questions/61200972/correct-usage-of-assertraises-in-python-unit-tests,"['python-3.x', 'unit-testing', 'testing', 'python-unittest']",366,True,1,1
Unit Testing UseState when its Setter function is passed to a Child Component,"<p>Below I have a an example of UseState hook where its setter function (<strong>setInputs</strong>) is passed down to a child component (<strong>LoginForm</strong>).</p>
<p>I am having trouble with Unit Testing where I cannot simulate a change to <code>setInputs</code> and thereby cannot assert that the dispatch is called.</p>
<p>How can I simulate a change to the <code>setInputs</code> prop in order to update the <code>inputs</code> state in my Test?</p>
<p><strong>Component:</strong></p>
<pre><code>const Login = () =&gt; {
  const [inputs, setInputs] = useState({ email: '' });

  const handleSubmit = event =&gt; {
    event.preventDefault();

    if (!inputs.email) {
      return;
    }
    // Cannot Assert this
    dispatch(requestAuthentication(inputs.email));
  };

  return (
    &lt;LoginForm
      setInputs={setInputs}
      handleSubmit={handleSubmit}
    /&gt;
  );
};

export default Login;
</code></pre>
<p>**Login Form **</p>
<p>Is a basic form than onChange of an input calls the following function</p>
<pre><code>const handleInputChange = event =&gt; {
    event.persist();

    props.setInputs(input =&gt; ({
      ...input,
      [event.target.name]: event.target.value,
    }));
  };
</code></pre>
<p><strong>Unit Test:</strong></p>
<pre><code>it('should return if no email is entered', () =&gt; {
    useDispatch.mockImplementation(() =&gt; jest.fn());
    useSelector.mockImplementation(() =&gt; jest.fn());

    requestAuthentication.mockImplementation((data, callback) =&gt; {
      callback();
    });

    const wrapper = shallow(
      &lt;Login&gt;
        &lt;LoginForm {...props} /&gt;
      &lt;/Login&gt;
    );

    wrapper
      .find('LoginForm')
      .props()
      .handleSubmit({
        preventDefault: () =&gt; {},
      });
    expect(requestAuthentication).not.toHaveBeenCalled();
  });
</code></pre>
",https://stackoverflow.com/questions/65135555/unit-testing-usestate-when-its-setter-function-is-passed-to-a-child-component,"['javascript', 'jestjs', 'use-state']",376,False,1,0
Why is a dist folder being created in all the directories in my local repository,"<p>I am working on a project which is using Apollo graphql server, Unit testing frameworks like Mocha, Chai, Sinon and nyc.</p>
<p>I really don't understand why does my project creates a <code>dist</code> folder in all the directory in the project after every few minutes on save. I have never seen this behaviour in any of my other local repositories.</p>
<p>I can't find this on any forums. Is it because of the Apollo graphql server I am using?</p>
<p>my script looks like this</p>
<pre><code>  &quot;scripts&quot;: {
    &quot;lint&quot;: &quot;npx standard&quot;,
    &quot;test:unit&quot;: &quot;mocha test/**&quot;,
    &quot;coverage&quot;: &quot;nyc --reporter=text --reporter=cobertura mocha test/**&quot;,
    &quot;lint:fix&quot;: &quot;npx standard --fix&quot;,
    &quot;dev&quot;: &quot;nodemon index.js&quot;,
    &quot;start&quot;: &quot;node index.js&quot;,
    &quot;crypto&quot;: &quot;node test.js&quot;
  },
</code></pre>
",https://stackoverflow.com/questions/64369605/why-is-a-dist-folder-being-created-in-all-the-directories-in-my-local-repository,"['node.js', 'unit-testing', 'express', 'graphql']",231,False,1,0
Element still defined even though *ngIf is false Jasmine unit testing Angular,"<p>I'm completely new to unit testing, so I may just be doing everything wrong here. I'm using *ngIf to display a data grid from DevExpress once my GET request completes, and I'm trying to verify with the Jasmine test that it only is displayed once my *ngIf condition is set to true.</p>
<p>A truncated version of my grid:</p>
<pre><code>
    &lt;dx-data-grid #grid *ngIf=&quot;!loading&quot;&gt;
        ...
    &lt;/dx-data-grid&gt;

</code></pre>
<p>and my .spec file:</p>
<pre><code>import { ApplicationsComponent } from &quot;./applications.component&quot;;
import { ComponentFixture, async, TestBed } from &quot;@angular/core/testing&quot;;
import { RouterTestingModule } from &quot;@angular/router/testing&quot;;
import { HttpClientTestingModule } from &quot;@angular/common/http/testing&quot;;
import { DxDataGridModule } from &quot;devextreme-angular&quot;;
import { DebugElement } from &quot;@angular/core&quot;;
import { By } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

describe(&quot;ApplicationPocComponent&quot;, () =&gt; {
  let component: ApplicationsComponent;
  let fixture: ComponentFixture&lt;ApplicationsComponent&gt;;
  let el: DebugElement;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ApplicationsComponent],
      imports: [RouterTestingModule, HttpClientTestingModule, DxDataGridModule, CommonModule ],
    })
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(ApplicationsComponent);
        component = fixture.componentInstance;
        el = fixture.debugElement; 
      });
  }));

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

  it(&quot;should display the data grid&quot;, () =&gt; { 
    component.loading = true; 
    fixture.detectChanges(); 
    const dataGrid = el.queryAll(By.css(&quot;#grid&quot;)); 
    expect(dataGrid).toBeTruthy(&quot;Datagrid not created&quot;); 
    expect(dataGrid).toBeNull(&quot;Datagrid is created&quot;); 
  })
});
</code></pre>
<p>My first assertion, <code>expect(dataGrid).toBeTruthy()</code> succeeds, whereas the assertion <code>.toBeNull()</code> fails. This is the opposite of what I expected, what am I missing here?</p>
",https://stackoverflow.com/questions/63041732/element-still-defined-even-though-ngif-is-false-jasmine-unit-testing-angular,"['angular', 'jasmine', 'angular-ng-if']",1781,True,1,2
"Unit Testing Using Jest and AWS-SDK-Mock, Mock DynamoDB Scan","<p>Jumping into Jest and unit testing lambda functions.  I'm trying to mock the aws dynamodb-document client scan in my unit test.  I'm getting back the actual scan from the real db though so i know something with my mock isn't working.  This is my .test.js:</p>
<pre><code>var AWS = require('aws-sdk-mock');
const sinon = require('sinon');
let index = require('./index.js');


beforeEach(()=&gt; {
    AWS.mock('DynamoDB.DocumentClient', 'scan', function(params, callback) {
        callback(null, {test: &quot;value&quot;});
    })
  });

  afterEach(()=&gt; {
      AWS.restore();
  });

    it( 'test invocation', async() =&gt; {
        console.log(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;)
      const result = await index.handler({}, {}, (err, result) =&gt; {
          expect(result).toEqual({test: &quot;value&quot;});
  });
  });
</code></pre>
<p>My actual lambda function code looks like this:</p>
<pre><code>'use strict';

var AWS = require(&quot;aws-sdk&quot;);
var DOC = require(&quot;dynamodb-doc&quot;);
AWS.config.update({region: &quot;us-east-1&quot;//,
    });
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
    TableName: &quot;table-name&quot;,
    FilterExpression: &quot;#PK = :cat_val&quot;,
    ExpressionAttributeNames: {&quot;#PK&quot;: &quot;PK&quot;,},
    ExpressionAttributeValues: { &quot;:cat_val&quot;: &quot;Value&quot;}
};

exports.handler = (event, context, callback) =&gt; {
    var response; 
    
    docClient.scan(params, onScan);
    function onScan(err, data) {
        if (err) {
            response = {
                statusCode: 500,
                body: &quot;Unable to complete scan.  Error JSON: &quot; + JSON.stringify(err,null,2)
            }
        } else {
            data.Items.sort(compare);
            response = {
                statusCode: 200,
                body: data.Items
            }
        }

        callback(null, response);
        console.log(response);
    }
}
</code></pre>
<p>Any direction you guys can point me in.  The test fails on the equal compare because it has the actual response from the Dynamo scan.</p>
<p>Thanks,
Tim</p>
",https://stackoverflow.com/questions/62604392/unit-testing-using-jest-and-aws-sdk-mock-mock-dynamodb-scan,"['node.js', 'jestjs', 'aws-sdk', 'aws-sdk-mock']",1668,False,1,1
transforme vcast testcase to gtest testcase using python,"<p>I would like to use Google-Test to do unit testing but all test files are written in vcast format so in order to automate things I choose to use python, to write a script that transforms vcast to gtest</p>

<p>an example of vcast file :</p>

<pre><code>-- VectorCAST 6.4b (01/11/16)
-- Test Case Script
-- 
-- Environment    : TESTSUITE
-- Unit(s) Under Test: ADA_WORDS ASKI BAG_TEST_HELP CONDITIONS FL_TIME FORKER LB_TEST_HELP LOCKS NAV_TYPES OPER_DEF REFLECT_TESTER TYPES
-- 
-- Script Features
TEST.SCRIPT_FEATURE:MULTIPLE_UUT_SUPPORT
TEST.SCRIPT_FEATURE:MIXED_CASE_NAMES
TEST.SCRIPT_FEATURE:ADA_DIRECT_ARRAY_INDEXING
--

-- Unit: ADA_WORDS

-- Subprogram: IS_DELIMITER

-- Test Case: IS_DELIMITER.001
TEST.UNIT:ADA_WORDS
TEST.SUBPROGRAM:IS_DELIMITER
TEST.NEW
TEST.NAME:IS_DELIMITER.001
TEST.VALUE:ADA_WORDS.&lt;&lt;GLOBAL&gt;&gt;.cb:cTrue
TEST.EXPECTED:ADA_WORDS.&lt;&lt;GLOBAL&gt;&gt;.cb:cFalse
TEST.END


-- Test Case: BASIS-PATH-001-TEMPLATE
TEST.UNIT:ADA_WORDS
TEST.SUBPROGRAM:IS_DELIMITER
TEST.NEW
TEST.NAME:BASIS-PATH-001-TEMPLATE
TEST.BASIS_PATH:1 of 2
TEST.NOTES:
This is an automatically generated test case.
   Test Path 1
      (1) case C ==&gt; '&amp;' | ''' | '(' | ')' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' | '&lt;' | '=' | '&gt;' | '|'
   Test Case Generation Notes:
     Conflict: A branch uses an unsupported enumeral (C) in branch 1
     Conflict: Cannot determine any comparisons (ADA_WORDS.IS_DELIMITER.C)
TEST.END_NOTES:
TEST.END
</code></pre>

<p>my output is :</p>

<pre><code>#include&lt;iostream&gt;
    // GoogleTEST 6.4b (03/04/2020)
    // Test Case Script
    // 
    // Environment    : TESTSUITE
    // Unit(s) Under Test: ADA_WORDS ASKI BAG_TEST_HELP CONDITIONS FL_TIME FORKER LB_TEST_HELP LOCKS NAV_TYPES OPER_DEF REFLECT_TESTER TYPES
    // 
    // Script Features
    //
    // Unit: ADA_WORDS
    #include ""ADA_WORDS.h""
    #include ""ADA_WORDS.cpp""
    // Subprogram: IS_DELIMITER
    // Test Case: IS_DELIMITER.001
    TEST(IS_DELIMITER_001, gtest_IS_DELIMITER_001) {
        cb = 1; 
        IS_DELIMITER();
        EXPECT_EQ(cb,0); 
    }
    // Test Case: BASIS-PATH-001-TEMPLATE
    TEST(BASIS-PATH-001-TEMPLATE, gtest_BASIS-PATH-001-TEMPLATE) {
        IS_DELIMITER();
    }
</code></pre>

<p>for the first  testcase all the lines are transformed my question is about the second one 
how can i transforme TEST.BASIS_PATH:1 of 2 ,  TEST.NOTES: and what are their equivalent in googleTest</p>

<p>thank you</p>
",https://stackoverflow.com/questions/61011613/transforme-vcast-testcase-to-gtest-testcase-using-python,"['python', 'unit-testing', 'googletest']",149,False,1,0
"Unit Testing Using Jest and AWS-SDK-Mock, Mock DynamoDB Scan","<p>Jumping into Jest and unit testing lambda functions.  I'm trying to mock the aws dynamodb-document client scan in my unit test.  I'm getting back the actual scan from the real db though so i know something with my mock isn't working.  This is my .test.js:</p>
<pre><code>var AWS = require('aws-sdk-mock');
const sinon = require('sinon');
let index = require('./index.js');


beforeEach(()=&gt; {
    AWS.mock('DynamoDB.DocumentClient', 'scan', function(params, callback) {
        callback(null, {test: &quot;value&quot;});
    })
  });

  afterEach(()=&gt; {
      AWS.restore();
  });

    it( 'test invocation', async() =&gt; {
        console.log(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;)
      const result = await index.handler({}, {}, (err, result) =&gt; {
          expect(result).toEqual({test: &quot;value&quot;});
  });
  });
</code></pre>
<p>My actual lambda function code looks like this:</p>
<pre><code>'use strict';

var AWS = require(&quot;aws-sdk&quot;);
var DOC = require(&quot;dynamodb-doc&quot;);
AWS.config.update({region: &quot;us-east-1&quot;//,
    });
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
    TableName: &quot;table-name&quot;,
    FilterExpression: &quot;#PK = :cat_val&quot;,
    ExpressionAttributeNames: {&quot;#PK&quot;: &quot;PK&quot;,},
    ExpressionAttributeValues: { &quot;:cat_val&quot;: &quot;Value&quot;}
};

exports.handler = (event, context, callback) =&gt; {
    var response; 
    
    docClient.scan(params, onScan);
    function onScan(err, data) {
        if (err) {
            response = {
                statusCode: 500,
                body: &quot;Unable to complete scan.  Error JSON: &quot; + JSON.stringify(err,null,2)
            }
        } else {
            data.Items.sort(compare);
            response = {
                statusCode: 200,
                body: data.Items
            }
        }

        callback(null, response);
        console.log(response);
    }
}
</code></pre>
<p>Any direction you guys can point me in.  The test fails on the equal compare because it has the actual response from the Dynamo scan.</p>
<p>Thanks,
Tim</p>
",https://stackoverflow.com/questions/62604392/unit-testing-using-jest-and-aws-sdk-mock-mock-dynamodb-scan,"['node.js', 'jestjs', 'aws-sdk', 'aws-sdk-mock']",1668,False,1,1
React JS Jest Unit Testing Enzyme Set state for testing,"<p>I am writing a jest and enzyme unit testing for a react js component that uses Reflux.</p>

<p>I finally got the test to check the componentdidmount and check the component with the folloiwng</p>

<pre><code>**const onWillMount = jest.fn()
MyComponent.protoType.componentWillMount = onWillMount
mount(&lt;MyComponent/&gt;)
expect(onWillMount).toHaveBeenCalled(1)**
</code></pre>

<p>but I have state variables which are populated before it passed back the rendering</p>

<p>using jest and  enzyme, how to do set the state variable like this.state.myList</p>

<p>I am getting the jest error myList of null.</p>

<p>I tried MyComponent.prototype.setState but that did not work</p>

<p>Any help is great appreciated. Thanks</p>

<pre><code>export default class MyComponent extends Reflux.Component {
  constructor(props) {
    super(props)
    this.stores= ['myStore']
    this.storeKeys = ['myDataList']
  }

  compentDidMount() {
    myAction.getMyList()
  }

  render() {
    const hasData = !_.isNil(this.state.myList)
  }
}
</code></pre>
",https://stackoverflow.com/questions/62197053/react-js-jest-unit-testing-enzyme-set-state-for-testing,"['reactjs', 'jestjs', 'enzyme']",227,False,1,0
getOrAwaitValue() method returned IllegalArgumentException when unit testing viewmodel in kotlin,"<p>I am getting the IllegalArgumentException when i run my <strong>PatientViewModelTest</strong> class, i struggled a lot to fix to problem on my own but failed to solve it. Actually i have no idea about why this error is occurring because i'm new in Kotlin as well as Unit Testing. This is my first application in kotlin. Please help me.</p>
<p>Thanks</p>
<p>PatientViewModel.kt</p>
<pre><code>import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.*
import com.aitriage.data.Patient
import com.aitriage.data.Staff
import com.aitriage.other.Event
import com.aitriage.other.Resource
import com.aitriage.repository.MainRepository
import kotlinx.coroutines.launch

class PatientViewModel @ViewModelInject constructor(private val mMainRepository: MainRepository): ViewModel()
{
    val patientList = mMainRepository.getAllPatients()

    private val _insertPatientStatus = MutableLiveData&lt;Event&lt;Resource&lt;Patient&gt;&gt;&gt;()

    val insertPatientStatus : LiveData&lt;Event&lt;Resource&lt;Patient&gt;&gt;&gt; = _insertPatientStatus

    fun insertPatientIntoDB(patient: Patient) = viewModelScope.launch {

        mMainRepository.insertPatient(patient)
    }

    fun insertPatient(age: String, createdAt: String, gender: String,hopitalId:String, patientId: String,race: String, sortKey: String, status: String){
        
        if (age.isEmpty() || createdAt.isEmpty() || gender.isEmpty() || hopitalId.isEmpty() || patientId.isEmpty() || race.isEmpty() || sortKey.isEmpty() || status.isEmpty())
        {
            _insertPatientStatus.postValue(Event(Resource.error(null,&quot;The fields can't be empty&quot;)))
            return
        }


        val staff = Staff(&quot;Himanshu&quot;)
        val patient = Patient(0,staff,age,createdAt, gender,hopitalId,patientId,race,sortKey,status)
        insertPatientIntoDB(patient)
        _insertPatientStatus.postValue(Event(Resource.success(patient)))


    }

 }
</code></pre>
<p>PatientViewModelTest.kt</p>
<pre><code>import android.os.Build
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.aitriage.MainCoroutineRule
import com.aitriage.getOrAwaitValue
import com.aitriage.other.Status
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito
import org.robolectric.annotation.Config

@Config(sdk = [Build.VERSION_CODES.O_MR1])
@ExperimentalCoroutinesApi
class PatientViewModelTest {
    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    var mainCoroutineRule = MainCoroutineRule()

    private lateinit var viewModel: PatientViewModel

    @Before
    fun setup() {
        viewModel = Mockito.mock(PatientViewModel::class.java)
    }

    @Test
    fun `insert patient with empty field, returns error`() {
        viewModel.insertPatient(&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with age is empty, returns error`() {
        viewModel.insertPatient(&quot;&quot;, &quot;ds&quot;, &quot;ds&quot;, &quot;gfdg&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with date is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;&quot;, &quot;ds&quot;, &quot;gfdg&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with gender is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;&quot;, &quot;gfdg&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with hopital id is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with patient id is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with race is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }


    @Test
    fun `insert patient with sortkey is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()


        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with status is empty, returns error`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;fd&quot;, &quot;&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()

        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.ERROR)
    }

    @Test
    fun `insert patient with valid input, returns success`() {
        viewModel.insertPatient(&quot;da&quot;, &quot;sfs&quot;, &quot;fs&quot;, &quot;gf&quot;, &quot;gf&quot;, &quot;fd&quot;, &quot;fd&quot;, &quot;gd&quot;)

        val value = viewModel.insertPatientStatus.getOrAwaitValue()

        assertThat(value.getContentIfNotHandled()?.status).isEqualTo(Status.SUCCESS)
    }

    @Test
    fun add()
    {
        val actual = 4

        assertThat(actual).isEqualTo(4)
    }
}
</code></pre>
<p>LiveDataTestUtilClass.kt</p>
<pre><code>import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun &lt;T&gt; LiveData&lt;T&gt;.getOrAwaitValue(
        time: Long = 2,
        timeUnit: TimeUnit = TimeUnit.SECONDS,
        afterObserve: () -&gt; Unit = {}
): T {
    var data: T? = null
    val latch = CountDownLatch(1)
    val observer = object : Observer&lt;T&gt; {
        override fun onChanged(o: T?) {
            data = o
            latch.countDown()
            this@getOrAwaitValue.removeObserver(this)
        }
    }
    this.observeForever(observer)

    try {
        afterObserve.invoke()

        // Don't wait indefinitely if the LiveData is not set.
        if (!latch.await(time, timeUnit)) {
            throw TimeoutException(&quot;LiveData value was never set.&quot;)
        }

    } finally {
        this.removeObserver(observer)
    }

    @Suppress(&quot;UNCHECKED_CAST&quot;)
    return data as T
}
</code></pre>
<p>MainRepository.kt</p>
<pre><code>import com.aitriage.data.Help
import com.aitriage.data.input.ForgotPwdInput
import com.aitriage.data.input.LoginInput
import com.aitriage.data.Patient
import com.aitriage.database.HelpDao
import com.aitriage.database.PatientDao
import com.aitriage.network.ApiHelperImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class MainRepository @Inject constructor(
    private val patientDao: PatientDao,
    private val helpDao: HelpDao,
    private val apiHelper: ApiHelperImpl
) {

    suspend fun login(body: LoginInput) = apiHelper.login(body)
    suspend fun forgotPassword(body: ForgotPwdInput) = apiHelper.forgotPassword(body)

    fun getAllPatients() = patientDao.getAllPatients()


    suspend fun insertPatient(patient: Patient)
    {
        patientDao.insertPatient(patient)
    }


    fun getHelp() = helpDao.getHelp(1)

    suspend fun saveHelp(help: Help) = helpDao.saveHelp(help)

    suspend fun getRemoteHelp(authToken: String) = apiHelper.getHelp(authToken)
}
</code></pre>
<p>This is the actual error i am getting. Please have a look at the screenshot.
<a href=""https://i.stack.imgur.com/0yx4J.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
",https://stackoverflow.com/questions/64555380/getorawaitvalue-method-returned-illegalargumentexception-when-unit-testing-vie,"['java', 'android', 'unit-testing', 'kotlin', 'android-viewmodel']",436,False,1,0
RPM: unit tests per subpackages in the %check section,"<p>I have this rpm that contains multiple subpackages and for each subpackage there should be a couple unit tests , according to docs, rpm support unit testing by using the <strong>%check</strong> directive.<br />
But i want to make sure that each subpackage runs it's own tests.
What i want to know is there any other way to divide the tests per subpackage, sort of like the spec file below(this won't work because it says that each spec file should have one <strong>%check</strong>)</p>

<pre><code>Name:                               Software
Version:                            1.0
Distribution:                       el7
Summary:                            Software divided to subpackages 
Group:                              Development

Source:                             Software1.0.tar.gz
Provides:                           software-package = %{sversion}
Requires:                           softlib = %{sversion}

%build

%package subpackage1
Requires:                           reqlib1 = 1.4
Provides:                           provlib1 = 1.5
Obsoletes:                          obslib1 = 1.0


%package subpackage2
Requires:                           reqlib2 = 1.4
Provides:                           provlib2 = 1.5
Obsoletes:                          obslib2 = 1.0

%install
#install script

%clean
#clean script

%check subpackage1
./test_subpackage1


%check subpackage2
./test_subpackage2


%files subpackage1
path-to-file-1

%files subpackage2
path-to-file-2

</code></pre>
",https://stackoverflow.com/questions/60054580/rpm-unit-tests-per-subpackages-in-the-check-section,"['rpm', 'rpmbuild', 'rpm-spec']",500,False,1,1
Is it possible to do multiple app builds concurrently in React Native?,"<p>I was wondering if it's possible to have different apps being built out of a single repo in React Native. The reason I'm trying to do this would probably be a huge edge case, but it's basically for unit testing RN modules that I'm developing.</p>

<p>I know I can unit test individual components using Enzyme, but I have some modules that are part of a whole framework, and I need to do end-to-end unit tests on them. So my thinking is that I should build the app and run unit tests on it with Appium. But what if there are multiple unit tests? I guess we would need to build multiple separate apps? But there's only one index.js file.</p>

<p>I was reading that I could set up some app targets and schemes (iOS) and equivalent stuff in Android. But how would I handle that on the RN side? Where can I specify which .js file is the entry point for each target? And how does RN handle building different targets?</p>

<p><a href=""https://www.dev6.com/frameworks/building-multiple-apps-from-one-react-native-project/"" rel=""nofollow noreferrer"">https://www.dev6.com/frameworks/building-multiple-apps-from-one-react-native-project/</a>
Read this article about setting up multiple schemes and using those to set environment variables that could influence control flow in the app. However, this would mean that I would have to run the unit tests in serial, loading the same app up over and over with different env (not the end of the world, I guess).</p>

<p>I was thinking that if I had multiple <code>index.js</code> files, one for each unit test, I could maybe set up some separate app targets/schemes and use those, but I guess I would have to figure out how to build and run them concurrently for concurrent unit testing. I think that the <code>react-native run-ios</code> and <code>run-android</code> commands just build a single app though, so I'm not sure how I'd fit that into my unit testing workflow.</p>

<p>Any thoughts on this strategy or other possible strategies would be very welcome! Thanks :)</p>
",https://stackoverflow.com/questions/61959027/is-it-possible-to-do-multiple-app-builds-concurrently-in-react-native,"['android', 'ios', 'reactjs', 'react-native', 'unit-testing']",1726,True,0,1
How to test websocket with jest and enzyme?,"<p>I am building an webapp and wish to unit test it. It also has Socket.io websocket backend (expressjs backend) and socket.io client on react app which is create-react-app application. 
Here is the test so far:</p>

<pre><code>import React from 'react';

// 3rd party imports 
import { render } from '@testing-library/react';
import { shallow, mount } from ""enzyme"";
import { SocketIO, Server } from 'mock-socket';

// custom imports
import App from '../App';
import Tasks from '../components/Tasks';

describe('App', () =&gt; {
  let wrapper, shallowWrapper;
  const mockServer = new Server('ws://localhost:8080');
  window.io = SocketIO;
  beforeEach(async () =&gt; {
    wrapper = mount(&lt;App /&gt;);
    //start web socket config with mock-server
    mockServer.on('connection', socket =&gt; {
      socket.emit('task', 'test message from mock server');
    });
  // end web socket config
    shallowWrapper = shallow(&lt;App /&gt;);
  });

  it(""renders"", () =&gt; {
    shallow(&lt;App /&gt;);
  });

  test('renders right text', () =&gt; {
    const { getByText } = render(&lt;App /&gt;);
    const linkElement = getByText(/BI4 Monitor/i);
    expect(linkElement).toBeInTheDocument();
  });

  it('has one unordered list', () =&gt;{
    expect(wrapper.find(""ul"")).toHaveLength(0);
  });

  it(""displays initial empty list"", () =&gt; {
    expect(wrapper.find(""li"")).toHaveLength(0);
  });

  it(""has Tasks component"", () =&gt; {
    console.log(shallowWrapper.debug())
    expect(shallowWrapper.contains(&lt;Tasks/&gt;)).toBe(true);
  });

});
</code></pre>

<p>I am using this mock library:
<a href=""https://github.com/thoov/mock-socket"" rel=""nofollow noreferrer"">https://github.com/thoov/mock-socket</a></p>

<p>Here is App.js</p>

<pre><code>import React, { useEffect, useState } from 'react';

// 3rd party imports
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import { useImmer } from 'use-immer';
import _ from ""underscore"";

// custom imports
import { SocketUtil } from './utils';
import Tasks from './components/Tasks';

const socket = SocketUtil.init();

function App() {
  const [msg, setMsg] = useState([]);
  function handleData(payload) {
    // data = [...data, payload]
    setMsg(m =&gt; m.concat(payload));
  }

  useEffect(() =&gt; {
     socket.on('task', payload =&gt; {
       console.log(""taskkkk"")
       handleData(payload);
     });
  });


  return (
    &lt;Container&gt;
      &lt;Row className=""row""&gt;
        &lt;Col xs={12}&gt;
          &lt;h1&gt;BI4 Monitor&lt;/h1&gt;
          {/* &lt;Tasks/&gt; */}
          {_.map(msg, function(m) {
            return (
              &lt;p&gt;{m.key}&lt;/p&gt;
            );
          })}
          &lt;Tasks/&gt;
        &lt;/Col&gt;
      &lt;/Row&gt;
    &lt;/Container&gt;
  );
}

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

<p>I wish to print that <code>console.log(""taskkkk"")</code> or basically just unit testing to see more then one <code>&lt;p&gt;{m.key}&lt;/p&gt;</code> getting rendered but is not happening. 
Also I have tried with <code>https://github.com/romgain/jest-websocket-mock</code> but no luck.
Any ideas how this could be achieved?</p>
",https://stackoverflow.com/questions/61292587/how-to-test-websocket-with-jest-and-enzyme,"['unit-testing', 'websocket', 'socket.io', 'jestjs', 'enzyme']",1787,False,3,1
TypeError: getUserInfo is not a function,"<p>I am using Jest for unit testing my code.</p>
<p>I have a file userinfo.js</p>
<pre><code>const getuserdata = async function (req, res, next) {
    let userinfo = await getUserInfo();
    return userinfo;
}

const getUserInfo = async function (req, res, next) {
    const records = await database.query('select * from users');
    return records;
}
module.exports = {
  getuserdata,
  getUserInfo
}
</code></pre>
<p>I want to write test in jest
I created a file userinfo.test.js for testing.</p>
<p>code:</p>
<pre><code>const { getuserdata, getUserInfo } = require('./userinfo');

describe('user data', () =&gt; {
  beforeEach(() =&gt; {
    jest.clearAllMocks();
  });
  test('user info', async () =&gt; {
    jest.mock('Path of file', () =&gt; ({ getUserInfo: jest.fn() }));
    getUserInfo.mockResolvedValue([{id: 1, name: &quot;test&quot;, password: &quot;123456&quot;}]);
    const userdata = await getuserdata();
    expect(userdata).not.toBeUndefined();
  });
}
</code></pre>
<p>I want to test getuserdata but mock getUserInfo.
When I try to mock by above method it is giving me error that: TypeError: getUserInfo is not a function</p>
<p>but if I save the getUserInfo in different file then mocking is working properly. can you please suggest me how to fix this issue.</p>
",https://stackoverflow.com/questions/62539321/typeerror-getuserinfo-is-not-a-function,"['node.js', 'unit-testing', 'mocking', 'jestjs']",796,False,0,1
How to mock Hawk library using Mockito?,"<p>I'm trying to do some unit testing with <code>Mockito</code>. Because I'm using <code>Hawk</code> library as <code>SharedPreference</code> to apply some constraints when I do my API calls, every time I run a test that implies an API call I get a NullPointerException because <code>Hawk</code> is not initialized.</p>
<p>By default the library is initialized on the <code>Application</code> class level:</p>
<pre><code>Hawk.init(context).build();
</code></pre>
<p>Although I'm using a mocked <code>context</code> to initialize <code>Hawk</code> in my test class, as in the following snippet:</p>
<pre><code>@Mock
private lateinit var context: Context

@Before
fun initMocks() {
    MockitoAnnotations.initMocks(this)
    Hawk.init(context).build()
}
</code></pre>
<p>I keep getting this error message:</p>
<pre><code>java.lang.NullPointerException
at com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain.&lt;init&gt;(SharedPrefsBackedKeyChain.java:65)
at com.orhanobut.hawk.ConcealEncryption.&lt;init&gt;(ConcealEncryption.java:17)
at com.orhanobut.hawk.HawkBuilder.getEncryption(HawkBuilder.java:93)
at com.orhanobut.hawk.DefaultHawkFacade.&lt;init&gt;(DefaultHawkFacade.java:12)
at com.orhanobut.hawk.Hawk.build(Hawk.java:27)
at com.orhanobut.hawk.HawkBuilder.build(HawkBuilder.java:109)
at com.terma.ds.rm.clientandroid.activity.radar_list.RadarListModelTest.initMocks(RadarListModelTest.kt:39)
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.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:68)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:74)
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: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>Is there a way to mock the <code>Hawk</code> library using <code>Mockito</code>?</p>
",https://stackoverflow.com/questions/62758440/how-to-mock-hawk-library-using-mockito,"['android', 'unit-testing', 'testing', 'mockito', 'integration-testing']",349,False,0,2
Android Unit Testing using Navigation Architecture,"<p>i am using Android Navigation Component which has 1 activity named as <strong>Authentication Activity</strong> which contains 3 fragments named <strong>SplashFragment</strong>, <strong>Login Fragment</strong>, <strong>OTP Fragment</strong>.</p>
<p>I want to do Unit Testing for Login Fragment which contains different fields like Mobile Number, Name, Email, State dropDown.</p>
<p>Please help me out how to write Unit test cases for Mobile number field, Name, email. I had attached sample unit test code of mine, gradle dependency.</p>
<p>Framework tried:- <strong>Mockito</strong>, <strong>Espresso</strong>, <strong>Roboelectric</strong></p>
<p>Thanks in advance.</p>
<pre><code>@Test
fun vmInitialization() {
    val state1 = State(&quot;DL&quot;, &quot;Delhi&quot;)
    val state2 = State(&quot;UP&quot;, &quot;Uttar Pradesh&quot;)
    val list: ArrayList&lt;State&gt; = ArrayList()
    list!!.add(state1)
    list!!.add(state2)
    val bundle = Bundle().putParcelableArrayList(&quot;stateList&quot;, list as ArrayList&lt;Parcelable&gt;)
    launchFragment(R.id.loginFragment, bundle as Bundle)
    val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
    navController.setGraph(R.navigation.nav_graph_auth)
    val scenario = launchFragmentInContainer&lt;LoginFragment&gt;()
    navController.setViewModelStore(ViewModelStore())
    scenario.onFragment { fragment -&gt;
        Navigation.setViewNavController(fragment.requireView(), navController)
    }
    onView(ViewMatchers.withId(R.id.btn_proceed)).perform(ViewActions.click())
    val navGraph = navController.navigatorProvider.navigation(
        id = R.id.nav_graph_auth,
        startDestination = R.id.otpFragment
    ) {
    }
    navController.setGraph(navGraph, null)
    scenario.onFragment { fragment -&gt;
        assertNotNull(fragment)
        assertThat(fragment).isNotNull()
        assertThat(fragment.savedStateViewModel).isNotNull()
    }
}
</code></pre>
<p>Gradle dependencies:-</p>
<pre><code>debugImplementation &quot;androidx.navigation:navigation-testing:2.3.0-alpha06&quot;
debugImplementation &quot;androidx.test:runner:1.2.0&quot;
debugImplementation &quot;androidx.test:core:1.2.0&quot;
debugImplementation(&quot;androidx.test:rules:1.2.0&quot;)
debugImplementation(&quot;androidx.fragment:fragment-ktx:1.1.0-beta01&quot;)
debugImplementation &quot;androidx.test.ext:junit-ktx:1.1.1&quot;
debugImplementation('androidx.fragment:fragment-testing:1.1.0') {
    // exclude androidx.test:core while fragment_testing depends on 1.1.0
    exclude group: 'androidx.test', module: 'core'
}
</code></pre>
",https://stackoverflow.com/questions/63788257/android-unit-testing-using-navigation-architecture,"['android', 'unit-testing', 'kotlin', 'junit']",869,False,0,1
How can I solve NoSuchMethodError using Retrofit2?,"<p>I tested some example code but Retrofit Builder occured error.
I can check for errors in initialization.</p>

<p>I read two articles but no my case.<br>
<a href=""https://stackoverflow.com/questions/43572791/retrofit2-nosuchmethoderror-with-external-aar-that-uses-okhttp3-3-3-1"">Retrofit2 NoSuchMethodError with external AAR that uses OkHttp3 3.3.1</a>
<br>
<a href=""https://stackoverflow.com/questions/39001404/unit-testing-nosuchmethoderror-at-mock-retrofit-get-request"">Unit testing: NoSuchMethodError at mock retrofit get request</a></p>

<p>Looking at other articles, the same error occurs in certain methods.<br>
But in my case it happens in initialization.</p>

<p>Creating a new project, just adding retrofits causes the same problem.</p>

<p>my build gradle:</p>

<pre><code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion ""29.0.3""
    viewBinding.enabled = true

    defaultConfig {
        applicationId ""kr.ac.sunmoon.gijoe.camaps""
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName ""1.0""

        testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    // Mistake, missing lines, Start
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    // missing lines, End
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

</code></pre>

<p>my error code:</p>

<pre><code>public class .... {
    private Retrofit mRetrofit;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setRetrofitinit();
    }

    private void setRetrofitInit() {
        mRetrofit = new Retrofit.Builder()
            .baseUrl(getString(R.string.baseUrl))  &lt;== Error: noSuchMethodError
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    }
}
</code></pre>

<p>and Error Messages:</p>

<pre><code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: kr.ac.sunmoon.kiwoon.testretrofit, PID: 10254
    java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or its super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at okhttp3.internal.Util.&lt;clinit&gt;(Util.java:87)
        at okhttp3.internal.Util.skipLeadingAsciiWhitespace(Util.java:321)
        at okhttp3.HttpUrl$Builder.parse(HttpUrl.java:1313)
        at okhttp3.HttpUrl.get(HttpUrl.java:917)
        at retrofit2.Retrofit$Builder.baseUrl(Retrofit.java:506)
        at kr.ac.sunmoon.kiwoon.testretrofit.MainActivity.setRetrofitinit(MainActivity.java:28)
        at kr.ac.sunmoon.kiwoon.testretrofit.MainActivity.onCreate(MainActivity.java:24)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code></pre>
",https://stackoverflow.com/questions/62282585/how-can-i-solve-nosuchmethoderror-using-retrofit2,"['android', 'retrofit']",765,True,0,1
What parameters to check for connection is &quot;dirty&quot; / leaking,"<p>I am trying to develop unit testing framework. I want to know if current connection is leaking. I want to check if previous stored procedure/function/sql executed is not leaking anything.</p>

<ul>
<li>There is no pending transaction for current connection</li>
<li>pg_advisory_lock</li>
<li>There is no temp table remaining to be deleted for current connection</li>
</ul>

<p><strong>What else I should check</strong></p>

<p>I know there is <code>DISCARD ALL</code> which reset everything, but I want to know if current connection is leaking anything and what it is leaking?</p>
",https://stackoverflow.com/questions/61960440/what-parameters-to-check-for-connection-is-dirty-leaking,['postgresql'],50,False,0,1
How to unit test a dynamic website that renders templates?,"<p>My controllers end in rendering a template and giving that template certain data via res.locals. I guess the point of unit testing these controllers wouldn't be the actual html (since the specifics of the layout can change), but whether given a certain request, the controller passes the right output to the template.</p>
<p>I don't understand how I'm supposed to test this though since the controller function doesn't actually &quot;output&quot; anything so how am I supposed to determine what it did in a test script? Also, I don't know how to give it a specific input because it's input is an HTTP request that's gone through a bunch of other middleware in the pipeline.</p>
<p>Here's an example of a controller:</p>
<pre class=""lang-js prettyprint-override""><code>    function index_post(req, res, next) {
      const errors = validationResult(req);
    
      if (!errors.isEmpty()) {
        res.locals.error = errors.array()[0];
        res.locals.email_value = req.body.email;
        res.locals.password_value = req.body.password;
        return res.render(&quot;login&quot;);
      }
   
      res.locals.message = 'You logged in';
      res.render('success');
    };

</code></pre>
<p>Outside the context of the Express pipeline, I'm not sure how to give it test inputs (normally it's reading properties from req as placed by previous middleware) and how to get access to the output (res.locals and what template it renders)
e.g I'd want to test that given a request with a valid email and password, <code>index_post</code> renders the &quot;success&quot; template and <code>res.locals</code> contains a <code>message</code> property with value. (I don't need to do do it in exactly the way I just mentioned, but I'm assuming unit testing a controller would require asserting those two facts.)</p>
",https://stackoverflow.com/questions/64900610/how-to-unit-test-a-dynamic-website-that-renders-templates,"['html', 'node.js', 'unit-testing', 'express', 'web-testing']",90,False,1,0
How to test the axios response of the Backend API on vue js?,"<p>I need help regarding how to test the <strong>get</strong>, <strong>post</strong>, <strong>put</strong>, <strong>patch</strong> backend API responses using <strong>vue js</strong>?</p>

<p>Currently I want to understand about <strong>unit testing</strong>. I have searched for it several times but I did not get an example or documentation that is easy to understand. If someone has already implemented it in their respective projects, can explain it a little. Maybe some of you all can provide references or examples for testing <strong>axios</strong> on <strong>vue js</strong> if you don't mind.</p>
",https://stackoverflow.com/questions/61459640/how-to-test-the-axios-response-of-the-backend-api-on-vue-js,"['javascript', 'unit-testing', 'vue.js', 'axios']",52,False,0,0
Virtual environments for Python based Azure Functions,"<p>I am looking at <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#folder-structure"" rel=""nofollow noreferrer"">Microsoft's recommended folder structure for Python Based Azure Functions</a> which contains some shared code and two functions in one app, along with testing. I have tried to implement this using VSCode but I am struggling to understand how this project structure works with Python's virtual environments.</p>
<p>If I was not publishing Functions (i.e. just starting with a basic Python library with unit testing), I would create a virtual environment at the same level as <code>test</code> so that my older structure may look something like</p>
<pre><code>__app__
 | 
 .venv
 |
 | - shared_code
 | | - my_first_helper_function.py
 | | - my_second_helper_function.py
 |
 tests
</code></pre>
<p>When I create <code>my_first_function</code> using VSCode (turning <code>__app__</code> into an Azure Function project), VSCode Azure Function Extension creates a new virtual environment at the same level as <code>my_first_function</code> so the folder structure then looks like</p>
<pre><code>__app__
 | 
 .venv
 | 
 | - .venv
 | |
 | - my_first_function
 | | - __init__.py
 | | - function.json
 | | - example.py
 | - shared_code
 | | - my_first_helper_function.py
 | | - my_second_helper_function.py
 |
 tests
</code></pre>
<p>i.e. the project contains multiple virtual environments. If I remove the new venv (the one at the same levels as <code>my_first_function</code>), I cannot deploy the Function correctly (the Function fails because it can't find the modules in the venv). If I delete the original venv, I cannot get the tests to run.</p>
<p>Is this an issue with the VSCode Functions Extension? How should I set up the virtual environments to ensure I can have unit testing (not deployed to Azure) with common code and two Azure Functions?</p>
<p>Any pointer greatly appreciated.</p>
",https://stackoverflow.com/questions/63526022/virtual-environments-for-python-based-azure-functions,"['python', 'azure-functions']",4929,True,1,1
How to create a 2D array of a contructor (with 2 arguments) in spec file,"<p>This question is entirely related to unit testing in Angular with Jasmine and Karma.</p>
<p>I have one component called <em>Strip</em>. I have its template, its typescript, its configuration and its test case i.e. spec file.</p>
<p><strong>strip.config.ts</strong></p>
<pre><code>// this is the configuration file for the StripComponent

import { WidgetSource } from '../../shared/models/widgetSource';

export class StripConfig {
    type: 'strip';
    rows: WidgetSource[][]; // &lt;-------------- MY REQUIREMENT

    constructor() {}
}
</code></pre>
<p>This is the <em>WidgetSource</em> that the above config class has imported:</p>
<p><strong>widgetSource.ts</strong></p>
<pre><code>/**
 * Widget Source class.
 */

import { DashboardName, WidgetName } from './myJSONConfig';

export class WidgetSource {
    dashboardName: DashboardName;
    widgetName: WidgetName;

    constructor(
        dashboardName: DashboardName,
        widgetName: WidgetName
    ) {
        this.dashboardName = dashboardName;
        this.widgetName = widgetName;
    }
}
</code></pre>
<p>Here's the spec file:</p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { StripComponent } from './strip.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { StripConfig } from './strip.config';
import { WidgetSource } from 'src/app/shared/models/widgetSource';
import { DashboardName, WidgetName } from 'src/app/shared/models/myJSONConfig';

fdescribe('StripComponent', () =&gt; {
    let component: StripComponent;
    let fixture: ComponentFixture&lt;StripComponent&gt;;
    ...
    const strip: StripConfig = {
        type: 'strip',
        rows: new WidgetSource([DashboardName.MY_DASHBOARD], [WidgetName.HISTOGRAM]) // HELP
    };

    ...
});
</code></pre>
<p>If it was a single value like this in config:</p>
<p><code>rows: WidgetSource;</code></p>
<p>My code in spec file would be:</p>
<p><code>rows: new WidgetSource(DashboardName.RPM_DASHBOARD, WidgetName.ACTIVE_DAYS_GRAPH)</code></p>
<p>But my requirement is a double dimensional array. Please help me.</p>
",https://stackoverflow.com/questions/64738552/how-to-create-a-2d-array-of-a-contructor-with-2-arguments-in-spec-file,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",79,False,0,1
How to mock instance method,"<p>I'm new to xunit and unit testing , I'm writing unit test which calls instance method from the implemented method of an Interface i.e While testing SendFaxAsEmail(..) method I want to mock the behavior of instance method SendEmail(..) which will return boolean. Below is the code</p>
<pre><code>public class NPFaxAsEmailBL : INPFaxEmailBL
{
    private IEmailSender _emailSender;
   
    public NPFaxAsEmailBL(IEmailSender emailSender)
    {
        _emailSender = emailSender;
    }

    public bool SendFaxAsEmail(FaxMailDTO faxMailDTO)
    {
        bool isEmailSuccessfully = false;
        bool validationCompleted = CompleteValidation(faxMailDTO);
        if (validationCompleted)
        {
            Log.Information($&quot;{faxMailDTO?.NP}: FaxAsMailRequest Request validation Completed.&quot;);
            
            faxMailDTO.ToAddressDisplayName = string.Format(GlobalConstant.EmailToFormat, faxMailDTO?.FaxNumber, faxMailDTO?.ReceiverName, faxMailDTO?.NP, faxMailDTO?.OTP);
            faxMailDTO.Subject = string.Empty;
            faxMailDTO.Body = string.Empty;
            faxMailDTO.FromAddressDisplayName = string.Empty;
            faxMailDTO.FromEmailAddress = AppSettingsHelper.FromEmailAddress;
            faxMailDTO.ToEmailAddress = AppSettingsHelper.ToEmailAddress;
            isEmailSuccessfully = SendEmail(AppSettingsHelper.RightFaxSMTPServer, faxMailDTO);
        }
            return isEmailSuccessfully;
    }

    public bool SendEmail(string sMTPServerUrl, FaxMailDTO faxAsMailRequest)
    {
        // return boolean value 
    }
}
</code></pre>
<p>When I execute below written test case it throws an error:</p>
<blockquote>
<p>System.NotSupportedException : Unsupported expression: x =&gt; x.SendEmail(NPFaxAsEmailTest.&lt;&gt;c__DisplayClass7_0.sMTPServerUrl, NPFaxAsEmailTest.&lt;&gt;c__DisplayClass7_0.faxMailDTO)
Non-overridable members (here: NPFaxAsEmailBL.SendEmail) may not be used in setup / verification expressions.</p>
</blockquote>
<pre><code>public class NPFaxAsEmailTest
{
    private NPFaxAsEmailBL _nPFaxAsEmailBL;
    private Mock&lt;IEmailSender&gt; mock;
    private Mock&lt;NPFaxAsEmailBL&gt; _mockNPFaxAsEmailBL;

    public NPFaxAsEmailTest()
    {
        mock = new Mock&lt;IEmailSender&gt;();
        _nPFaxAsEmailBL = new NPFaxAsEmailBL(mock.Object);
        _mockNPFaxAsEmailBL = new Mock&lt;NPFaxAsEmailBL&gt;();
    }
    
    [Theory]
    [MemberData(nameof(GetFaxAsMailDTO))]
    public void SendFaxAsEmailTest_ReturnsTrue(FaxMailDTO faxMailDTO)
    {
        string sMTPServerUrl = AppSettingsHelper.RightFaxSMTPServer;
        _mockNPFaxAsEmailBL.Setup(x =&gt; x.SendEmail(sMTPServerUrl, faxMailDTO)).Returns(true); //&lt;-this line throws an error
        var result=_nPFaxAsEmailBL.SendFaxAsEmail(faxMailDTO);
        Assert.True(result);
    }
}
</code></pre>
",https://stackoverflow.com/questions/64115775/how-to-mock-instance-method,"['c#', 'unit-testing', '.net-core', 'moq', 'xunit']",300,False,0,0
Using dlsym() to stub malloc/free leads to segmentation fault,"<p>I started to dabble in unit testing C code (using check) and stubbing functions. I am trying to unit 
test a small library of data structures that I wrote and wanted to test how it would react to OOM. So I
wrote a simple <code>stubs.c</code> file containing:</p>

<pre class=""lang-c prettyprint-override""><code>#include &lt;stdlib.h&gt;
#include &lt;errno.h&gt;
#include &lt;dlfcn.h&gt;

static int malloc_fail_code = 0;
static int calloc_fail_code = 0;

void set_malloc_fail_code(int no) { malloc_fail_code = no; }
void set_calloc_fail_code(int no) { calloc_fail_code = no; }

void *malloc(size_t size)
{
    static void *(*real_malloc)(size_t) = NULL;

    if (!real_malloc)
        real_malloc = (void *(*)(size_t)) dlsym(RTLD_NEXT, ""malloc"");

    if (malloc_fail_code != 0) {
        errno = malloc_fail_code;
        malloc_fail_code = 0;
        return NULL;
    }

    return real_malloc(size);
}

void *calloc(size_t nmemb, size_t size)
{
    static void *(*real_calloc)(size_t, size_t) = NULL;

    if (!real_calloc)
        real_calloc = (void *(*)(size_t, size_t)) dlsym(RTLD_NEXT, ""calloc"");

    if (calloc_fail_code != 0) {
        errno = calloc_fail_code;
        calloc_fail_code = 0;
        return NULL;
    }

    return real_calloc(nmemb, size);
}
</code></pre>

<p>with its relative <code>stubs.h</code> containing the definitions for the two setters. I then compiled stubs.c as 
a shared object called <code>libstubs.so</code>. I also compiled my library as a shared object called 
<code>libmy_lib.so</code>.</p>

<p>My test code is in <code>test.c</code> is something like this:</p>

<pre class=""lang-c prettyprint-override""><code>#include &lt;stdlib.h&gt;
#include &lt;errno.h&gt;
#include &lt;check.h&gt;

#include ""my_lib.h""
#include ""stubs.h""

START_TEST(my_test)
{
    ... // using the two setters I force malloc and calloc to return null and set errno to ENOMEM
}
END_TEST

... // check boilerplate to create suite and add tests
</code></pre>

<p>I then linked the test executable against <code>libmy_lib.so</code> and <code>libstubs.so</code>. Running said executable greets me with a segfault. Inspecting the crash with gdb makes me believe that I encountered a stack overflow due to infinte recursion (gdb backtrace):</p>

<pre><code>#0  0x00007ffff7fc143c in calloc (
    nmemb=&lt;error reading variable: Cannot access memory at address 0x7fffff7feff8&gt;, 
    size=&lt;error reading variable: Cannot access memory at address 0x7fffff7feff0&gt;)
    at stubs.c
#1  0x00007ffff7db9c88 in _dlerror_run (operate=operate@entry=0x7ffff7db94f0 &lt;dlsym_doit&gt;, 
    args=args@entry=0x7fffff7ff030) at dlerror.c:148
#2  0x00007ffff7db9570 in __dlsym (handle=&lt;optimized out&gt;, name=&lt;optimized out&gt;) at dlsym.c:70
#3  0x00007ffff7fc1487 in calloc (nmemb=1, size=32) at stubs.c
...
</code></pre>

<p>I tried including directly <code>stubs.c</code> into <code>test.c</code> but no luck. I also tried writing a small unit testing framework of my own that extends <code>stubs.c</code> and it worked. However I don't want to waste time reinventing the wheel and I am sure there is something I am doing wrong in linking since I don't know much in compilation/linking.</p>

<p>For compilation I am using the meson build system so I don't know how to get the exact command line arguments but I can write a MWE of my build targets:</p>

<pre><code>lib = library(
  'my_lib',
  sources,
  include_directories: includes,
  install: true
)

stubs = shared_library(
  'stubs',
  'stubs.c',
  c_args: ['-g'],
  include_directories: test_includes,
  link_args: ['-ldl']
)

test_exe = executable(
  'test_exe',
  c_args: ['-g'],
  sources: 'test.c',
  dependencies: check,
  link_with: [stubs, lib],
  include_directories: includes + test_includes
)
test('test', test_exe, suite: 'suite')
</code></pre>
",https://stackoverflow.com/questions/62376361/using-dlsym-to-stub-malloc-free-leads-to-segmentation-fault,"['c', 'unit-testing', 'linker', 'meson-build', 'dlsym']",408,True,1,1
how to post and put request in unit testing with front-end angular and back-end node using jasmine and karma?,"<p>I have created one angular project and one node project for add data in SQL workbench.</p>
<p>I can add data in SQL workbench while I am running ng serve from angular project.</p>
<p>while the time of unit testing using jasmine &amp; karma and we run ng test command &amp; its run your test case and we got data in console log but we didn't get data in SQL database.</p>
<p><a href=""https://i.stack.imgur.com/q4svS.png"" rel=""nofollow noreferrer"">api.services.spec.ts</a></p>
<p><a href=""https://i.stack.imgur.com/owXNk.png"" rel=""nofollow noreferrer"">Form.component.ts</a></p>
<p>Can anyone help me for the same?</p>
<p>Thanks in Advance</p>
",https://stackoverflow.com/questions/64658067/how-to-post-and-put-request-in-unit-testing-with-front-end-angular-and-back-end,"['angular', 'unit-testing', 'karma-jasmine', 'angular-unit-test']",124,False,0,1
Is there a way to mimic the function of startup.cs in unit test cases while running multiple tests together?,"<p>I am trying to test some code that uses a static class. The static class has a initialization method which can be called only once and throws exception if called second time.  I have multiple test cases which tests the code that need to access the static class. In the code the initialization is done in startup.cs. How do I do something similar for test cases. I am using x-unit for unit testing.</p>
<pre><code> public static class UniqueId
{
    public static void Initialize()
    {
        if (_generator != null)
            throw new Exception(&quot;Already initialized.&quot;);
        _generator = new IdGenerator();
    }


    private static IdGenerator _generator = null;
    
    public static BigId NextId()
    {
        if (_generator == null)
            throw new Exception(&quot;Not initialized.&quot;);
        return _generator.NextId();
    }
}
</code></pre>
<p>Code that I want to test:</p>
<pre><code>public string GenerateId
{
    return UniqueId.NextId().ToString()
}
</code></pre>
",https://stackoverflow.com/questions/63580053/is-there-a-way-to-mimic-the-function-of-startup-cs-in-unit-test-cases-while-runn,"['c#', '.net-core', 'xunit']",442,False,0,3
Unit testing in Python: Nesting mocked objects,"<p>I am new to unit testing in Python. I am trying to unit test a method that does something like this:</p>
<pre><code>MyClass:

    client : Client

    def __init__(client):
        self.client=client

    def method_to_test(self):
        images = self.client.get_stuff()
        image = images[0]
        result = []
        for region in image.regions:    
            result.append(region.region_id)
        return result
</code></pre>
<p>I have tried mocking and nesting of all the classes involved: Client, Image and ImageRegion. But at some point the mocking breaks down and my test fails. Is there a way to mock things so that one can do something like:</p>
<pre><code>def test_method_to_test():
   result = MyClass(mock_client).method_to_test()
   assert dummy_region_id in result
</code></pre>
<p>... or perhaps better ways to test in such situations with nested custom objects?</p>
<p>My latest attempt looks like this:</p>
<pre><code>with patch('package.module.ImageRegion') as MockRegion:
    region = MockRegion()
    region.region_id.return_value = dummy_region_id 
        with patch('package.module.Image') as MockImage:
            image = MockImage()
            image.regions.return_value = [region]
                with patch('package.module.Client') as MockClient:
                    mock_client = MockClient()
                    mock_client.get_regions.return_value = [image]
                    result = MyClass(mock_client).method_to_test()
                    assert dummy_region_id in result
</code></pre>
",https://stackoverflow.com/questions/63948475/unit-testing-in-python-nesting-mocked-objects,"['python-3.x', 'unit-testing', 'pytest', 'python-unittest', 'python-unittest.mock']",342,True,0,1
How do I test a component that subscribes to a service?,"<p>I'm relatively new to unit testing in Angular. I'm using Jasmine and I find the API to be vague. I'm trying to write good tests for my component, but I'm getting stuck on how to test a component that subscribes to data from a service.</p>

<p>// component</p>

<pre><code>ngOnInit() {
    this.store.dispatch(this.loadDatagridDataAction({data: this.authorizations}));

    this.authorizationService.initAuthorizations();
    this.authorizationService.authorizations.subscribe(authorizations =&gt; {
        this.realAuthorizations = authorizations;
        this.realAuthorizations.results.forEach(authorization =&gt; {

            const formatAuthorization = {};

            if (authorization.number) {
                formatAuthorization['number'] = authorization.number;
            }

            if (authorization.status) {
                formatAuthorization['status'] = authorization.status;

            }

            if (authorization.requesting_provider) {
                const requestingProvider = flattenObject(authorization.requesting_provider);
                formatAuthorization['requesting_provider'] = requestingProvider['name'];

            }

            if (authorization.servicing_provider) {
                const servicingProvider = flattenObject(authorization.servicing_provider);
                formatAuthorization['servicing_provider'] = servicingProvider['name'];

            }

            if (authorization.termination_date) {
                formatAuthorization['termination_date'] = authorization.termination_date;
            }

            this.formattedAuthorizations.push(formatAuthorization);
        });

    });

}

setActiveTab(tab) {
    this.store.dispatch(this.setActiveTabAction({tab}));
}

setActiveRow(row) {
    console.log(row);
}

setCurrentPage(page) {
    this.store.dispatch(this.setPaginatorCurrentPageAction({page}));
}

goBack(route) {
    console.log(route);
}
</code></pre>

<p>}</p>

<p>// service</p>

<pre><code>export class AuthorizationService {

private _authorizations = new Subject&lt;any&gt;();

constructor(
    private http: HttpClient,
) { }

public get authorizations() {
    return this._authorizations.asObservable();
}

public getAuthorizations() {
    const auth = '/api/enrollment/tocs/';
    return this.http.get(auth);
}

public initAuthorizations() {
    this.getAuthorizations().subscribe(data =&gt; {
        this._authorizations.next(data);
    }, error =&gt; {
        console.log('Failed to get data', error);
    });
}
</code></pre>

<p>}</p>

<p>// unit test</p>

<pre><code>describe('AuthorizationsReferralsComponent', () =&gt; {
let component: AuthorizationsReferralsComponent;
let fixture: ComponentFixture&lt;AuthorizationsReferralsComponent&gt;;
let storeMock;
let configurationServiceMock;
let authorizationMockService;

beforeEach(async(() =&gt; {
    storeMock = {
        select: jasmine.createSpy('select'),
        dispatch: jasmine.createSpy('dispatch'),
    };

    authorizationMockService = jasmine.createSpyObj(['getAuthorizations', 'initAuthorizations', 'authorizations']);

    configurationServiceMock = {
        getTemplateConfiguration: () =&gt; {}
    };

    TestBed.configureTestingModule({
        declarations: [ AuthorizationsReferralsComponent ],
        imports: [SidebarTableViewModule,  HttpClientTestingModule],
        providers: [
            {
                provide: Store,
                useValue: storeMock
            },
            {
                provide: ConfigurationService,
                useValue: configurationServiceMock,
            },
            {
                provide: AuthorizationService,
                useValue: authorizationMockService
            },

        ]
    })
    .compileComponents();
}));

beforeEach(() =&gt; {
    HEROES = [
      {id: 1, name: 'SpiderDude', strength: 8},
      {id: 2, name: 'Wonderful Woman', strength: 24},
      {id: 3, name: 'SuperDude', strength: 55}
    ];

    fixture = TestBed.createComponent(AuthorizationsReferralsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', () =&gt; {
    authorizationMockService.initAuthorizations.and.returnValue(of(HEROES));
    fixture.detectChanges();

    expect(fixture.componentInstance.realAuthorizations.length).toBe(3);
});
</code></pre>

<p>});</p>

<p>I receiving the following error <code>TypeError: this.authorizationService.authorizations.subscribe is not a function</code></p>

<p>It appears that it thinks my <code>get authorizations()</code> function is not a function. How can I mock my service appropriately so I test the statements inside my subscribe?</p>

<pre><code> this.authorizationService.authorizations.subscribe(
</code></pre>
",https://stackoverflow.com/questions/59635833/how-do-i-test-a-component-that-subscribes-to-a-service,"['angular', 'unit-testing', 'jasmine', 'observable']",51,True,0,1
Is it possible to have a global setup method in Spock test?,"<p>I am a developer on a Grails/Groovy application which uses Spock as its framework for unit testing. The project has around 1000 unit tests, and I would essentially like to perform a specific mock / operation before running all tests. Preferably it should only be executed once, alternatively before each test - or before some large subset of all the tests. I imagine that it out to be possible to have a “global” setup method which all tests can extend. Is this possible?</p>
",https://stackoverflow.com/questions/59991383/is-it-possible-to-have-a-global-setup-method-in-spock-test,"['java', 'unit-testing', 'grails', 'groovy', 'spock']",1493,True,0,2
How to capture logs with logCaptor or MOCKITO?,"<p>I am following these solution:</p>
<p><a href=""https://github.com/Hakky54/log-captor"" rel=""nofollow noreferrer"">https://github.com/Hakky54/log-captor</a></p>
<p><a href=""https://dzone.com/articles/unit-testing-log-messages-made-easy"" rel=""nofollow noreferrer"">https://dzone.com/articles/unit-testing-log-messages-made-easy</a></p>
<p>i am using</p>
<pre><code>            &lt;groupId&gt;io.github.hakky54&lt;/groupId&gt;
            &lt;artifactId&gt;logcaptor&lt;/artifactId&gt;
            &lt;version&gt;2.2.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
</code></pre>
<p>My code is exactly same like:</p>
<pre><code>package com.filter.requeststatistics.writer;

import com.testutil.data.TestDataUtil;
import nl.altindag.log.LogCaptor;
import org.junit.Test;

import java.util.List;
public class StatisticsModuleImplTest {


    @Test
    public void testSuccessCall(){

        RequestStatisticsInput input = TestDataUtil.createFilledTestData(RequestStatisticsInput.class);
        input.getBrandId();

        LogCaptor logCaptor = LogCaptor.forClass(StatisticsModuleImpl.class);

        StatisticsModuleImpl statisticsModule = new StatisticsModuleImpl();
        statisticsModule.writeRequestStatistic(input);

        List&lt;String&gt; infoLogs = logCaptor.getInfoLogs();
        //List&lt;String&gt; logs = logCaptor.getLogs();
        //List&lt;String&gt; debugLogs = logCaptor.getDebugLogs();
        //List errorLogs = logCaptor.getErrorLogs();
        //logs.size();
        //assertThat(logCaptor.getLogs()).containsExactly(&quot;a&quot;);

    }
</code></pre>
<p>but infoLogs size is zero (and also other log types when set are also zero)</p>
<p>my StatisticsModuleImpl class is:</p>
<pre><code>package com.filter.requeststatistics.writer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class StatisticsModuleImpl implements StatisticsModule {

    private static final Logger LOGGER = LogManager.getLogger(StatisticsModuleImpl.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void writeRequestStatistic(RequestStatisticsInput input) {

        try {
            String jsonString = mapper.writeValueAsString(input);
            LOGGER.info(&quot;received request: &quot; + jsonString);
        } catch (JsonProcessingException ignored) {
            // Should never happen, nevertheless we should not stop serving requests if it does.
            LOGGER.error(&quot;Exception while trying to log request statistic: &quot; + input.toString(), ignored);
        }

    }

}
</code></pre>
<p>I am not able to understand whats the problem ???? All the imports are same. When i debug my test, the field logCaptor.listAppender, there the i dont see any Appenders. My log4j.properties file is:</p>
<pre><code>log4j.rootLogger=DEBUG, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
</code></pre>
<p>and log4j2.xml is</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Configuration&gt;
    &lt;Properties&gt;
        &lt;Property name=&quot;log-path&quot;&gt;target/logs&lt;/Property&gt;
    &lt;/Properties&gt;
    &lt;Appenders&gt;
        &lt;Console name=&quot;stdout&quot; target=&quot;SYSTEM_OUT&quot;&gt;
            &lt;PatternLayout pattern=&quot; %-5p %d{ABSOLUTE} %5p %c{1}:%L - %m%n&quot;/&gt;
        &lt;/Console&gt;
        &lt;File name=&quot;testlogfile&quot; fileName=&quot;${log-path}/test.log&quot; append=&quot;false&quot;&gt;
            &lt;PatternLayout&gt;
                &lt;Pattern&gt;%d{ABSOLUTE} %5p %c{1}:%L - %m%n&lt;/Pattern&gt;
            &lt;/PatternLayout&gt;
            &lt;ThresholdFilter level=&quot;info&quot;  onMatch=&quot;ACCEPT&quot; onMismatch=&quot;DENY&quot;/&gt;
        &lt;/File&gt;
    &lt;/Appenders&gt;
    &lt;Loggers&gt;
        &lt;Root level=&quot;DEBUG&quot; additivity=&quot;false&quot; includeLocation=&quot;true&quot; &gt;
            &lt;AppenderRef ref=&quot;testlogfile&quot;/&gt; 
            &lt;AppenderRef ref=&quot;stdout&quot;/&gt; 
        &lt;/Root&gt;
    &lt;/Loggers&gt;
&lt;/Configuration&gt;
</code></pre>
",https://stackoverflow.com/questions/64880276/how-to-capture-logs-with-logcaptor-or-mockito,"['logging', 'mockito', 'log4j']",3515,True,3,1
Jest - spyOn does not code cover actual implementation,"<p>I working on Jest Unit testing for Typescript, I created a method </p>

<pre><code>addNumbers:() {
     return 6;
}
</code></pre>

<p>it is just a static test method for testing purpose.</p>

<p>I created a Unit Test using jest</p>

<pre><code>spyOn(object, 'addNumbers').mockReturnValue(6);
expect(object.addNumbers).toHaveBeenCalled(); // expect is success
</code></pre>

<p>The Unit test is working fine, but while checking the Code Coverage ""return 6;"" is not covered. </p>

<p>Not sure what is missing , configuration or any other issues.</p>

<p>Because once this is working , need to implement in actual Code.</p>

<p>If any other information is required, please let me know.</p>

<p>Thanks in Advance... </p>
",https://stackoverflow.com/questions/61459254/jest-spyon-does-not-code-cover-actual-implementation,"['typescript', 'jestjs', 'code-coverage']",1099,False,-2,2
How to solve &quot;Package org is not accessible&quot; error in eclipse while importing org.junit.Assert.*?,"<p>I am following a tutorial on unit testing from school and wrote JUnit tests for a method in a class. This is what the files look like : <a href=""https://i.stack.imgur.com/h9beV.png"" rel=""nofollow noreferrer"">enter image description here</a></p>

<p>Why am I getting this error? All the annotations like @AfterClass are also underlined with error ""cannot resolve @AfterClass to a type"" How do I fix this ? I have programmed in Java for a year now but this is my first time using eclipse and writing JUnit test cases.</p>
",https://stackoverflow.com/questions/61629034/how-to-solve-package-org-is-not-accessible-error-in-eclipse-while-importing-or,['eclipse'],4735,True,0,2
Javax.naming.NameNotFoundException: when trying to look up the jndi name in JavaEE and Wildfly,"<p>I am doing some unit testing using javaee and wildly so I am in the client project trying to lookup the jndi name remotely in order to test a service located of course in the ejb, all is fine and the handshake is done correctly but while testing I am getting an exeception which is:</p>
<pre><code>test.ServiceLocatorException: javax.naming.NameNotFoundException:
/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
</code></pre>
<p>Here is a snippet showing the appname, modulename and this is how I am trying to lookup the jndi:</p>
<pre><code>java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
    java:app/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote
    java:module/ClientSessionBean!utilities.CllientSessionBeanRemote
    java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanLoacal
    java:app/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanLoacal
    java:module/ClientSessionBean!utilities.CllientSessionBeanLoacal
</code></pre>
<p>Client Code:</p>
<pre><code>public class JunitTester {

public static final String jndi = &quot;java:global/phenomenon-ear/phenomenon-ejb/ClientSessionBean!utilities.CllientSessionBeanRemote&quot; ;
private static CllientSessionBeanRemote getProxy() {
    return (CllientSessionBeanRemote) ServiceLocator.getInstance().getProxy(jndi);
}


@org.junit.Test
public void Test() throws NamingException {
System.out.println(JunitTester.getProxy().Verify_No_Existence(&quot;Multiskan&quot;));}
</code></pre>
<p>Any advice could help, thanks.</p>
",https://stackoverflow.com/questions/62983300/javax-naming-namenotfoundexception-when-trying-to-look-up-the-jndi-name-in-java,"['wildfly', 'jndi', 'java-ee-7', 'java-ee-8']",1528,False,0,1
Jest unit test - mock value of async function within async function,"<p>In my React project, I'm unit testing an async function that calls another async function.</p>

<pre><code>//SomeComponent.js
getAllJobs = async () =&gt; {
    var allJobStatuses = new Array();
    for(var endpointForRegion in this.props.regionalEndpointsMap) {
        let jobStatusesForRegion = await getJobStatuses(endpoint);
        allJobStatuses = allJobStatuses.concat(jobStatusesForRegion);
....
    }
    return allJobStatuses;
}

getJobStatuses = async (endpoint) =&gt; {
   const response = await fetch(endpoint, {
   ......
   return await response.json();
}
</code></pre>

<pre><code>//SomeComponentTest.js
describe('&lt;SomeComponent /&gt;', () =&gt; {
    ....
    beforeEach(() =&gt; {
        props = {regionalEndpointsMap: {
             'region1': 'region1ep',
             'region2': 'region2ep'
        }};
        wrapper = shallow(&lt;SomeComponent {...props} /&gt;);
    });
    it('should get jobs for all regions', async () =&gt; {
        var startTime = new Date();
        let mockdata = {[
            {
            jobId: 'id',
            }
        ]};

        jest.spyOn(wrapper.instance(), 'getJobStatuses').mockResolvedValue(data);
        let allJobs = wrapper.instance.getAllJobs();
        let expectedData = [
            {jobId:'id'},
            {jobId:'id'}
        ];
        expect(allJobs).toEqual(expectedData);
}
</code></pre>

<p>Though every time this is tested, the result ends up just being an empty Promise {} instead of the expectedData.
I've tried many implementations I've found online for mocking the result of the async 'getJobStatuses' function with no luck (showing the implementation I used from <a href=""https://stackoverflow.com/questions/56736193/jest-test-fails-for-async-function-that-calls-another-async-function"">here</a>. What would be the correct way to mock a result for this function, for the purposes of testing the function calling it (getAllJobs)</p>
",https://stackoverflow.com/questions/61069413/jest-unit-test-mock-value-of-async-function-within-async-function,"['javascript', 'reactjs', 'unit-testing', 'asynchronous', 'jestjs']",562,False,0,1
How do I stub AJAX requests whose response depends on data passed?,"<p>I'm trying to do unit testing with Jasmine. I need to mock two AJAX GET requests to the same URL but whose responses depend on the data passed in the request. So far I've been unable to find any information on how to make the response depend on anything but the URL.</p>

<p>I've been trying to use the <code>stubRequest</code> method:</p>

<pre><code>   jasmine.Ajax.stubRequest('MY_URL.json')
      .andReturn({
        ""status"": 200,
        ""contentType"": 'application/json',
        ""responseText"": rawData
      });
</code></pre>

<p>I should also mention that the AJAX requests are made in an arbitrary order. Also the data passed is just a single parameter.</p>
",https://stackoverflow.com/questions/60628161/how-do-i-stub-ajax-requests-whose-response-depends-on-data-passed,"['javascript', 'ajax', 'unit-testing', 'jasmine', 'client-side']",712,False,0,2
How do I get my Django serializer to save my foreign key objects?,"<p>I'm using Python 3.8 and Django 3.  I have the following models.  Notice the second has foreign keys to the first ...</p>
<pre><code>class ContactMethod(models.Model):
    class ContactTypes(models.TextChoices):
        EMAIL = 'EMAIL', _('Email')
        PHONE = 'PHONE', _('Phone')

    type = models.CharField(
        null=False,
        max_length=5,
        choices=ContactTypes.choices,
    )
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)

    class Meta:
        unique_together = ('phone', 'email',)


class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    addresses = models.ManyToManyField(Address)
    enabled = models.BooleanField(default=True, null=False)
    phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
    email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
    web_site = models.TextField()
</code></pre>
<p>Using the Django rest framework, I have crated the following serializers to help save data ...</p>
<pre><code>class ContactMethodPhoneSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContactMethod
        fields = ['type', 'phone']
        read_only_fields = ['type']
        extra_kwargs = {'type': {'default': 'PHONE'}}


class CoopSerializer(serializers.ModelSerializer):
    types = CoopTypeSerializer(many=True, allow_empty=False)
    addresses = AddressTypeField(many=True)
    phone = ContactMethodPhoneSerializer()
    email = ContactMethodEmailSerializer()

    class Meta:
        model = Coop
        fields = '__all__'

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['types'] = CoopTypeSerializer(instance.types.all(), many=True).data
        rep['addresses'] = AddressSerializer(instance.addresses.all(), many=True).data
        return rep

    def create(self, validated_data):
        &quot;&quot;&quot;
        Create and return a new `Snippet` instance, given the validated data.
        &quot;&quot;&quot;

        coop_types = validated_data.pop('types', {})
        phone = validated_data.pop('phone', {})
        email = validated_data.pop('email', {})
        instance = super().create(validated_data)
        for item in coop_types:
            coop_type, _ = CoopType.objects.get_or_create(name=item['name'])
            instance.types.add(coop_type)
        instance.phone = ContactMethod.objects.create(type=ContactMethod.ContactTypes.PHONE, **phone)
        instance.email = ContactMethod.objects.create(type=ContactMethod.ContactTypes.EMAIL, **email)
        return instance
</code></pre>
<p>However, in unit testing (and actual), when I attempt to save data like so</p>
<pre><code>    serializer_data = {
        &quot;name&quot;: name,
        &quot;types&quot;: [
            {&quot;name&quot;: coop_type_name}
        ],
        &quot;addresses&quot;: [{
            &quot;formatted&quot;: street,
            &quot;locality&quot;: {
                &quot;name&quot;: city,
                &quot;postal_code&quot;: postal_code,
                &quot;state&quot;: state.id
            }
        }],
        &quot;enabled&quot;: enabled,
        &quot;phone&quot;: {
          &quot;phone&quot;: phone
        },
        &quot;email&quot;: {
          &quot;email&quot;: email
        },
        &quot;web_site&quot;: web_site
    }

    serializer = CoopSerializer(data=serializer_data)
    assert serializer.is_valid(), serializer.errors
    coop_saved = serializer.save()
    coop = Coop.objects.get(pk=coop_saved.id)
    ...
    assert coop.phone.phone == phone
</code></pre>
<p>The foreign key fields (email and phone) are not saving (they are null).  All the other fields save properly.  What else am I missing in order to save my foreign key fields successfully?</p>
",https://stackoverflow.com/questions/63065639/how-do-i-get-my-django-serializer-to-save-my-foreign-key-objects,"['python-3.x', 'django', 'django-models', 'django-rest-framework', 'django-serializer']",829,True,0,1
HTML Canvas Testing With Jest-Puppeteer (Javascript),"<p>I have a signature component (React.js) that requires testing with the automation suite I've built with Jest-Puppeteer. The component is a <code>&lt;canvas&gt;</code> HTML element. </p>

<p><code>&lt;canvas width=""1316"" height=""500"" style=""width: 100%; touch-action: none;""&gt;&lt;/canvas&gt;</code></p>

<p>I have found this npm package: <a href=""https://www.npmjs.com/package/jest-canvas-mock"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/jest-canvas-mock</a> and another solution on StackOverflow: <a href=""https://stackoverflow.com/questions/4406864/html-canvas-unit-testing"">HTML Canvas Unit testing</a></p>

<p>But, I was wondering if someone could give a much more comprehensive explanation of how exactly one could automate a process on a <code>&lt;canvas&gt;</code> tag and then assert it ideally with Jest-Puppeteer, i.e. how does <code>ctx</code> work, it's properties, etc. </p>

<p>Thank you! </p>
",https://stackoverflow.com/questions/61313724/html-canvas-testing-with-jest-puppeteer-javascript,"['javascript', 'reactjs', 'canvas', 'jestjs', 'jest-puppeteer']",2536,True,2,2
How to test class components in react,"<p>I am trying some unit testing, I created a sandbox with a fake example <a href=""https://codesandbox.io/s/wizardly-hooks-32w6l"" rel=""noreferrer"">https://codesandbox.io/s/wizardly-hooks-32w6l</a> (in reality I have a form)</p>

<pre><code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { number: 0 };    
  }

  handleSubmit = (number1, number2) =&gt; {
    this.setState({ number: this.handleMultiply(number1, number2) })
  }

  handleMultiply = (number1, number2) =&gt; {
    return number1 * number2
  }

  render() {
    const { number } = this.state;

    return (
      &lt;div className=""App""&gt;
        &lt;form onSubmit={e =&gt; this.handleSubmit(3, 7)}&gt;       
          &lt;input type=""submit"" name=""Submit"" value=""Multiply"" /&gt;
        &lt;/form&gt;
        &lt;Table number={number} /&gt;
      &lt;/div&gt;
    );
  }
}

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

<p>So my initial idea was to try to test the multiply function. And did this, which obviously doesn't work</p>

<pre><code>import App from ""../src/App"";

test(""Multiply"", function() {
  const expected = 21;
  const result = App.handleMultiply(3, 7);
  expect(result).toBe(expected);
});
</code></pre>

<p>I get</p>

<blockquote>
  <p>_App.default.handleMultiply is not a function</p>
</blockquote>

<p>Is my approach right? If yes then how do I test the functions? Else, should I test from a user point of view instead of for internal functions (this is what I read)? Should I test for the output on the screen (I don't think this is reasonable)?</p>
",https://stackoverflow.com/questions/59796928/how-to-test-class-components-in-react,"['javascript', 'reactjs', 'jestjs']",1651,True,10,1
Chaining Ajax calls fail after upgrading jQuery to 3.x,"<p>I'm working on a very old project with the following frameworks for unit testing:
QUnit 1.14.0,
Sinon 1.17.2,
jQuery 1.12.4</p>
<p>This unit test works fine with jQuery 1.x and 2.x. But after upgrading to 3.x, I got error <code>requests[1] is undefined</code>, which means the second AJAX call is not caught. I read the <a href=""https://jquery.com/upgrade-guide/3.0/"" rel=""nofollow noreferrer"">3.0 doc</a> and it seems 3.0 has a new version of Deferred which was changed to behave like the native Promise object. But I'm not sure how that could screw up the tests.</p>
<pre><code>function doSomething(successCallback, failureCallback) {
    var promise = firstCall()
           .then(secondCall);

    if (successCallback) {
        promise.done(successCallback);
    }
        
    if (failureCallback) {
        promise.fail(failureCallback);
    }
    return promise;
}
</code></pre>
<pre><code>function firstCall() {
    return $.ajax({
           url: 'No1.aspx',
           type: 'HEAD'
        });
}
function secondCall() {
    return $.ajax({
           url: 'No2.aspx',
           type: 'GET'
        });
}
</code></pre>
<pre><code>QUnit.test('correct sequence of AJAX calls', function (assert) {
    var server = this.sandbox.useFakeServer();

    doSoemthing(this.successHandler, this.failureHandler);

    // Simulate successful responses to the two expected AJAX requests
    server.requests[0].respond('success');
    server.requests[1].respond('success');

    assert.equal( 1, &quot;1&quot;, &quot;dummy&quot; );
});
</code></pre>
",https://stackoverflow.com/questions/64684029/chaining-ajax-calls-fail-after-upgrading-jquery-to-3-x,"['javascript', 'jquery', 'ajax', 'sinon', 'jquery-deferred']",101,False,2,0
"JUnit, IntegrationTest and Test Execution Order","<p>Junit is a framework for unit testing but it is also used for integration testing. The behaviour required for unit testing and integration tests are different. Unit tests are supposed to be isolated from other tests. But integration tests require interaction between consecutive tests. In my case sceanario is as follows. Each line requires the object from the previous execution. To achieve this behaviour there should be an execution order of tests. There is an @Order annotation but this annotation orders the methods of a single class. But in my case it is not proper to keep these test in a single class.</p>

<ul>
<li>Create a customer</li>
<li>Create a hierarchical billing account for this customer</li>
<li>Create a contract for the customer</li>
<li>Sell some hierarchical item for customer</li>
<li>Sell some non-hierarchical item for customer</li>
</ul>

<p>A proposal may be to make these operations for each test. For example to create a hierarchical billing account, create a customer first in the test. This scheme is not an optimum solution, has complexities too. </p>

<ul>
<li>Would increase required run time.</li>
<li>Would increase complexity for a single test.</li>
</ul>

<p>So is there a way for me to order my tests in Junit that I am missing? If not why it is not? Should I use another tool?</p>
",https://stackoverflow.com/questions/61682066/junit-integrationtest-and-test-execution-order,"['junit', 'junit5']",203,False,0,0
How to unit test with Jasmine when FormGroup is set to disabled?,"<p>I havea a angular 8 application  and I am using Jasmine Karma for unit testing. And I want to test a Formbuilder that is disabled in the NgOninit function:</p>
<p>I have it like this: component.ts</p>
<pre><code>constructor(
    private dossierService: DossierService,
    private route: ActivatedRoute,
    private sanitizer: DomSanitizer,
    private dossierFileService: DossierFileService,
    private errorProcessor: ErrorProcessor,
    private dialog: MatDialog
  ) {
    this.dossierItems = this.route.snapshot.data.dossierItems;
    this.editDossierForm = this.formBuilder.group({});
    this.editDossierForm.disable();
 
    this.dossier = this.route.snapshot.data.dossier;
    this.dossierItems = route.snapshot.data.dossierItems;
    this.profileImagefile = this.route.snapshot.data.profileImage;
 
    this.editDossierForm = this.formBuilder.group({
      firstName: this.formBuilder.control(this.dossier.firstName, [Validators.required, Validators.maxLength(255)]),
      lastName: this.formBuilder.control(this.dossier.lastName, [Validators.required, Validators.maxLength(255)]),
      mobile: this.formBuilder.control(this.dossier.mobile, [Validators.maxLength(255)]),
      company: this.formBuilder.control(this.dossier.company, [Validators.maxLength(255)]),
      buddy: this.formBuilder.control(this.dossier.buddy, [Validators.maxLength(255)]),
      supervisor: this.formBuilder.control(this.dossier.supervisor, [Validators.maxLength(255)]),
      dateOfBirth: this.formBuilder.control(this.dossier.dateOfBirth)
    });
  }
  ngOnInit(): void {
    this.editDossierForm.disable();
  }
}
</code></pre>
<p>and this is the spec file of it:</p>
<pre><code>
describe('DossierPersonalDataComponent', () =&gt; {
  let component: DossierPersonalDataComponent;
  let fixture: ComponentFixture&lt;DossierPersonalDataComponent&gt;;

  beforeEach(async(() =&gt; {


    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, DossierModule, BrowserModule],
      declarations: [DossierPersonalDataComponent],
      providers: [
          DossierFileService,
          ErrorProcessor,
          {
            provide: ActivatedRoute,
            useValue: {
              snapshot: {
                data: {
                  dossier: {
                    firstName: 'hello',
                    lastName: 'world',
                    mobile: '111-111-1111',
                    company: 'carapax',
                    buddy: 'bud',
                    supervisor: 'super',
                    dateOfBirth: '1900-01-01',
                  },
                  dossierItems: [], // mock
                  profileImage: '',
                }
              }
            }
          },
        {
          // DossierFileService, These have to be outside of the braces
          // ErrorProcessor,

          provide: DomSanitizer,
          useValue: {
            sanitize: () =&gt; 'safeString',
            bypassSecurityTrustHtml: () =&gt; 'safeString'
          }
        }
      ]
    })
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(DossierPersonalDataComponent);
        component = fixture.componentInstance;
      });
  }));


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

</code></pre>
<p>but in the instanbul coverage rapport this stays red:</p>
<pre><code>  }
  ngOnInit(): void {
    this.editDossierForm.disable();
  }
</code></pre>
<p>So how to coverage this part?</p>
<p>Thank you</p>
<p>oke,</p>
<p>if I do it like this:</p>
<pre><code>  it('should create', () =&gt; {    
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

</code></pre>
<p>I get this error:</p>
<pre><code>DossierPersonalDataComponent &gt; should create
TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
</code></pre>
<p>and in my tesspec, I see this:</p>
<pre><code> get profileImageUrl() {
    return this.profileImagefile === null
      ? '/assets/placeholder.jpg'
      : this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.profileImagefile));
  }
</code></pre>
<p>and this line:</p>
<pre><code> ? '/assets/placeholder.jpg'
</code></pre>
<p>is in yellow. Branch not covered.</p>
",https://stackoverflow.com/questions/63880268/how-to-unit-test-with-jasmine-when-formgroup-is-set-to-disabled,"['javascript', 'angular', 'karma-jasmine']",1130,True,1,1
Using a common test utility file for projects built in SBT,"<p>Given a project using a <code>build.sbt</code> file, I would like to have a common <code>TestUtils.scala</code> file which the integration and unit tests both rely upon.</p>
<p>I have my src folder at <code>src/scala</code> and my integration testing folder at <code>it/scala</code>. My unit testing folder is at <code>test/scala</code>, and contains the common <code>TestsUtils.scala</code> file.</p>
<p>Currently I am running my tests through ScalaTest in Intellij. When I run it this way Intellij is able to determine the dependency from the integration testing folder on the unit testing folder. I am attempting to switch over to using a <code>test</code>, <code>it:test</code> and <code>unit:test</code> set of SBT tasks. When I do so the integration testing folder fails to compile since it can't find the common <code>TestUtils.scala</code> file. If I copy the <code>TestUtils.scala</code> file over to my integration testing folder then it does compile but I don't want to have the same code in 2 locations.</p>
<p>Here are the approaches I see to resolve this:</p>
<ol>
<li>Copy the file into both test folders (bad)</li>
<li>Move the file into the <code>src</code> folder (introduces <code>src</code> reliance on <code>scalatest</code> which I would prefer to avoid)</li>
<li>Find a way for the <code>integration</code> folder to use the file from the <code>test</code> folder (don't know how to do this)</li>
</ol>
<p>Ideally I would like to use the third approach but don't know how to actually implement it. How do you get one folder to use another folder as a dependency in SBT? Is there a better approach I'm unaware of?</p>
",https://stackoverflow.com/questions/63272825/using-a-common-test-utility-file-for-projects-built-in-sbt,"['scala', 'unit-testing', 'sbt', 'integration-testing']",269,True,5,1
Implication branch doesn&#39;t see variables,"<p>Here is a little test:</p>

<pre><code>:- begin_tests(tuturuu).

test(foo) :- Expected=[a,b],Got=[a,b,c],verdict(foo,Expected,Got).

% helper: transform lists A,B into ordered sets As,Bs

setify(A,B,As,Bs) :-      % A,B -&gt; As,Bs
   list_to_ord_set(A,As), % A-&gt;As
   list_to_ord_set(B,Bs). % B-&gt;Bs

% did the test pass? set-compare Expected and Got

verdict(Value,Expected,Got) :-   % V,E,G -&gt; b?
   setify(Expected,Got,Eos,Gos),  
   format(""For ~w, expected ~w and got ~w\n"",[Value,Eos,Gos]),
   ord_seteq(Eos,Gos)
   -&gt; true ; (format(""For ~w, expected ~w but got ~w\n"",[Value,Eos,Gos]),fail).

:- end_tests(tuturuu).


rt :- run_tests(tuturuu).
</code></pre>

<p>When I load this into SWI-Prolog:</p>

<pre><code>?- [foo].
Warning: /home/somone/foo.pl:13:
Warning:    Singleton variable in branch: Eos
Warning:    Singleton variable in branch: Gos
true.
</code></pre>

<p>The <code>-&gt;</code> branch doesn't have access to the (local) variables <code>Eos</code> and <code>Gos</code>? But why?</p>

<p>It has access to <code>Value</code> because that one appears in the head I suppose.</p>

<p>And indeed:</p>

<pre><code>?- rt.
% PL-Unit: tuturuu For foo, expected [a,b] and got [a,b,c]
For foo, expected _29026 but got _29032                       &lt;--- YUP NO ACCESS
ERROR: /home/someone/foo.pl:3:
        test foo: failed

 done
% 1 test failed
% 0 tests passed
false.
</code></pre>

<p>It don't really see why this restriction occurs, expect that maybe it's a part that hasn't been implemented in the compiler?</p>

<p>(Btw, we need one of those ""keep the bar in the green windows"" for unit testing from the Java World, like this: (stolen from <a href=""https://netbeans.org/kb/docs/java/junit-intro.html]"" rel=""nofollow noreferrer"">here</a>)</p>

<p><a href=""https://i.stack.imgur.com/ZSBw7.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZSBw7.png"" alt=""junit test bar""></a></p>
",https://stackoverflow.com/questions/61079055/implication-branch-doesnt-see-variables,"['prolog', 'implication']",48,True,1,1
Unable to import module in my Jest test file,"<p>I am writing my unit tests for few services that i have written. My services and components are written in Typescript.
My understanding is that its unable to parse my typescript.
I am importing one such service in my unit test. I am using jest for unit testing.
Without import, test is working fine</p>

<p>My </p>

<p>package.json</p>

<pre><code>{
  ""name"": ""web"",
  ""version"": ""0.1.0"",
  ""private"": true,
  ""dependencies"": {
    ""@date-io/core"": ""^1.3.6"",
    ""@material-ui/core"": ""^4.0.1"",
    ""@material-ui/icons"": ""^4.9.1"",
    ""@testing-library/dom"": ""&gt;=5"",
    ""@testing-library/jest-dom"": ""^4.2.4"",
    ""@testing-library/react"": ""^9.3.2"",
    ""@testing-library/user-event"": ""7.2.1"",
    ""@types/jest"": ""^24.0.0"",
    ""@types/js-cookie"": ""^2.2.6"",
    ""@types/jwt-decode"": ""^2.2.1"",
    ""@types/lodash"": ""^4.14.150"",
    ""@types/node"": ""^12.0.0"",
    ""@types/react"": ""^16.9.0"",
    ""@types/react-dom"": ""^16.9.0"",
    ""@types/react-router-dom"": ""^5.1.4"",
    ""@types/reactstrap"": ""^8.4.2"",
    ""@types/recharts"": ""^1.8.9"",
    ""@typescript-eslint/eslint-plugin"": ""^2.28.0"",
    ""@typescript-eslint/parser"": ""^2.28.0"",
    ""axios"": ""^0.19.2"",
    ""bootstrap"": ""4.4.1"",
    ""clsx"": ""^1.1.0"",
    ""cross-env"": ""^7.0.2"",
    ""eslint"": ""6.8.0"",
    ""eslint-config-airbnb"": ""18.1.0"",
    ""eslint-config-prettier"": ""^6.10.1"",
    ""eslint-plugin-import"": ""^2.20.1"",
    ""eslint-plugin-jsx-a11y"": ""^6.2.3"",
    ""eslint-plugin-prettier"": ""^3.1.3"",
    ""eslint-plugin-react"": ""^7.19.0"",
    ""eslint-plugin-react-hooks"": ""2.5.0"",
    ""jquery"": ""3.0.0"",
    ""js-cookie"": ""^2.2.1"",
    ""jwt-decode"": ""^2.2.0"",
    ""lodash"": ""^4.17.15"",
    ""material-table"": ""1.57.2"",
    ""moment"": ""^2.24.0"",
    ""popper.js"": ""^1.16.0"",
    ""prettier"": ""^2.0.4"",
    ""prop-types"": ""^15.7.2"",
    ""react"": ""^16.8.4"",
    ""react-dom"": ""^16.8.4"",
    ""react-router-dom"": ""^5.1.2"",
    ""react-scripts"": ""3.4.1"",
    ""reactstrap"": ""^8.4.1"",
    ""recharts"": ""^1.8.5"",
    ""typescript"": ""~3.7.2""
  },
  ""scripts"": {
    ""start"": ""CI=true react-scripts start"",
    ""build"": ""react-scripts build"",
    ""test"": ""react-scripts test"",
    ""eject"": ""react-scripts eject"",
    ""lint"": ""tsc --noEmit &amp;&amp; eslint \""**/*.{js,jsx,ts,tsx}\"" --fix""
  },
  ""eslintConfig"": {
    ""extends"": ""react-app""
  },
  ""browserslist"": {
    ""production"": [
      ""&gt;0.2%"",
      ""not dead"",
      ""not op_mini all""
    ],
    ""development"": [
      ""last 1 chrome version"",
      ""last 1 firefox version"",
      ""last 1 safari version""
    ]
  },
  ""devDependencies"": {}
}
</code></pre>

<p>tsconfig.json</p>

<pre><code>{
  ""compilerOptions"": {
    ""target"": ""es5"",
    ""lib"": [
      ""dom"",
      ""dom.iterable"",
      ""esnext""
    ],
    ""allowJs"": true,
    ""skipLibCheck"": true,
    ""esModuleInterop"": true,
    ""allowSyntheticDefaultImports"": true,
    ""strict"": true,
    ""forceConsistentCasingInFileNames"": true,
    ""module"": ""esnext"",
    ""moduleResolution"": ""node"",
    ""resolveJsonModule"": true,
    ""isolatedModules"": true,
    ""noEmit"": true,
    ""jsx"": ""react""
  },
  ""include"": [
    ""src""
  ],
  ""files"": [
    ""src/types.d.ts""
  ]
}
</code></pre>

<p>test that i created </p>

<pre><code>import axios from 'axios';
test(""Check if Company Details exists"", () =&gt; {
  expect(false).toBe(false);
});
</code></pre>

<p>Issue I received </p>

<p><img src=""https://i.stack.imgur.com/LzlQB.png"" alt=""Error""></p>

<p><img src=""https://i.stack.imgur.com/k0oQW.png"" alt=""Error""></p>

<p>Also, it is clearly visible that test suite hasn't run itself</p>

<p>I tried different things but not to any help so far.</p>
",https://stackoverflow.com/questions/61853050/unable-to-import-module-in-my-jest-test-file,"['reactjs', 'typescript', 'configuration', 'jestjs', 'package.json']",11470,True,1,3
Will unittest work for functional (non-object-oriented) program in Python?,"<p>I'm a beginner programmer, I've been stuck for the past week trying to write unit tests.  I read through the unit test docs and watched two long tutorials on implementing unit testing with <code>Mock</code>.  The docs refer to mocking classes extensively, but for functions, I'm not sure if I should be using <code>@patch/with patch</code>, <code>patch.dict{}</code>, <code>side_effect</code>, or some other option to mock a function, specifically the argument to a function.</p>
<p><strong>mymodule.py</strong></p>
<pre><code>def regex():
    '''Runs a regex, creates a dict 'data' and then calls scraper(data)'''

def scraper(data):
    '''scrapes a website and then calls a function which submits data to a db'''
</code></pre>
<p>I would like to create a test that passes in test data to the function <code>scraper</code> .  Thank you in advance.</p>
",https://stackoverflow.com/questions/62945167/will-unittest-work-for-functional-non-object-oriented-program-in-python,"['python', 'unit-testing', 'mocking']",259,True,1,2
Stencil unit test: access deeply nested Shadow DOM components,"<p>I have a <code>Stencil.js</code> component library with some nested elements that I'm unit testing</p>

<p>I'm using the <code>newSpecPage</code> helper functionality provided by Stencil:</p>

<pre class=""lang-js prettyprint-override""><code>const page = await newSpecPage({
    components: [CustomFileInput, CustomPanel],
    html: `
      &lt;custom-file-input multiple&gt;                    
      &lt;/custom-file-input&gt;
    `
});
</code></pre>

<p>The <code>CustomPanel</code> component is nested within the <code>CustomFileInput</code> component. To query elements within <code>CustomPanel</code> I have to step down through <code>Shadow DOM</code> elements before being able to run a <code>querySelector()</code> command successfully</p>

<pre class=""lang-js prettyprint-override""><code>// page.root is the CustomFileInput HTML Element
const customPanelElement = page.root.shadowRoot.querySelector('custom-panel');
const queriedElemnt = customPanelElement.shadowRoot.querySelector('panel-child')
</code></pre>

<p>I'm wondering is there a more concise way to get a reference to the <code>CustomPanel</code> or <code>panel-child</code> elements rather than querying down through the components? In the above case there's just 2 components, but there could be more of course</p>
",https://stackoverflow.com/questions/61560334/stencil-unit-test-access-deeply-nested-shadow-dom-components,"['ionic-framework', 'jestjs', 'stenciljs']",1943,True,1,1
Invalid attempt to destructure non-iterable instance while using react testing library,"<p>I am trying to do a functional test for my React App, my component has a div with <code>data-testid=""btnHeaderCategory""</code>, on click of the div I have to update the style of the body 
I am using react and <a href=""https://testing-library.com/docs/intro"" rel=""nofollow noreferrer"">react testing library</a> for unit testing.</p>

<p>I am updating the style of the body with
<code>document.body.style.overflow = ""hidden"";</code></p>

<p>Here is my component </p>

<pre><code>import React, {useState} from ""react"";

const Main = () =&gt; { 
    const [flag, updateFlag] = useState(false);
    const getCategory = () =&gt; {
        updateFlag(true);
        document.body.style.overflow = ""hidden"";
    }
    return(
        &lt;div onClick={getCategory} data-testid=""btnHeaderCategory""&gt;
            {flag ? &lt;div data-testid=""megaMenu"" &gt; New categories &lt;/div&gt; : """"}
        &lt;/div&gt;
    )
}

export default Main;

</code></pre>

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

<pre><code>import { render, fireEvent, cleanup, waitForElement } from '@testing-library/react';

describe(""components/Main"",()=&gt;{
    let Main;

    beforeAll(()=&gt;{
      Main = require('./Main').default;

    });
    afterAll(() =&gt; {
      cleanup();
    });
    test(""Test if categories shown"", async()=&gt;{

      const { getByTestId } = render(
        &lt;Main /&gt;
      );
      fireEvent.click(getByTestId('btnHeaderCategory'));
      const elem = getByTestId('megaMenu'));
      expect(elem).toBeInTheDocument();

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

<p>When I try to run the test, it breaks with the following error</p>

<p><em>TypeError: Invalid attempt to destructure non-iterable instance</em></p>

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

<p>Jest configuration</p>

<pre><code>
var baseConfig = {
   collectCoverageFrom: [
    '&lt;rootDir&gt;/**/*.js',
    '!**/node_modules/**',
    '!&lt;rootDir&gt;/coverage/**',
    '!&lt;rootDir&gt;/jest.config.js',
    '!**/__tests__/**',
  ],
  coverageThreshold: {
    global: {
      statements: 100,
      branches: 100,
      functions: 100,
      lines: 100,
    },
  },
};

module.exports = {
  ...baseConfig,
  collectCoverageFrom: [baseConfig.collectCoverageFrom, '!&lt;rootDir&gt;/build/**'],
  coverageReporters: ['json', 'lcov', 'text', 'clover', 'html'],
  coverageThreshold: {
    global: {
      statements: 0.5,
      branches: 0.1,
      functions: 0.1,
      lines: 0.5,
    },
  },
  projects: [
    createProject({
      displayName: 'Configuration',
      testMatch: ['&lt;rootDir&gt;/__tests__/**/*.js'],
      testEnvironment: 'node',
    }),
    createProject({

      displayName: 'Client',
      testMatch: ['&lt;rootDir&gt;/client/**/__tests__/**/*.js'],
      testEnvironment: 'jsdom',

    }),
  ],
}
</code></pre>
",https://stackoverflow.com/questions/59602356/invalid-attempt-to-destructure-non-iterable-instance-while-using-react-testing-l,"['javascript', 'reactjs', 'jestjs', 'react-testing-library']",2676,True,1,2
How to use Glide within screenshot-tests-for-android tests,"<p>Hi im new to Android Unit Testing and try to make some Screenshot tests with facebooks : screenshot-tests-for-android. So the first components are fine but now im on an component that utilize Glide to load an Picture. How can i use it in screenshot-tests-for-android ? For now i got this exception</p>
<p>Task :app:connectedDevDebugAndroidTest
Starting 5 tests on EML-L29 - 8.1.0</p>
<p>ViewModelTests emptyViewModel[EML-L29 - 8.1.0] FAILED</p>
<p>java.lang.IllegalArgumentException: You must call this method on the main thread</p>
<p>at com.bumptech.glide.util.Util.assertMainThread(Util.java:142)</p>
",https://stackoverflow.com/questions/63742190/how-to-use-glide-within-screenshot-tests-for-android-tests,"['android', 'unit-testing', 'junit']",228,False,1,1
Is it possible to expect dispatch command from a non axon-class in AxonFramework,"<p>Suppose I have some classes which is not axon class (etc. Saga or agrgregate), and if I want it to dispatch command I could use command gateway, but here is the problem.  I want to write
unit testing to make sure that this non axon-class has dispatched command already. So if it's either saga or aggregate I could use fixture and then given command or event, but is it possible to use fixture with these non axon-class also.<br />
Here is how the code looks like</p>
<pre><code>class MyService {
    //...
    lateinit var commandGateway: CommandGateway
    fun doSomething(command: doSomethingCommand){
        commandGateway.send(command)
    }
}

class MyServiceTest {
    //...
    @Test
    fun doSomething_ShouldDispatchDoSomethingCommand(){
        // expect dispatch command from non axon-class
    }
}
</code></pre>
",https://stackoverflow.com/questions/62873159/is-it-possible-to-expect-dispatch-command-from-a-non-axon-class-in-axonframework,"['kotlin', 'axon']",257,True,1,1
How to write Unit test in angular for testing routing code inside subscribe block,"<p>I am new to unit testing in jasmine and karma for angular, here I am trying to test the router navigation, here we have a service to which some data is sent and inside the subscribe block I am navigating to a link,</p>
<p>For this how can I write a unit test.</p>
<p>CODE FOR THE FUNCTION INSIDE TS FILE.</p>
<pre><code>onAction(action) {
   
    if (action == true) {
        this.data.action = action;
        this.data.loggedInId = this.id;
        this.Formservice.formMethod(this.data).subscribe(() =&gt; {
        this.router.navigate([`/${this.breadCrum}`]);
    });
    }
   }
</code></pre>
<p>CODE FOR THE SPEC.TS FILE</p>
<pre><code>it(&quot;Check the router navigate after onAction&quot;,fakeAsync(()=&gt; {        
        component.onAction(true)
        flushMicrotasks()
        tick(10)
        fixture.detectChanges()
        tick(10)
        expect (mockRouter.navigate).toHaveBeenCalledWith ('/action-taken');
    }));
</code></pre>
<p>STEPS I FOLLOWED TO CREATE MOCK ROUTER SERVICE</p>
<pre><code>import { Routes, RouterModule, ActivatedRoute, Router } from '@angular/router';

let mockRouter = {
    navigate: jasmine.createSpy('navigate')
  }

providers:[
{ provide: Router, useValue: mockRouter}
]
</code></pre>
<p>Here am I getting the error of <strong>Cannot read property of 'subscribe' of undefined</strong></p>
",https://stackoverflow.com/questions/62882369/how-to-write-unit-test-in-angular-for-testing-routing-code-inside-subscribe-bloc,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",864,True,1,1
Set unit test for raised exception in property setter,"<p>I am using property setter and raising errors if inputs are not the expected type. I am also unit testing all functions and want to test that the exception is actually raised when using the setter.</p>

<p>I try to get a callable to give to <code>unittest.TestCase.assertRaises</code>. Here is an example:</p>

<pre><code>import unittest

class A:
    def __init__(self, num):
        self.var = num

    @property
    def var(self):
        return self._var

    @var.setter
    def var(self, new):
        if not isinstance(new, int):
            raise TypeError
        self._var = new

class TestA(unittest.TestCase):
    def test_a_setter(self):
        a = A(5)
        self.assertRaises(TypeError, a.var = 'a') #&lt;--- a not working try

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

</code></pre>

<p>Is there a way to get the setter callable ? Else, I'll just use <code>try ... except</code> block, but this doesn't look like a clean solution.</p>

<p>Another idea I got is to use <code>setattr</code> but this doesn't work with property.</p>
",https://stackoverflow.com/questions/61309922/set-unit-test-for-raised-exception-in-property-setter,"['python', 'unit-testing', 'properties', 'callable']",481,True,1,1
Unit testing VueJs with Jest and Typescript - components not mounted,"<p>We are building an app with VueJs. We have previous experience with Angular unit testing with Jasmine and karma, so we decided to use Typescript for our VueJs app.</p>

<p>Currently I have written very simple specs for components, but it seems like the components are not getting mounted.</p>

<p>Here is an example of a <strong>component</strong>:</p>

<pre class=""lang-js prettyprint-override""><code>export default class TableOverview extends Vue {
  public mounted() {
    console.log(""mounted"");
  }
}
</code></pre>

<p>Here is my <strong>spec</strong>:</p>

<pre class=""lang-js prettyprint-override""><code>describe(""table-overview.vue"", () =&gt; {
  it(""logs mounted"", () =&gt; {
    const wrapper = mount(TableOverview);

    expect(wrapper).toBeDefined();
  });
});
</code></pre>

<p>I don't see anything in the console log.</p>

<p>What am I missing? This project was set with <strong>Vue CLI v4.3.1</strong></p>

<p>Here is the Vue <strong>info</strong>:</p>

<pre class=""lang-sh prettyprint-override""><code>  System:
    OS: Windows 10 10.0.18363
    CPU: (8) x64 Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz
  Binaries:
    Node: 8.11.3 - C:\Program Files\nodejs\node.EXE
    Yarn: Not Found
    npm: 5.6.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: 44.18362.449.0
  npmPackages:
    @vue/babel-helper-vue-jsx-merge-props:  1.0.0
    @vue/babel-plugin-transform-vue-jsx:  1.1.2
    @vue/babel-preset-app:  4.2.3
    @vue/babel-preset-jsx:  1.1.2
    @vue/babel-sugar-functional-vue:  1.1.2
    @vue/babel-sugar-inject-h:  1.1.2
    @vue/babel-sugar-v-model:  1.1.2
    @vue/babel-sugar-v-on:  1.1.2
    @vue/cli-overlay:  4.2.3
    @vue/cli-plugin-babel: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-eslint: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-router:  4.2.3
    @vue/cli-plugin-typescript: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-unit-jest: ~4.2.0 =&gt; 4.2.3
    @vue/cli-plugin-vuex: ~4.2.0 =&gt; 4.2.3
    @vue/cli-service: ~4.2.0 =&gt; 4.2.3
    @vue/cli-shared-utils:  4.2.3
    @vue/component-compiler-utils:  3.1.1
    @vue/eslint-config-prettier: ^6.0.0 =&gt; 6.0.0
    @vue/eslint-config-typescript: ^5.0.1 =&gt; 5.0.2
    @vue/preload-webpack-plugin:  1.1.1
    @vue/test-utils: 1.0.0-beta.31 =&gt; 1.0.0-beta.31
    @vue/web-component-wrapper:  1.2.0
    eslint-plugin-vue: ^6.1.2 =&gt; 6.2.2
    jest-serializer-vue:  2.0.2
    typescript: ~3.7.5 =&gt; 3.7.5
    vue: ^2.6.11 =&gt; 2.6.11
    vue-class-component:  7.2.3
    vue-eslint-parser:  7.0.0
    vue-hot-reload-api:  2.3.4
    vue-jest:  3.0.5
    vue-loader:  15.9.1
    vue-property-decorator: ^8.3.0 =&gt; 8.4.1
    vue-style-loader:  4.1.2
    vue-template-compiler: ^2.6.11 =&gt; 2.6.11
    vue-template-es2015-compiler:  1.9.1
    vuetify: ^2.2.25 =&gt; 2.2.25
    vuetify-loader: ^1.4.3 =&gt; 1.4.3
    vuex: ^3.1.2 =&gt; 3.1.3
    vuex-class: ^0.3.2 =&gt; 0.3.2
    vuex-module-decorators: ^0.17.0 =&gt; 0.17.0
  npmGlobalPackages:
    @vue/cli: Not Found
</code></pre>
",https://stackoverflow.com/questions/61894798/unit-testing-vuejs-with-jest-and-typescript-components-not-mounted,"['typescript', 'unit-testing', 'vue.js', 'jestjs', 'vue-component']",1674,True,1,1
Laravel unit testing assert functions always failing,"<p>I have created a very basic unit testing class under Laravel root-->tests-->Unit-->SimpleTest.php</p>

<p>Inside the file i have import the controller class that i need to test. And test function is like this.</p>

<pre><code>class SimpleTest extends TestCase
{
   public function testLoadUsers()
   {
     $controller_obj = new UsersController;
     $data_status = $controller_obj-&gt;load_users();
        if($data_status != null){
           $this-&gt;assertTrue(true);
         }
        else{
           $this-&gt;assertTrue(false);
         }
    }

  }
</code></pre>

<p>I executed this test case in Artisan console like this,</p>

<pre><code>php vendor/phpunit/phpunit/phpunit tests/Unit/SimpleTest.php
</code></pre>

<p>Always this fails. My controller function returning data as well without an issue. I tested without defining any condition and just,</p>

<pre><code>$this-&gt;assertTrue(true);
</code></pre>

<p>Then it works. So i assume there is no any issue with the phpunit test command as well.</p>
",https://stackoverflow.com/questions/60312026/laravel-unit-testing-assert-functions-always-failing,"['laravel', 'unit-testing', 'phpunit', 'laravel-unit-test']",598,False,1,1
How to start a BaseX Unit Test Module in a XQuery script?,"<p>I have pairs of XML databases that i want to iterate through and use it as input for unit tests. I'm using <a href=""https://docs.basex.org/wiki/Unit_Module#Query"" rel=""nofollow noreferrer"">BaseX Unit Testing Module</a>. To give an example <code>validate.xqm</code> looks like this:</p>
<pre><code>module namespace test=&quot;mytests&quot;;
 
declare variable $test:fibexDB external;
declare variable $test:autosarDB external;
 
declare variable $test:fibex := db:open($test:fibexDB);
declare variable $test:autosar := db:open($test:autosarDB);
 
declare %unit:test function test:validateCountSignals() {
  let $countSignalsFBX := count($test:fibex//*:SIGNAL)
  let $countSignalsASR := count($test:autosar//*:SYSTEM-SIGNAL)
  return unit:assert-equals($countSignalsFBX,$countSignalsASR + 5,concat('Database:',$test:fibexDB))
};
 
declare %unit:test function test:validateOEMExtension() {
  let $countOEMExtensionsFBX := count($test:fibex//*:OEM-SPECIFIC-EXTENSIONS)
  return unit:assert-equals($countOEMExtensionsFBX,1,concat('Database:',$test:fibexDB))
}; 
</code></pre>
<p>I know that the tests can be started with the TEST command or on the command line like this:</p>
<pre><code>\bin\basex -oC:\UnitTestConverter\FlexRayTestResult.xml -b{mytests}fibexDB=DB01A -b{convertertests}autosarDB=DB01B -t validate.xqm
</code></pre>
<p>Is it also possible to start <code>validate.xqm</code> in a XQuery script? Or is there any other X-technology solution that let iterate through a set of input values and start one or more unit test modules?</p>
",https://stackoverflow.com/questions/63473955/how-to-start-a-basex-unit-test-module-in-a-xquery-script,"['unit-testing', 'xquery', 'basex']",125,True,1,1
&quot;&#39;str&#39; object is not callable&quot; after I tried to break the circular import (Django),"<p>I have been trying to solve this circular import issue in order to implement unit testing without failure. If I may show you the short version of the previous solution I got:</p>
<p>This....</p>
<pre><code>serializer_class = serializers.CompanyMappingSerializer
</code></pre>
<p>should be changed to This:</p>
<pre><code>serializer_class = &quot;serializers.CompanyMappingSerializer&quot;
</code></pre>
<p>After doing this, the unit tests run fine. However, when I run the api with POSTMAN, it shows this error:</p>
<pre><code>TypeError at /api/v1/company/
'str' object is not callable
</code></pre>
<p>What should I do in this situation?</p>
<p>P.S.:
For more information here is the full traceback:</p>
<pre><code>Traceback:

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py&quot; in inner
  34.             response = get_response(request)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py&quot; in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py&quot; in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py&quot; in wrapped_view
  54.         return view_func(*args, **kwargs)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py&quot; in view
  114.             return self.dispatch(request, *args, **kwargs)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py&quot; in dispatch
  505.             response = self.handle_exception(exc)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py&quot; in handle_exception
  465.             self.raise_uncaught_exception(exc)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py&quot; in raise_uncaught_exception
  476.         raise exc

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/views.py&quot; in dispatch
  502.             response = handler(request, *args, **kwargs)

File &quot;/Users/nick/work/shiftwork_backend/api/views/company.py&quot; in list
  74.             serializer = self.get_serializer(page, many=True)

File &quot;/Users/nick/myvenv/lib/python3.8/site-packages/rest_framework/generics.py&quot; in get_serializer
  110.         return serializer_class(*args, **kwargs)

Exception Type: TypeError at /api/v1/company/
Exception Value: 'str' object is not callable
</code></pre>
<p>and below is the more detailed version of api/company.py</p>
<pre><code>...
...
from api.models import Company, Pattern, UserCompany, CompanyMapping, Category, COUNTRY_CODE_CHOICES
from statistics.models import CompanySearch
# from api.serializers import CompanySerializer, PatternSerializer, UserCompanySerializer, CompanyMappingSerializer, CategorySerializer
from api import serializers
from api.views import get_user_company_by_local_id, get_user_pattern_by_local_id
...
...
class CompanyMappingViewSet(viewsets.ModelViewSet):
    queryset = CompanyMapping.objects.all()
    serializer_class = serializers.CompanyMappingSerializer
    permission_classes = (IsAuthenticated,)
</code></pre>
",https://stackoverflow.com/questions/64853750/str-object-is-not-callable-after-i-tried-to-break-the-circular-import-djang,"['python', 'django']",187,True,1,2
Angular Test: Use Data Type Any to Mock Classes and Services,"<p>I am mocking services without TestBed and using Fake Classes.
Is it good practice to use a Mock with <code>: any</code> data type below?
If not I receive following errors, missing items/parameters.</p>
<p>I could use spyOn, but it requires TestBed, and I am trying to avoid getting rid of all executable-run time error, 'with injectable import not found' with testBed.</p>
<p><a href=""https://medium.com/angular-in-depth/angular-testbed-considered-harmful-3f91f647d1fd"" rel=""nofollow noreferrer"">https://medium.com/angular-in-depth/angular-testbed-considered-harmful-3f91f647d1fd</a></p>
<p><a href=""https://dev.to/angular/unit-testing-in-angular-to-testbed-or-not-to-testbed-3g3b"" rel=""nofollow noreferrer"">https://dev.to/angular/unit-testing-in-angular-to-testbed-or-not-to-testbed-3g3b</a></p>
<pre><code>  class ConfigMgmtServiceMock {
    modifyLkDocumentDiscardReasonPost() : Observable&lt;any&gt; { 
      let data = 'test';
      return of(data);
    };
  }

  let configMgmtServiceMock: any = new ConfigMgmtServiceMock();
  let snackBarMock : any = new SnackBarMock();

  beforeEach(() =&gt; {
    configMgmtServiceMock = new ConfigMgmtServiceMock();
    snackBarMock = new SnackBarMock();
    component = new DocumentDiscardLookupEditorComponent(null, configMgmtServiceMock, snackBarMock);
    component.gridRef = new GridMock() as any;
  });
</code></pre>
<p><a href=""https://i.stack.imgur.com/0bHEW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0bHEW.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/65177774/angular-test-use-data-type-any-to-mock-classes-and-services,"['angular', 'typescript', 'karma-jasmine', 'angular10']",529,True,1,1
Spring Integration Tests for Resource Server (based on spring-cloud-starter-oauth2),"<p>I am using Spring Boot and Spring Cloud for a oAuth2 resource server. This is the configuration:</p>
<p>pom.xml</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
    &lt;artifactId&gt;spring-security-acl&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
    &lt;artifactId&gt;spring-cloud-starter-oauth2&lt;/artifactId&gt;
&lt;/dependency&gt;

...
</code></pre>
<pre class=""lang-xml prettyprint-override""><code>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
&lt;version&gt;2.3.4.RELEASE&lt;/version&gt;
</code></pre>
<pre class=""lang-xml prettyprint-override""><code>&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
&lt;version&gt;Hoxton.SR8&lt;/version&gt;
</code></pre>
<p>ResourceServerConfig</p>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Value(&quot;${my-app.security.audience}&quot;)
    private String audience;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(audience);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .cors().and()
                .httpBasic().disable()
                .formLogin().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests(authorize -&gt; authorize
                    .antMatchers(&quot;/actuator/**&quot;).permitAll() // TODO: Enable basic auth for actuator
                    .anyRequest().authenticated()
                );
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration().applyPermitDefaultValues();
        corsConfiguration.addAllowedMethod(&quot;PATCH&quot;);
        source.registerCorsConfiguration(&quot;/**&quot;, corsConfiguration);
        return source;
    }

    @Bean
    public ResourceServerProperties resourceServerProperties() {
        return new ResourceServerProperties(null, null);
    }
}
</code></pre>
<p>OidcJwkTokenStoreConfig</p>
<pre class=""lang-java prettyprint-override""><code>@Configuration
public class OidcJwkTokenStoreConfig {
    private final ResourceServerProperties resource;

    public OidcJwkTokenStoreConfig(ResourceServerProperties resource) {
        this.resource = resource;
    }

    @Bean
    public TokenStore jwkTokenStore(UserDetailsService userDetailsService) {
        DefaultAccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
        tokenConverter.setUserTokenConverter(new MvcUserAuthenticationConverter(userDetailsService));
        return new JwkTokenStore(this.resource.getJwk().getKeySetUri(), tokenConverter);
    }
}
</code></pre>
<p>Custom User Authentication Converter</p>
<pre class=""lang-java prettyprint-override""><code>public class MvcUserAuthenticationConverter implements UserAuthenticationConverter {
    private final String SUB = &quot;sub&quot;;
    private final UserDetailsService userDetailsService;

    public MvcUserAuthenticationConverter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Map&lt;String, ?&gt; convertUserAuthentication(Authentication userAuthentication) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Authentication extractAuthentication(Map&lt;String, ?&gt; map) {
        if (map.containsKey(SUB)) {
            Object principal = map.get(SUB);
            Collection&lt;? extends GrantedAuthority&gt; authorities = getAuthorities(map);
            if (userDetailsService != null) {
                UserDetails user = userDetailsService.loadUserByUsername((String) map.get(SUB));
                authorities = user.getAuthorities();
                principal = user;
            }
            return new UsernamePasswordAuthenticationToken(principal, &quot;N/A&quot;, authorities);
        }
        return null;
    }

    private Collection&lt;? extends GrantedAuthority&gt; getAuthorities(Map&lt;String, ?&gt; map) {
        if (!map.containsKey(AUTHORITIES)) {
            return null;
        }
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection&lt;?&gt;) authorities));
        }
        throw new IllegalArgumentException(&quot;Authorities must be either a String or a Collection&quot;);
    }
}
</code></pre>
<h2>How to do integration tests?</h2>
<p>Unit Testing is not a big problem. But when it comes to Integration Tests, I'm struggling. How can I mock/skip providing a real bearer token? Prefered solution would be using <code>MockMvc</code> for Integration Tests.</p>
<p>I got the following so far:</p>
<pre class=""lang-java prettyprint-override""><code>@SpringBootTest
@Testcontainers
@ContextConfiguration(
        initializers = ProjectResourceTest.Initializer.class,
        classes = {ProjectResourceTest.ApiTestConfiguration.class, MyApplication.class}
)
@AutoConfigureMockMvc
public class ProjectResourceTest {
    @Container
    private static final MongoDBContainer mongoDB = new MongoDBContainer(&quot;mongo:4.2.5&quot;);

    public static class Initializer implements ApplicationContextInitializer&lt;ConfigurableApplicationContext&gt; {

        @Override
        public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
            TestPropertyValues values = TestPropertyValues.of(
                    &quot;spring.data.mongodb.uri=&quot; + mongoDB.getReplicaSetUrl()
            );
            values.applyTo(configurableApplicationContext);
        }
    }

    @TestConfiguration
    public static class ApiTestConfiguration {
        @Bean
        @Primary
        public UserDetailsService userDetailsService() {
            MvcUser defaultUser = new MvcUser(&quot;default-user&quot;, &quot;Default User&quot;);

            return new InMemoryUserDetailsManager(singletonList(defaultUser));
        }
    }

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    MongoTemplate mongo;

    @Test
    @WithUserDetails(&quot;default-user&quot;)
    void shouldReturnAllProjects() throws Exception {
        ProjectEntity project = ProjectFaker.newProjectEntity();
        mongo.save(project);

        mockMvc.perform(get(&quot;/api/v1/projects&quot;))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;$.key&quot;, is(project.getKey())))
                .andExpect(jsonPath(&quot;$.name&quot;, is(project.getName())))
                .andExpect(jsonPath(&quot;$.createdAt&quot;, is(project.getCreatedAt())));
    }
}
</code></pre>
<p>But this approach ends in the following exception</p>
<pre><code>java.lang.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(setupBefore=TEST_METHOD, userDetailsServiceBeanName=, value=default-user)

    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:126)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:96)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.beforeTestMethod(WithSecurityContextTestExecutionListener.java:62)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
    at org.springframework.test.context.junit.jupiter.SpringExtension.beforeEach(SpringExtension.java:108)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$1(TestMethodTestDescriptor.java:161)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:197)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:197)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:160)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.core.userdetails.UserDetailsService' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.findUserDetailsService(WithUserDetailsSecurityContextFactory.java:78)
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:58)
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:44)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:123)
    ... 61 more
</code></pre>
<p>My custom UserDetailsService</p>
<pre class=""lang-java prettyprint-override""><code>@Service
public class MvcUserDetailsService implements UserDetailsService {
    private final UserRepository userRepository;

    @Autowired
    public MvcUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional&lt;UserEntity&gt; user = userRepository.findByUserId(username);

        if (user.isPresent()) {
            return new MvcUser(user.get());
        } else {
            return createNewUser();
        }
    }
    ...
}
</code></pre>
<p>What am I missing here?</p>
",https://stackoverflow.com/questions/64529187/spring-integration-tests-for-resource-server-based-on-spring-cloud-starter-oaut,"['spring-boot', 'spring-security', 'oauth-2.0', 'spring-oauth2', 'spring-test-mvc']",2414,True,0,1
What exactly does @Test annotation of Kotlin test methods do?,"<p>When writing unit tests in Kotlin, test methods are typically annotated @Test. What exactly does this do?</p>

<p>That is, I understand at the black-box level, the answer is 'it causes them to be recognized by unit testing frameworks like JUnit'. But I'd like to be able to look inside the box (ideally by a more direct route than reading the ~80,000 lines of code comprising the latest version of JUnit). Is it documented anywhere, exactly how the annotation is recognized and what happens when it is?</p>
",https://stackoverflow.com/questions/61538978/what-exactly-does-test-annotation-of-kotlin-test-methods-do,"['java', 'unit-testing', 'kotlin', 'junit']",143,True,0,1
AskTimeoutException during Embedded Kafka Unit testing Akka Java,"<p>I am working on <strong>akka</strong> with <strong>Kafka</strong> and writing test cases for my Kafka Consumer.
I used Embedded Kafka for unit testing.</p>

<p>When i try to run my test case everything goes fine, but in last following Exception occurred:</p>

<pre><code>akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://testActor/system/StreamSupervisor-0/flow-0-1-mapAsyncUnordered#-2130769]] after [1000 ms]. Message of type [akka.stream.impl.fusing.ActorGraphInterpreter$Snapshot$] was sent by [Actor[akka://testActor/system/StreamSupervisor-0#-867168141]]. A typical reason for `AskTimeoutException` is that the recipient actor didn't send a reply.

at akka.pattern.PromiseActorRef$.$anonfun$defaultOnTimeout$1(AskSupport.scala:675)
at akka.pattern.PromiseActorRef$.$anonfun$apply$1(AskSupport.scala:696)
at akka.actor.Scheduler$$anon$4.run(Scheduler.scala:202)
at scala.concurrent.Future$InternalCallbackExecutor$.unbatchedExecute(Future.scala:875)
at scala.concurrent.BatchingExecutor.execute(BatchingExecutor.scala:113)
at scala.concurrent.BatchingExecutor.execute$(BatchingExecutor.scala:107)
at scala.concurrent.Future$InternalCallbackExecutor$.execute(Future.scala:873)
at akka.actor.LightArrayRevolverScheduler$TaskHolder.executeTask(LightArrayRevolverScheduler.scala:334)
at akka.actor.LightArrayRevolverScheduler$$anon$3.executeBucket$1(LightArrayRevolverScheduler.scala:285)
at akka.actor.LightArrayRevolverScheduler$$anon$3.nextTick(LightArrayRevolverScheduler.scala:289)
at akka.actor.LightArrayRevolverScheduler$$anon$3.run(LightArrayRevolverScheduler.scala:241)
at java.lang.Thread.run(Thread.java:748)
</code></pre>

<p>Here is my code.</p>

<p>My Test method is:</p>

<pre><code>@Test
public void publishMessage() {

    final TestKit probe = new TestKit(system);
    final Config config = system.settings().config().getConfig(""akka.kafka.producer"");
    ActorRef childMaker = probe.getTestActor();

    final ProducerSettings&lt;String, String&gt; producerSettings =
            ProducerSettings.create(config, new StringSerializer(), new StringSerializer())
                    .withBootstrapServers(bootstrapServers);

    Source.range(1, 10)
            .map(Object::toString)
            .map(value -&gt; new ProducerRecord&lt;&gt;(topic, 0, ""key1"", value))
            .runWith(Producer.plainSink(producerSettings), materializer);

    new EventFilter(Logging.Info.class, system)
            .occurrences(1)
            .matches(""Starting up Consumer:"")
            .matches(""Consumer Started:"")
            .intercept(() -&gt; TestActorRef
                    .create(system, KafkaConsumerPlainExternalSource.props(new RequestRegisterConsumer(system,
                            config, bootstrapServers, groupId, topic, (byte) 0, childMaker))));

}
</code></pre>

<p>My KafkaConsumer Class looks like: </p>

<pre><code>public class KafkaConsumerPlainExternalSource extends AbstractLoggingActor {

private static RequestRegisterConsumer consumerConf;

static Props props(RequestRegisterConsumer consumerConf) {
    return Props.create(KafkaConsumerPlainExternalSource.class, consumerConf);
}

public KafkaConsumerPlainExternalSource(RequestRegisterConsumer consumerConf) {
    KafkaConsumerPlainExternalSource.consumerConf = consumerConf;
}

@Override
public Receive createReceive() {
    return receiveBuilder().build();
}

@Override
public void preStart() {

    log().info(""Starting up Consumer: "" + self().path().toString());

    //Update
akka.kafka.javadsl.Consumer.plainExternalSource(consumer, Subscriptions
                .assignment(new TopicPartition(consumerConf.getTopic(), consumerConf.getTopicPartition())))
                .mapAsync(10, Consumer :: consume)
                .to(Sink.ignore())
                .run(ActorMaterializer.create(consumerConf.getActorSystem()));
    log().info(""Consumer Started: "" + self().path().toString());
}
</code></pre>

<p>}</p>

<p>My application.conf file is:</p>

<pre><code>&gt;    akka { 
&gt;   loggers = [akka.testkit.TestEventListener] 
&gt;     test {
&gt;     timefactor = 1.0
&gt;     filter-leeway = 10s
&gt;     calling-thread-dispatcher {
&gt;       type = akka.testkit.CallingThreadDispatcherConfigurator
&gt;     }   }   kafka.producer {//producer conf} }
</code></pre>

<p>When i add a sleep of 10 sec in last of my test case than my test runs fine. I could not find the root cause of this Exception.</p>
",https://stackoverflow.com/questions/60112945/asktimeoutexception-during-embedded-kafka-unit-testing-akka-java,"['java', 'apache-kafka', 'akka', 'akka-stream']",549,False,0,0
How do I stub a module method&#39;s callback with sinon?,"<p>I'm using the mv module to move files, an older module that still gets a lot of downloads and has been helpful in dealing with moving files between docker volumes and also outside of docker. I created a method to treat mv method as a promise.</p>

<p>When unit testing, I'm struggling to mock mv when used within a method.</p>

<pre><code>import mv from 'mv';

export class CmdUtils {
  /**
   * Move a file to a new location. Using mv, this will attempt a mv command, however
   * this could fail with docker volumes and will fallback to the mv module streaming
   * data to the new location as needed.
   * @param filePath - Full path to file
   * @param destinationFilePath - Full path to file's new destination
   */
  public static moveFile = (filePath: string, destinationFilePath: string): Promise&lt;void&gt; =&gt; {
    return new Promise((resolve, reject) =&gt; {
      mv(filePath, destinationFilePath, err =&gt; {
        if (!err) {
          resolve();
        } else {
          console.error('moveFile err', err);
          reject(err);
        }
      });
    });
  }
}
</code></pre>

<p>Here's a starting test with gaps:</p>

<pre><code>import mv from 'mv';
import { CmdUtils } from './cmd-utils';

describe(""CmdUtils: moveFile"", () =&gt; {
  it(""should successfully move a file using mv module"", async () =&gt; {
    const sandbox = sinon.createSandbox();
    try {
      const moveFromPath = '/full/path/to/file.jpg';
      const moveToPath = '/full/path/to/destination/file.jpg';

      // Starting attempt at a replacement callback
      const mvCallback = (err: Error) =&gt; {
        if (!err) {
          Promise.resolve();
        } else {
          console.error('moveFile err', err.message);
          Promise.reject(err);
        }
      }

      // Stub mv
      sandbox.stub(mv)
      // What am I missing here?

      // Move file
      await CmdUtils.moveFile(moveFromPath, moveToPath);

      // expect no errors... (will revisit this)
    } finally {
      sandbox.restore();
    }
  });
});
</code></pre>

<p>How do I mock a successful file move? I'm seeing similar questions, yet not finding an answer just yet.</p>
",https://stackoverflow.com/questions/61141090/how-do-i-stub-a-module-methods-callback-with-sinon,"['node.js', 'typescript', 'mocha.js', 'chai', 'sinon']",155,True,0,1
Pre loading data from .sql before unit testing throws syntax error,"<p>I'm performing unit testing on spring boot app using JPA and SpringJUnit4ClassRunner. for that I have created a configuration file as - </p>

<pre><code>
@Configuration
@EnableJpaRepositories(basePackages = ""base_package_name"")
@EnableTransactionManagement
public class JPAConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(""org.postgresql.Driver"");
        dataSource.setUrl(""jdbc:postgresql://localhost:5432/employeedb_test"");
        dataSource.setUsername(""postgres"");
        dataSource.setPassword(""postgres"");

        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put(""hibernate.dialect"", ""org.hibernate.dialect.PostgreSQL9Dialect"");        
        properties.put(""hibernate.hbm2ddl.auto"", ""create"");
        properties.put(""hibernate.show_sql"", ""true"");
        properties.put(""hibernate.format_sql"", ""false"");
        return properties;
    }

    @Bean(name=""entityManagerFactory"")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setDataSource(this.dataSource());
        lcemfb.setPackagesToScan(new String[] {""Package_to_scan""});

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        lcemfb.setJpaVendorAdapter(va);

        lcemfb.setJpaProperties(this.hibernateProperties());

        lcemfb.afterPropertiesSet();

        return lcemfb;

    }


    @Bean
    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();

        tm.setEntityManagerFactory(
            this.entityManagerFactoryBean().getObject() );

        return tm;

    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }
}


</code></pre>

<p>My test class looks like this - </p>

<pre><code>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={
        JPAConfig.class,
        TestConfig.class
        })
@SqlGroup({
    @Sql(executionPhase=ExecutionPhase.BEFORE_TEST_METHOD,scripts=""classpath:beforeTestRun.sql"")
})
public class ExampleTest {
     ...
}

</code></pre>

<p>now I want to insert data from script file beforeTestRun.sql into entity before running any test. so I added following annotation above my test class(i.e. ExampleTest) - </p>

<pre><code>@SqlGroup({
    @Sql(executionPhase=ExecutionPhase.BEFORE_TEST_METHOD,scripts=""classpath:beforeTestRun.sql"")
})
</code></pre>

<p>my beforeTestRun.sql contains insert query - </p>

<pre><code>INSERT INTO employee(emp_name)
    VALUES ('Jhon Dave');
</code></pre>

<p>my model class is - </p>

<pre><code>
@Entity
@Table(name = ""employee"")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name=""emp_id"")
    Integer id;

    @Column(name=""emp_name"")
    String empName;


    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }


}

</code></pre>

<p>now after running test class, it trying to insert from .sql file but eventhough the syntax is correct it throwing an error says - </p>

<pre><code>org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of class path resource [beforeTestRun.sql]: INSERT INTO employee(emp_name) VALUES ('Jhon Dave'); nested exception is org.postgresql.util.PSQLException: ERROR: syntax error at or near ""INSERT""
  Position: 1
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:626)
    at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254)
    at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:49)
    at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.execute(ResourceDatabasePopulator.java:269)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$4(SqlScriptsTestExecutionListener.java:263)
    at org.springframework.transaction.support.TransactionOperations.lambda$executeWithoutResult$0(TransactionOperations.java:68)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
    at org.springframework.transaction.support.TransactionOperations.executeWithoutResult(TransactionOperations.java:67)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:263)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$0(SqlScriptsTestExecutionListener.java:185)
    at java.lang.Iterable.forEach(Unknown Source)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:185)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:147)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.beforeTestMethod(SqlScriptsTestExecutionListener.java:117)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near ""INSERT""
  Position: 1
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2497)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2233)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:311)
    at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:297)
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:274)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:269)
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:605)
    ... 35 more
</code></pre>

<p>Can you please suggest me on this??</p>
",https://stackoverflow.com/questions/60370765/pre-loading-data-from-sql-before-unit-testing-throws-syntax-error,"['java', 'postgresql', 'spring-boot', 'unit-testing', 'springjunit4classrunner']",877,True,3,1
Angular testing Service with params return an mocked observable,"<p>I'm still new to all different kinds of unit-testing and I'm once more stuck on a test for a service.</p>
<p>This is the function in my service I want to test:</p>
<pre><code>For your information:
this.setParams returns an object like {name: 'Test', id: 3}


  getDataCount(dataparams: Filter): Observable&lt;number&gt; {
    const url = 'http://blablabla.com';
    const params = this.setParams(dataparams);
    return new Observable&lt;number&gt;(observer =&gt; {
      this.httpc.get&lt;number&gt;(url, { params }).subscribe(
        (data) =&gt; {
          observer.next(data);
          observer.complete();
        }
      );
    }
    );
  }
</code></pre>
<p>The setup for my test is:</p>
<pre><code>describe('MyDataService', () =&gt; {
  let service: DataService;
  let mockParams: Filter;
  let mockCount: number;

  mockParams = { name: 'Test', id: 3 };
  mockCount = 358;

  beforeEach(() =&gt; {

    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
        ]
    });
    service = TestBed.inject(DataService);
  });
</code></pre>
<p>My test looks like this:</p>
<pre><code>  it('should return mockCount', async () =&gt; {
    const test = await service.getOperatingDataCount(mockParams).toPromise();
    expect(test).toBe(mockCount);
  });
</code></pre>
<p>but it's returning 'Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)'. I read other threads, too, but I'm still not able to figure out how to write an appropiate test for this. Can anyone point me to the right direction?</p>
",https://stackoverflow.com/questions/65307031/angular-testing-service-with-params-return-an-mocked-observable,"['angular', 'typescript', 'unit-testing', 'rxjs', 'jasmine']",2120,True,0,1
OSGI services not loading in Mockito unit tests,"<p>I have several service classes that are not loading in Mockito for unit testing. The services are being loaded in classes and Sling models using the @Reference and @Inject annotations.</p>

<p>The case is that I have several services and Sling models that are loading other services using the @Inject or @Reference annotations.</p>

<pre><code>public class MyModel{
    @Inject
    SomeService service;
}

public class MyService{
    @Reference
    SomeOtherService service;
}
</code></pre>

<p>Then when I have a unit test mock the service, the injected services are not loaded. How do I get them loaded into the mock context so that they load are tested as well?</p>
",https://stackoverflow.com/questions/60831382/osgi-services-not-loading-in-mockito-unit-tests,"['mockito', 'osgi', 'inject']",517,False,0,2
Angular unit test for component with service arguments,"<p>I am new to angular and unit testing, I am trying to write a unit test for the component with service where the service url is fetched from the <code>@Input()</code> value.</p>
<p><strong>cms-sonor.component.ts</strong></p>
<pre><code>export class CmsSonarComponent implements OnInit {
    @Input() configParam;
    sonarData;
    constructor(public cmsService: CmsService) {}

    ngOnInit(): void {
        this.cmsService
            .getData(this.configParam.url, { responseType: &quot;text&quot; })
            .subscribe(
                (resp) =&gt; {
                    this.sonarData = resp;
                },
                (err) =&gt; {
                    console.log(err);
                }
            );
    }
}
</code></pre>
<p><strong>cms-sonar.component.spec.ts</strong></p>
<pre><code>describe(&quot;CmsSonarComponent&quot;, () =&gt; {
    let component: CmsSonarComponent;
    let injector: TestBed;
    let fixture: ComponentFixture&lt;CmsSonarComponent&gt;;
    let service: CmsService;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            declarations: [CmsSonarComponent, SonorPipe],
            providers: [
                {
                    provide: CmsService,
                    useValue: {
                        getData: () =&gt; of({ id: 123, name: &quot;Product&quot; }),
                    },
                },
            ],
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(CmsSonarComponent);
        service = TestBed.get(CmsService);
        component = fixture.componentInstance;
        //fixture.detectChanges();
    });

    it(&quot;should create&quot;, () =&gt; {
        expect(component).toBeDefined();
    });

    it(&quot;testing cms sonar ngOnInit&quot;, () =&gt; {
        spyOn(service, &quot;getData&quot;).and.callThrough();
        component.ngOnInit();
        fixture.detectChanges();
        expect(service.getData).toHaveBeenCalledWith(&quot;/getData&quot;, &quot;json&quot;);
        expect(component.sonarData).toEqual({ id: 123, name: &quot;Product&quot; });
    });
});
</code></pre>
<p><strong>Error</strong>
<code>TypeError: Cannot read property 'url' of undefined</code></p>
<p>Can you let me known what mistake I am making? Any help is appreciated.</p>
<p>i even try with args like this <code>spyOn(service, 'getData') .withArgs('abc')</code></p>
<p><strong>Update-1</strong>
I was able resolve the above issue, URL was try to getting the input value.</p>
<pre><code>const configParam = {
    url: 'visible'
};
beforeEach(() =&gt; {
        fixture = TestBed.createComponent(CmsSonarComponent);
        service = TestBed.get(CmsService);
        component = fixture.componentInstance;
        component.configParam = configParam;
        //fixture.detectChanges();
    });
it('testing cms sonar ngOnInit', () =&gt; {
        spyOn(service, 'getData').and.callThrough();
        component.ngOnInit();
        fixture.detectChanges();
        expect(service.getData).toHaveBeenCalledWith('visible', {
            responseType: 'text'
        });
        expect(component.sonarData).toEqual({ id: 123, name: 'Product' });
    });
</code></pre>
<p>But now i am get this error</p>
<pre><code>Expected spy getData to have been called with:
  [ 'visible', Object({ responseType: 'text' }) ]
but actual calls were:
  [ 'visible' ],
  [ 'visible' ]
</code></pre>
<p>any guides on this is highly appreciated.</p>
",https://stackoverflow.com/questions/62673216/angular-unit-test-for-component-with-service-arguments,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",3581,False,0,0
unit testing of class without dependencies,"<p>Imagine I have the following class:</p>

<pre><code>public class MyWeirdCollection
{
    private IList&lt;string&gt; _myTrueList;
    private IList&lt;string&gt; _myFalseList;

    public MyCollection()
    {
        _myTrueList = new List&lt;string&gt;();
        _myFalseList = new List&lt;string&gt;();
    }

    public void Add(string item, bool listType)
    {
        if (listType)
        {
            _myTrueList.Add(item);
        }
        else
        {
            _myFalseList.Add(item);
        }
    }

    public IList&lt;string&gt; Get(bool listType)
    {
        return listType ? _myTrueList : myFalseList;
    }
}
</code></pre>

<p>How would I go about unit testing the <code>Get</code> and <code>Add</code> methods? I'm doubting between 2 possible solutions:</p>

<ol>
<li>Making the 2 lists protected instead of private, so I can create an inheriting <code>TestableWeirdCollectionClass</code> that exposes the content of the lists to the test</li>
<li>Leave the class as it is and test <code>Add</code> and <code>Get</code> together? i.e. calling <code>Add</code> to add some elements and then <code>Get</code> to see if the correct values come back.</li>
</ol>

<p>I'm leaning towards option no. 2, but would like some more opinions. Thanks.</p>
",https://stackoverflow.com/questions/61216734/unit-testing-of-class-without-dependencies,"['c#', 'unit-testing']",91,True,0,2
Laravel polymorphic many-to-many not detaching?,"<p>I have a polymorphic many to many <code>User</code>/<code>Location</code> - <code>Group</code> relationship, but I'm having a time getting the basic unit testing to pass.</p>

<pre class=""lang-php prettyprint-override""><code>/** @test */
public function it_can_have_groups()
{
    $user = factory(User::class)-&gt;create();
    $group = factory(Group::class)-&gt;create();

    $user-&gt;addToGroup($group);
    $this-&gt;assertCount(1, $user-&gt;groups);  // true

    $user-&gt;removeFromGroup($group);
    $this-&gt;assertCount(0, $user-&gt;groups);  // false
}
</code></pre>

<p>These methods simply call <code>attach</code> and <code>detach</code> as per the <a href=""https://laravel.com/docs/6.x/eloquent-relationships#updating-many-to-many-relationships"" rel=""nofollow noreferrer"">documentation</a>:</p>

<blockquote>
  <p>To remove a many-to-many relationship record, use the detach method. The detach method will delete the appropriate record out of the intermediate table; however, both models will remain in the database</p>
</blockquote>

<pre class=""lang-php prettyprint-override""><code>public function addToGroup(Group $group)
{
    $this-&gt;groups()-&gt;attach($group-&gt;id);
}

public function removeFromGroup(Group $group)
{
    $this-&gt;groups()-&gt;detach($group-&gt;id));
    dump($group-&gt;users());                 // []
}
</code></pre>

<p>So it seems to work (?), but only from the groups side, and the assertion still fails.  Why, and what should I be doing differently?</p>
",https://stackoverflow.com/questions/60662422/laravel-polymorphic-many-to-many-not-detaching,"['laravel', 'many-to-many', 'polymorphic-relationship']",108,True,0,1
"professional code template for Python project - include Modules, Packages, Unit Test, API / Help - IDE","<p>I'm trying to find an IDE that can build Python code templates for me to get started with a large Python project. It should include typical professional / production looking code with Python 3 style, Unit Testing, API/Documentation, Code Review, Packages / Modules, Errors / Exceptions etc etc</p>

<p>In Visual Studio I can build this in .NET quickly ... the Project Wizards build this quickly ... but am struggling to find an IDE that can do something similar for Python. </p>

<p>Any suggestion or push in the right direction is much appreciated.   </p>
",https://stackoverflow.com/questions/59581635/professional-code-template-for-python-project-include-modules-packages-unit,"['python', 'unit-testing', 'templates', 'ide']",155,False,-1,2
Does pytest provide a way of automatically reading properties for a test from a yml or conf file?,"<p>I'm using Python 3.8 and pytest for unit testing.  I have tests similar to the following</p>
<pre><code>def test_insert_record(az_sql_db_inst):
    &quot;&quot;&quot;.&quot;&quot;&quot;
    foreign_key_id = 10
</code></pre>
<p>I don't like hard-coding &quot;10&quot; in the file, and would prefer this be stored in some external configuration file where other tests can also access the value.  Does pytest provide a way to do this (to load the values from a properties or yml file)?  I could just open a file on my own, e.g.</p>
<pre><code>def test_insert_record(az_sql_db_inst):
    &quot;&quot;&quot;.&quot;&quot;&quot;
    file = open('test.txt')
    for line in file:
        fields = line.strip().split()
        foreign_key_id = fields[0]
</code></pre>
<p>but it seems like there is something that can automatically do that for me.</p>
",https://stackoverflow.com/questions/62836330/does-pytest-provide-a-way-of-automatically-reading-properties-for-a-test-from-a,"['python-3.x', 'unit-testing', 'pytest', 'configuration-files']",402,False,0,1
Unit testing angular and jasmine,"<p>How does one go about unit testing in angular something in the index.html file?</p>

<p>For example:  I want to create a unit test that checks that the body tag has a specific class assigned to it.  Is this possible</p>

<p>Most unit test or spec files are made for components but I cant seem to access the body tag.</p>

<p>this is a working css unit test for anything inside a component, just no idea how to get access to the body tag of the index.html page.</p>

<pre><code>
  it('should have class-name in body class tag', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);

    fixture.detectChanges();
    const compiled = fixture.debugElement;

    expect(compiled.query(By.css('.class-name'))).toBeTruthy();
  });

</code></pre>
",https://stackoverflow.com/questions/61602228/unit-testing-angular-and-jasmine,"['angular', 'unit-testing', 'jasmine']",1006,True,0,1
No provider for MockState,"<p>I am still figuring things out in regards to Angular Unit Testing. I believe this is my first time writing a unit test for a service from scratch. I have copy/pasted code from another and attempted to adapt it. Here's what I have so far:</p>

<pre><code>describe('SERVICE -&gt; EditServiceProcedureAuthorizationService', () =&gt; {
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpClientModule],
            providers: [
                EditServiceProcedureAuthorizationService,
                { provide: Store, useClass: MockStore },
                { provide: AuthorizationsService, useClass: MockAuthorizationsService },
                { provide: ServiceProcedureAuthorizationWorkflowService, useClass: ServiceProcedureAuthorizationWorkflowServiceMock },
                { provide: SpViewAuthorizationDetailsService, useClass: MockSpViewAuthorizationDetailsService }
            ]
        });
    });

    it('should loadAuthorization()', inject(
        [EditServiceProcedureAuthorizationService, Store, AuthorizationsService, ServiceProcedureAuthorizationWorkflowService,
                 SpViewAuthorizationDetailsService],
        fakeAsync(
            (
                editServiceProcedureAuthorizationService: EditServiceProcedureAuthorizationService,
                mockStore: MockStore&lt;AppStore&gt;,
                mockAuthorizationService: MockAuthorizationsService,
                mockServiceProcedureAuthWorkflowService: ServiceProcedureAuthorizationWorkflowServiceMock,
                mockSpViewAuthorizationDetailsService: MockSpViewAuthorizationDetailsService
            ) =&gt; {
                const dispatchSpy: Spy = spyOn(mockStore, 'dispatch');
                editServiceProcedureAuthorizationService.loadAuthorization(undefined, undefined);
                expect(dispatchSpy).not.toHaveBeenCalled();

                const memberId = '42';
                const authId = 'auth42';

                editServiceProcedureAuthorizationService.loadAuthorization(memberId, authId);
                expect(dispatchSpy).toHaveBeenCalledTimes(1);
            }
        )
    ));
});
</code></pre>

<p>Then, when I tried to run this, I got:</p>

<pre><code>Error: StaticInjectorError(DynamicTestModule)[Store -&gt; MockState]: 
  StaticInjectorError(Platform: core)[Store -&gt; MockState]: 
    NullInjectorError: No provider for MockState!
    at NullInjector.get node_modules/@angular/core/fesm5/core.js:8894:1)
    at resolveToken node_modules/@angular/core/fesm5/core.js:9139:1)
    at tryResolveToken node_modules/@angular/core/fesm5/core.js:9083:1)
    at StaticInjector.get node_modules/@angular/core/fesm5/core.js:8980:1)
    at resolveToken node_modules/@angular/core/fesm5/core.js:9139:1)
    at tryResolveToken node_modules/@angular/core/fesm5/core.js:9083:1)
    at StaticInjector.get node_modules/@angular/core/fesm5/core.js:8980:1)
    at resolveNgModuleDep node_modules/@angular/core/fesm5/core.js:21120:1)
    at _createClass node_modules/@angular/core/fesm5/core.js:21173:1)
    at _createProviderInstance node_modules/@angular/core/fesm5/core.js:21137:1)
</code></pre>

<p>I googled this and the closest thing I found was this: <a href=""https://stackoverflow.com/questions/46687469/angular-karma-ngrx-no-provider-for-store"">Angular - Karma - ngrx - No provider for Store</a>, but don't think it applies.</p>

<p>Really not sure what to try next.</p>
",https://stackoverflow.com/questions/59737885/no-provider-for-mockstate,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",939,True,0,1
Mongodb always start with embedded mode in spring boot,"<p>I have below in my pom, which i only expect embed mongo db with my unit testing.</p>

<pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;de.flapdoodle.embed&lt;/groupId&gt;
            &lt;artifactId&gt;de.flapdoodle.embed.mongo&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>

<p>But even when i start Spring STS with local mode, the mongo db always start with embeded mode where i can not connect to it using a db client.</p>

<p>For local dev testing, i expect to connect to my local db runs on post 27017 which i mentioned in my application-local.yml as below,</p>

<pre><code>spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/mydb
</code></pre>

<p>This is what my MongoConfig class looks like,</p>

<pre><code>@Configuration
@EnableMongoAuditing
public class MongoConfig {

    private final MongoProperties mongoProperties;

    public MongoConfig(MongoProperties mongoProperties) {
        super();
        this.mongoProperties = mongoProperties;
    }

    //Other bean initialization methods
}
</code></pre>

<p>Main class has only @SpringBootApplication </p>
",https://stackoverflow.com/questions/61084763/mongodb-always-start-with-embedded-mode-in-spring-boot,"['java', 'mongodb', 'spring-boot', 'spring-data']",326,False,0,1
Different unit testing coverage branch with different env variables,"<p>I don't think that unit testing coverage should depend on env variables, and I would like to know how can I deal with it.</p>

<ul>
<li>Using Istanbul</li>
</ul>

<p>The coverage is lower when I run the tests with envs, in this part: </p>

<pre><code>host: process.env.DATABASE_HOST || 'localhost'
</code></pre>

<p>because with this the last branch never is reach.</p>

<p>I think that is related with <a href=""https://github.com/istanbuljs/nyc/issues/969"" rel=""nofollow noreferrer"">https://github.com/istanbuljs/nyc/issues/969</a>
and I was thinking to do <code>del process.env</code> starting the tests</p>

<p>What do you think about that? Do you know another way to solve that?</p>
",https://stackoverflow.com/questions/61734063/different-unit-testing-coverage-branch-with-different-env-variables,"['javascript', 'unit-testing', 'istanbul']",74,False,0,1
MS Test - define DataRows in separate class,"<p>I am working on some legacy code project and I am using MS Test 1.3 for unit testing. I use <code>[DataRow]</code> to pass parameters to my tests, but the problem is that some of my tests have 10-20 <code>[DataRow]</code>s. Is there a way to have them in separate class and pass it like this to unit test?</p>
<p>I think xUnit have something like this (I think it is called a fixture, but not sure if I remember correctly), but I have to stick to MS Test 1.3</p>
",https://stackoverflow.com/questions/62816987/ms-test-define-datarows-in-separate-class,"['c#', '.net', 'unit-testing', 'mstest']",260,False,0,1
"Unit testing, mocking and traits in rust","<p>Iam current building a application which heavy relies on File IO, so obviously lots of parts of my code have <code>File::open(file)</code>.</p>
<p>Doing some integration tests are ok, I can easily set folders to load file and scenarios needed for it.</p>
<p>The problem comes whatever I want to unit tests, and code branches. I know there is lots of mocking libraries out there that claim to mocks, but i feel my biggest problem is code design itself.</p>
<p>Let's say for instance, I would do the same code in any object oriented language (java in the example), i could write some interfaces, and on tests simple override the default behavior I want to mock, set the a fake <code>ClientRepository</code>, whatever reimplemented wih a fixed return, or use some mocking framework, like mockito.</p>
<pre class=""lang-java prettyprint-override""><code>
public interface ClientRepository {
   Client getClient(int id)
}

public class ClientRepositoryDB {
   
  private ClientRepository repository;
  
  //getters and setters

  public Client getClientById(int id) {
    Client client = repository.getClient(id);

    //Some data manipulation and validation
  }
}

</code></pre>
<p>But i couldn`t manage to get the same results in rust, since we endup mixing data with behavior.</p>
<p>On the <a href=""https://doc.rust-lang.org/1.33.0/book/ch15-05-interior-mutability.html#a-use-case-for-interior-mutability-mock-objects"" rel=""noreferrer"">RefCell documentation</a>, there is a similar example with the one I gave on java. Some of answers points to traits, <a href=""https://stackoverflow.com/questions/61941650/how-do-i-create-a-mock-function-in-rust"">clojures</a>, <a href=""https://klau.si/blog/mocking-in-rust-with-conditional-compilation/"" rel=""noreferrer"">conditional compiliation</a></p>
<p>We might come with some scenarios in test, first one a public function in some mod.rs</p>
<pre class=""lang-rust prettyprint-override""><code>

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SomeData {
    pub name: Option&lt;String&gt;,
    pub address: Option&lt;String&gt;,
}


pub fn get_some_data(file_path: PathBuf) -&gt; Option&lt;SomeData&gt; {
    let mut contents = String::new();


    match File::open(file_path) {
        Ok(mut file) =&gt; {
            match file.read_to_string(&amp;mut contents) {
                Ok(result) =&gt; result,
                Err(_err) =&gt; panic!(
                    panic!(&quot;Problem reading file&quot;)
                ),
            };
        }
        Err(err) =&gt; panic!(&quot;File not find&quot;),
    }
    
    // using serde for operate on data output
    let some_data: SomeData = match serde_json::from_str(&amp;contents) {
        Ok(some_data) =&gt; some_data,
        Err(err) =&gt; panic!(
            &quot;An error occour when parsing: {:?}&quot;,
            err
        ),
    };

    //we might do some checks or whatever here
    Some(some_data) or None
}


mod test {

    use super::*;
    
    #[test]
    fn test_if_scenario_a_happen() -&gt; std::io::Result&lt;()&gt; {
       //tied with File::open
       let some_data = get_some_data(PathBuf::new);

        assert!(result.is_some());

        Ok(())
    }


    #[test]
    fn test_if_scenario_b_happen() -&gt; std::io::Result&lt;()&gt; {
       //We might need to write two files, and we want to test is the logic, not the file loading itself
       let some_data = get_some_data(PathBuf::new);

        assert!(result.is_none());

        Ok(())
    }
}
</code></pre>
<p>The second the same function becoming a trait and some struct implement it.</p>
<pre class=""lang-rust prettyprint-override""><code>


#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SomeData {
   pub name: Option&lt;String&gt;,
   pub address: Option&lt;String&gt;,
}

trait GetSomeData {
   fn get_some_data(&amp;self, file_path: PathBuf) -&gt; Option&lt;SomeData&gt;;
}

pub struct SomeDataService {}

impl GetSomeData for SomeDataService {
   fn get_some_data(&amp;self, file_path: PathBuf) -&gt; Option&lt;SomeData&gt; {
       let mut contents = String::new();

       match File::open(file_path) {
           Ok(mut file) =&gt; {
               match file.read_to_string(&amp;mut contents) {
                   Ok(result) =&gt; result,
                   Err(_err) =&gt; panic!(&quot;Problem reading file&quot;),
               };
           }
           Err(err) =&gt; panic!(&quot;File not find&quot;),
       }
       // using serde for operate on data output
       let some_data: SomeData = match serde_json::from_str(&amp;contents) {
           Ok(some_data) =&gt; some_data,
           Err(err) =&gt; panic!(&quot;An error occour when parsing: {:?}&quot;, err),
       };

       //we might do some checks or whatever here
       Some(some_data) or None
   }
}

impl SomeDataService {
   pub fn do_something_with_data(&amp;self) -&gt; Option&lt;SomeData&gt; {

       self.get_some_data(PathBuf::new())
   }
}


mod test {

   use super::*;
   
   #[test]
   fn test_if_scenario_a_happen() -&gt; std::io::Result&lt;()&gt; {
      //tied with File::open
      let service = SomeDataService{}

      let some_data = service.do_something_with_data(PathBuf::new);

       assert!(result.is_some());

       Ok(())
   }

}
</code></pre>
<p>On both examples, we have a hard time unit testing it, since we tied with <code>File::open</code>, and surely, this might be extend to any non-deterministic function, like time, db connection, etc.</p>
<p>How would you design this or any similar code to make easier to unit testing and better design?</p>
",https://stackoverflow.com/questions/63850791/unit-testing-mocking-and-traits-in-rust,"['unit-testing', 'rust', 'mocking', 'tdd', 'traits']",12874,True,14,2
How to mock boolean variable having several &amp;&amp; conditions with nested methods? MOCKITO FOR UNIT TEST,"<p>So, my problem is like this?
I have private method in which I am passing the variable <code>a</code> and these are the conditions for the boolean variable to be true.
I am having a class <code>B</code> having <code>getB()</code>, class <code>C</code> having <code>getC()</code> methods, interface <code>D</code> having <code>getD()</code> method with return type as <code>long</code>.
I am having another method (static boolean <code>isE()</code>) in which I am passing a local variable <code>f</code>
and calling method <code>getG()</code> from a different class <code>H</code>.</p>
<p>How do I mock these values for unit testing using Mockito so that my boolean variable <code>check</code> becomes <code>true</code>.</p>
<pre><code>boolean check = a != null
                &amp;&amp; a.getB().getC().getD() &gt;= 0
                &amp;&amp; !isE(f.getG()))
</code></pre>
",https://stackoverflow.com/questions/63238453/how-to-mock-boolean-variable-having-several-conditions-with-nested-methods-m,"['java', 'mockito']",4629,False,0,3
Sandboxing Blazor WebAssemblies in lieu of AppDomain Sandboxing,"<p>I need a way to securely load assemblies created by 3rd parties on a multi tenant server that may perform a variety of tasks.</p>
<p>What are my choices beyond what is listed below, and what is the most ideal?</p>
<ul>
<li>WebAssembly rehosting (perhaps borrow ideas from Blazor WASM Unit testing?)</li>
<li>Silverlight (no.)</li>
<li>AppDomain</li>
<li>URL to an Azure Function app (how do function apps work? CScript might work as well)</li>
<li>MicroServices (I don't know enough about this, I just need to load and run a DLL function)</li>
</ul>
",https://stackoverflow.com/questions/64375464/sandboxing-blazor-webassemblies-in-lieu-of-appdomain-sandboxing,"['azure-functions', 'microservices', 'appdomain', 'blazor-webassembly']",80,False,0,0
AssertJ assert on Exception covered another Exception,"<p>I'm a beginner of AssertJ. I encountered some issue when I use AssertJ to do Unit Testing. </p>

<ul>
<li><strong>JAVA: version 8</strong></li>
<li><strong>AssertJ: 3.11.1</strong></li>
</ul>

<p>I have a source code as below, to capture an exception and throw another exception.</p>

<pre><code>try {
    Integer.valueOf(valueA);
} catch(Exception e) {
    throw new XXXException(""value is not valid"", e);
}
</code></pre>

<p>My test case as below failed, and I was told wrong exception assert, it's a bit confusing.</p>

<pre><code>Throwable thrown = catchThrowable(() -&gt; {
    contract.init(ctx, ""A"", ""100A"", ""B"", ""200"");
});
assertThat(thrown).isInstanceOf(XXXException.class);
</code></pre>

<p>The error message as below, it seems like the original exception was captured by AssertJ. Anyone can help? Is it a bug or my mistake of AssertJ API usage? Many Thanks.</p>

<pre><code>java.lang.AssertionError: 
Expecting:
  &lt;java.util.IllegalFormatConversionException: d != java.lang.String&gt;
to be an instance of:
  &lt;xxxx.XXXException&gt;
but was:
  &lt;""java.util.IllegalFormatConversionException: d != java.lang.String
</code></pre>
",https://stackoverflow.com/questions/60903001/assertj-assert-on-exception-covered-another-exception,"['exception', 'assertj', 'throwable']",361,True,0,1
How to pass List through viewmodel with cshtml without database,"<p>I am working on a webapplication where u can keep stock of what you have in your shop. But when I hit submit, the previous list doesn`t show up in the submitted form.</p>

<p>Everything else of the information is in the viewmodel.</p>

<p>Any help is welcome</p>

<p>Here is my code</p>

<p>INDEX.CSHTML</p>

<pre><code>@{
ViewData[""Title""] = ""Home Page"";
}

@model WebApp.Models.Item;

&lt;div class=""text-center""&gt;
    &lt;h1 class=""display-4""&gt;Stock manager&lt;/h1&gt;
    &lt;form asp-controller=""Home"" asp-action=""AddItem"" method=""post""&gt;
        &lt;label&gt;Naam&lt;/label&gt;
        &lt;input type=""text"" asp-for=""Name"" name=""Name"" /&gt;
        &lt;label&gt;Aantal&lt;/label&gt;
        &lt;input type=""number"" asp-for=""Aantal"" name=""Aantal"" /&gt;
        &lt;label&gt;Beschrijving&lt;/label&gt;
        &lt;input type=""text"" asp-for=""Beschrijving"" name=""Beschrijving"" /&gt;
        &lt;input type=""submit"" value=""toevoegen"" /&gt;

        &lt;h1 class=""display-4""&gt;Stock list&lt;/h1&gt;
        @if (Model.Stock != null)
        {
    &lt;ul&gt;
        @for (int idx = 0; idx &lt; Model.Stock.Count; idx++)
        {
            &lt;li&gt;
                @Html.HiddenFor(Model.Stock[idx].Name)
                @Html.HiddenFor(Model.Stock[idx].Aantal)
                @Html.HiddenFor(Model.Stock[idx].Beschrijving)
                &lt;h3&gt;@Model.Stock[idx].Name&lt;/h3&gt;
                &lt;p&gt;Aantal: @Model.Stock[idx].Aantal&lt;/p&gt;
                &lt;p&gt;Beschrijving: @Model.Stock[idx].Beschrijving&lt;/p&gt;
            &lt;/li&gt;

        }
    &lt;/ul&gt;
        }
        else
        {
            &lt;span&gt;Nog niets toegevoegd&lt;/span&gt;
        }
    &lt;/form&gt;
&lt;/div&gt;
</code></pre>

<p>HOMECONTROLLER.CS</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApp.Models;

namespace WebApp.Controllers
{
public class HomeController : Controller
{

    private readonly ILogger&lt;HomeController&gt; _logger;
    public  List&lt;Item&gt; items;
    public HomeController(ILogger&lt;HomeController&gt; logger)
    {
        _logger = logger;

    }

    public IActionResult Index()
    {
        Item item = new Item();
        return View(item);
    }


    public IActionResult AddItem(Item item)
    {
        if (item.Stock == null)
        {
            item.Stock = new List&lt;Item&gt;();
        }

        item.Stock.Add(new Item
        {
            Name = item.Name,
            Aantal = item.Aantal,
            Beschrijving = item.Beschrijving
        });

        return View(""Index"",item);
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
}
</code></pre>

<p>ITEM.CS</p>

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

namespace WebApp.Models
{
public class Item
{
    public string Name { get; set; }
    public int Aantal { get; set; }
    public string Beschrijving { get; set; }
    public List&lt;Item&gt; Stock { get; set; }
}
}
</code></pre>

<p>This is a schoolproject due to the end of the weekend so i'm kinda worried plus there is some unit testing still to do.</p>

<p>Thank you!</p>

<p>RAW HTML after adding 2 items</p>

<pre><code> &lt;div class=""text-center""&gt;
    &lt;h1 class=""display-4""&gt;Stock manager&lt;/h1&gt;
    &lt;form method=""post"" action=""/Home/AddItem""&gt;
        &lt;label&gt;Naam&lt;/label&gt;
        &lt;input type=""text"" name=""Name"" id=""Name"" value=""test"" /&gt;
        &lt;label&gt;Aantal&lt;/label&gt;
        &lt;input type=""number"" name=""Aantal"" data-val=""true"" data-val-required=""The Aantal field is required."" id=""Aantal"" value=""3"" /&gt;
        &lt;label&gt;Beschrijving&lt;/label&gt;
        &lt;input type=""text"" name=""Beschrijving"" id=""Beschrijving"" value=""test"" /&gt;
        &lt;input type=""submit"" value=""toevoegen"" /&gt;

        &lt;h1 class=""display-4""&gt;Stock list&lt;/h1&gt;
            &lt;ul&gt;
                    &lt;li&gt;
                        &lt;h3&gt;test&lt;/h3&gt;
                        &lt;p&gt;Aantal: 3&lt;/p&gt;
                        &lt;p&gt;Beschrijving: test&lt;/p&gt;
                    &lt;/li&gt;
            &lt;/ul&gt;
    &lt;input name=""__RequestVerificationToken"" type=""hidden"" value=""CfDJ8KvM1zMUD4ZOqfaYG4a2bsBumYriiijPssoEk30unaH30LZcWhGlluH47isCWUR2P-tDvQNQWZgxgHJRhqHf_2SyfcRI80clCL3fvM0hETtZ43eiWokSS3vId3OQe-P8rP1jBe5RWYyt8n9UB9yPjaI"" /&gt;&lt;/form&gt;
&lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/61544783/how-to-pass-list-through-viewmodel-with-cshtml-without-database,"['c#', 'asp.net-mvc', 'list', 'viewmodel']",444,True,0,2
Unit Testing Abstract Base and Child Classes,"<p>Unit testing newbie here. I have an abstract base class with one concrete, public method and one abstract, private method. Several child classes implement this private method:</p>

<pre><code>@add_metaclass(ABCMeta)
class Base(object):

    def concrete(self, x, y):
        x = self._abstract(x)
        return x, y

    @abstractmethod
    def _abstract(self, x):
        pass


class Child(Base):

    def _abstract(self, x):
        return x + 1
</code></pre>

<p>What is the best way to unit test the methods in these classes? In my initial attempt I created a <code>MockBase</code> and a set of tests in <code>BaseTests</code> common to all children of the original base class (<code>BaseTests</code> skips tests to avoid redundancy on execution). Child tests inherit from <code>BaseTests</code>. </p>

<pre><code>class MockBase(Base):

    def _abstract(self, x):
        return x


class BaseTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        if cls is BaseTests:
            raise unittest.SkipTest(""Skipping BaseTests."")
        super(BaseTests, cls).setUpClass()

    def setUp(self):
        super(BaseTests, self).setUp()
        self.class_ = MockBase()

    def test_concrete_returns_y(self):
        _, y = self.class_.concrete(1, 1)
        self.assertEqual(y, 1)


class TestChild(BaseTests):

    def setUp(self):
        super(TestChild, self).setUp()
        self.class_ = Child()

    def test_concrete_returns_x_plus_1(self):
        x, _ = self.class_.concrete(1, 1)
        self.assertEqual(x, 2)
</code></pre>

<p>This approach seems to work, but I'm wondering if it's the most elegant and scalable option. </p>
",https://stackoverflow.com/questions/59595330/unit-testing-abstract-base-and-child-classes,"['python', 'unit-testing', 'inheritance']",361,False,2,0
How to check return value in Jest,"<p>I'm doing unit testing with jest and was able to successfully run some of it but there's certain code that I don't know how to test.</p>

<p>I have Create Organization method that needs to check first if the organization is already exist.</p>

<pre><code>async createOrganization(opt) {
    try {
        const organizationExist = await this.OrganizationRepository.getOne({name: opt.name})
        if (organizationExist) {
            throw new Error('Organization already exist')
        }    
    } catch (error) {
        throw error
    }

    let organizationObject = {}
    organizationObject.name = opt.name    
    return this.OrganizationRepository.save(organizationObject)
}
</code></pre>

<p>and so far this is the unit test code that I was able to cover</p>

<pre><code>describe('Create Organization', () =&gt; {
    it('should call getOne function', () =&gt; {
        const mockGetOne = jest.spyOn(OrganizationRepository.prototype, 'getOne')
        organizationService.createOrganization(expectedOrganization)
        expect(mockGetOne).toHaveBeenCalledWith({name: 'sample org'})
    })

    it('should return created organization', async () =&gt; {
        const mockSave = jest.spyOn(OrganizationRepository.prototype, 'save')
        mockSave.mockReturnValue(Promise.resolve(expectedOrganization))
        const result = await organizationService.createOrganization({name: 'sample org'})
        expect(mockSave).toHaveBeenCalledWith({name: 'sample org'})
        expect(result).toBe(expectedOrganization)
    })
})
</code></pre>

<p>now what I want to test is this part</p>

<pre><code>const organizationExist = await this.OrganizationRepository.getOne({name: opt.name})
if (organizationExist) {
    throw new Error('Organization already exist')
}
</code></pre>

<p>I want to throw an error if the organization is already exist using the name parameter.</p>

<p>Hope you guys can help me. Thanks</p>
",https://stackoverflow.com/questions/60843620/how-to-check-return-value-in-jest,"['javascript', 'jestjs']",1969,True,2,2
How to get the unit test results in variables in Azure DevOps Pipelines?,"<p>I have a build pipeline in Azure DevOps and I'm using the .NET Core task for applying unit testing.</p>
<p>I need to get the result of the unit tests in variables. For example, if there are 10 tests cases and two failed, I need to get something like:</p>
<pre><code>failedTestCases = 2
succeededTestCases = 8
</code></pre>
<p>This is because I need those values in the next tasks. Is there a way to do that?</p>
<p>To be clear, I don't need to publish the results, they are already being published, I need to get those values in execution time.</p>
",https://stackoverflow.com/questions/62825065/how-to-get-the-unit-test-results-in-variables-in-azure-devops-pipelines,"['azure', 'unit-testing', 'azure-devops', 'azure-pipelines']",1722,True,2,1
How to do dependency injection on a noncontroller in asp.net core?,"<p>I'm trying to create a context for my redis database without using Entity Framework. My connection depends on a <code>ConnectionMultiplexer</code> class, so for unit testing I'm trying to use dependency injection. I'm not sure how to create the using statement for my context without the <code>ConnectionMultiplexer</code> parameter.</p>
<p>Am I doing dependency injection wrong? How can I restructure so I can use the &quot;using&quot; context correctly and have it resolve the dependency for me?</p>
<p>GameSession.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;

namespace Bored.GameService.GameSession
{
    public class GameSessionContext : IGameSession, IDisposable
    {
        private IDatabase conn;
        private readonly IConnectionMultiplexer _muxer;

        public GameSessionContext(IConnectionMultiplexer muxer)
        {
            _muxer = muxer;
            string connectionString = Startup.Configuration.GetConnectionString(&quot;redis&quot;);
            _muxer = ConnectionMultiplexer.Connect(connectionString);
            //conn = muxer.GetDatabase();
            //conn.StringSet(&quot;foo&quot;, &quot;bar&quot;);
            //var value = conn.StringGet(&quot;foo&quot;);
            //Console.WriteLine(value);
        }

        public void GetGameState()
        {
            throw new NotImplementedException();
        }

        public void AddGameState()
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            _muxer.Dispose();
        }
    }
}
</code></pre>
<p>Here is where I'm registering the dependency in my startup.cs</p>
<p>Startup.cs</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton&lt;IConnectionMultiplexer, ConnectionMultiplexer&gt;();

    services.AddSignalR();

    services.AddCors(options =&gt;
    {
        options.AddPolicy(&quot;ClientPermission&quot;, policy =&gt;
        {
            policy.AllowAnyHeader()
                  .AllowAnyMethod()
                  .WithOrigins(&quot;http://localhost:3000&quot;)
                  .AllowCredentials();
        });
    });
}
</code></pre>
<p>Here is how I'm using it in my GameServiceAPI class:</p>
<pre><code>using Bored.GameService.Clients;
using Bored.GameService.GameSession;
using Bored.GameService.Models;
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace Bored.GameService.GameServiceAPI
{
    public class GameServiceHub : Hub&lt;IGameClient&gt;
    {
        public Task SendMessage(GameMessage message)
        {
// Throws an error because GameSessionContext has no IConnectionMultiplexer parameter passed in.
            using (var context = new GameSessionContext())
            {
                // var gameState = context.GetGameState(context);
                // context.AddGameState(gameState);
                // Clients.All.ReceiveMessage(gameState);
            }
            return Clients.All.ReceiveMessage(message);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/65371832/how-to-do-dependency-injection-on-a-noncontroller-in-asp-net-core,"['c#', 'asp.net-core', 'dependency-injection']",537,True,2,1
Multiple DB contexts to a single database,"<p>I am using EF in memory database to do some unit testing. I have figured out how to populate the database with some test data and to query results through the context. The problem is that I have two db contexts. One used for adding data to the table and another with views used to access data. I don't know how to create the two contexts so that they use the same database. My unit test is returning failed, because it expected 1 result but found 0.</p>
<p>Any suggestions?</p>
<pre><code>[Fact]
public void WhenCallingA_ThenCallReturnThis()
{
    var tableOptions = new DbContextOptionsBuilder&lt;TableContext&gt;()
        .UseInMemoryDatabase(databaseName: &quot;MyDatabase&quot;)
        .Options;

    var viewOptions = new DbContextOptionsBuilder&lt;ViewContext&gt;()
        .UseInMemoryDatabase(databaseName: &quot;MyDatabase&quot;)
        .Options;

    using (var tableContext = new TableContext(tableOptions))
    {
        tableContext.MyTable.Add(GenerateRecord());
        tableContext.SaveChanges();
    }

    using (var viewContext = new ViewContext(viewOptions))
    {
        Assert.Equal(&quot;HelloWorld&quot;, viewContext.MyTopics.Find(12).name);
    }
}
</code></pre>
",https://stackoverflow.com/questions/63522425/multiple-db-contexts-to-a-single-database,"['c#', 'asp.net', 'entity-framework-core', 'in-memory-database']",541,True,2,1
Unable to Access HTMLElement,"<p>I have some code where I convert an HTML string to Document using DOM Parser. And then traverse the DOM to find an element depending on the class name.</p>
<p><strong>helper.js</strong></p>
<pre><code>export function stringToHTML(htmlString) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, 'text/html');
  return doc.body; 
}

export function getTextBoxInfo(htmlContent) {
  const textBox = {
    element: null,
    index: null
  };

  htmlContent.getElementsByClassName('document-content')[0].children.forEach((ele, index) =&gt; {
    if (ele.getAttribute('class').includes('freetext')) {
      textBox.element = freeTextElement;
      textBox.index = index;
    }
  });

  return textBox;
}
</code></pre>
<p><strong>helper.test.js</strong></p>
<pre><code>describe('The getTextBoxInfo function', () =&gt; {
    it('returns an object with text box element and its position', () =&gt; {
        const htmlString = `&lt;div class=&quot;document-content&quot;&gt;
            &lt;div class=&quot;content&quot; id=&quot;bfb53c88&quot;&gt; Heading &lt;/div&gt;
            &lt;div class=&quot;freetext&quot; contenteditable=&quot;true&quot;&gt; Content &lt;/div&gt;
        &lt;/div&gt;`;
        const htmlContent = helper.stringToHTML(htmlString);

        const textBox = helper.getTextBoxInfo(htmlContent);
        expect(true).toBe(true);
    });
});
</code></pre>
<p>It works fine with the source code. Document converted by DOM Parser is,</p>
<p><a href=""https://i.stack.imgur.com/mInqr.png"" rel=""nofollow noreferrer"">Converted as Document</a></p>
<p>But the output is different during unit testing(JEST),</p>
<p><a href=""https://i.stack.imgur.com/oAPHz.png"" rel=""nofollow noreferrer"">Converted differently</a></p>
<p>As a result the spec is failing with the below error,</p>
<blockquote>
<p>TypeError: Cannot read property 'children' of undefined</p>
</blockquote>
<p>at the line - htmlContent.getElementsByClassName('document-content')[0].children</p>
<p>and I am unable to write the tests.</p>
",https://stackoverflow.com/questions/64223568/unable-to-access-htmlelement,"['javascript', 'html', 'dom', 'jestjs', 'domparser']",170,True,2,1
Uncaught TypeError shown in Karma when unit testing in Angular,"<p>Suppose i have a service named <strong>testService</strong> with a function <strong>getData</strong> in it. Also i have a component ( say <strong>A</strong> ) into which the service is injected.</p>

<pre><code>export class A implements OnInit,OnDestroy{
    saveObj;

    constructor(public service:testService){

    }

    ngOnDestroy(){
      if(this.saveObj) this.saveObj.unsubscribe();
    }

    ngOnInit(){
        this.saveObj = this.service.getData.subscribe(res =&gt; {
            this.func(res);
        },
        err =&gt; {
            console.log(""Error Occured"");
            this.saveObj.unsubscribe();
        });
    }

    private func(result: any){
        // Some code
    }
}
</code></pre>

<p>Now i am doing <strong><em>unit testing</em></strong> for this component. The problem is in some cases , it throws an error:</p>

<pre><code>Uncaught TypeError: _this.saveObj.unsubscribe is not a function thrown
</code></pre>

<p>Code snippet of spec.ts:</p>

<pre><code>// testServiceStub is just a mock of testService. 

beforeEach(async(()=&gt;{
    testServiceStub = jasmine.createSpyObj(['getData']);

    TestBed.configureTestingModule({
        declarations : [A],
        schemas : [NO_ERRORS_SCHEMA],
        providers : [
            { provide : testService, useValue: testServiceStub }
        ]
    }).compileComponents();
}))

beforeEach(async(()=&gt;{
    fixture = TestBed.createComponent(A);
    component = fixture.componentInstance;
}))

it('checks whether error is handled or not',()=&gt;{
    spyOn(console,'log');
    testServiceStub.getData.and.returnValue(throwError({status:404})); 
    fixture.detectChanges();
    expect(console.log).toHaveBeenCalled(); // shows the TypeError
})


it('checks whether value is handled or not',()=&gt;{
    testServiceStub.getData.and.returnValue(of(mockData)); // some mock data
    fixture.detectChanges();
    expect(component.func).toHaveBeenCalled();  // also shows the TypeError
})
</code></pre>

<p>I also referred this link <a href=""https://stackoverflow.com/questions/41191077/unsubscribe-is-not-a-function-on-an-observable"">unsubscribe is not a function on an observable</a> . But the problem is it also works in some cases and no error is shown.</p>

<p>Please help me figure out the reason and possible scenarios.</p>

<p>UPD: Added onDestroy lifecycle hook</p>
",https://stackoverflow.com/questions/61725741/uncaught-typeerror-shown-in-karma-when-unit-testing-in-angular,"['angular', 'unit-testing']",681,True,2,1
Unit testing ASP.NET Core 3.1 MVC controller - value cannot be null. (Parameter &#39;provider&#39;),"<p>I've recently started working with .NET Core 3.1 after coming from a .NET background and just trying to get up to speed with Unit Testing an MVC controller in the new framework.</p>
<p>In .NET creating an MVC website used to give the option of adding a Unit Test project whereas Core doesn't; so I have followed some guides and have put this simple test together in MSTest for the <code>HomeController</code> index view.</p>
<p>HomeController.cs:</p>
<pre><code>public class HomeController : Controller
{
    public IActionResult Index()
    {
        return this.View();
    }
}
</code></pre>
<p>HomeControllerTests.cs:</p>
<pre><code>[TestMethod]
public void WhenIndexIsExecutedAsyncThenContentShouldBeReturned()
{
    // arrange
    var httpContext = new DefaultHttpContext();
    var controller = new HomeController()
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = httpContext
            }
        };

    var actionContext = new ActionContext
        {
            HttpContext = httpContext
        };

    // act
    var result = controller.Index().ExecuteResultAsync(actionContext);

    // assert
    Assert.IsNotNull(result);
    Assert.IsNull(result.Exception);
}
</code></pre>
<p>I get an error:</p>
<blockquote>
<p>Value cannot be null. (Parameter 'provider')</p>
</blockquote>
<p>And I do not know what is causing the error.</p>
",https://stackoverflow.com/questions/65339974/unit-testing-asp-net-core-3-1-mvc-controller-value-cannot-be-null-parameter,"['c#', 'asp.net-mvc', 'asp.net-core', 'mstest']",931,True,2,1
How best to unit test a ServiceStack service that uses IServiceGateway to call other internal services,"<p>I've been following the guidelines here - <a href=""https://docs.servicestack.net/testing"" rel=""nofollow noreferrer"">https://docs.servicestack.net/testing</a></p>

<p>I'm trying to do unit testing rather than integration, just to cut down the level of mocking and other complexities.</p>

<p>Some of my services call some of my other services, via the recommended IServiceGateway API, e.g. Gateway.Send(MyRequest).</p>

<p>However when running tests i'm getting System.NotImplementedException: 'Unable to resolve service 'GetMyContentRequest''.</p>

<p>I've used  container.RegisterAutoWired() which is the service that handles this request.</p>

<p>I'm not sure where to go next. I really don't want to have to start again setting up an integration test pattern.</p>
",https://stackoverflow.com/questions/61532991/how-best-to-unit-test-a-servicestack-service-that-uses-iservicegateway-to-call-o,"['unit-testing', 'servicestack', 'inversion-of-control']",384,True,2,2
"Understanding Dependency Injection, Simple Example","<p>Below is a very basic console App example that I put on understanding Dependency Injection &amp; IOC. I somehow could not see the value as in this case I still need to modify my program.cs to inject the new implementation of Interface. Also, how unit testing fits into this?</p>

<p>Program.cs</p>

<pre><code>using Microsoft.Extensions.DependencyInjection;

namespace UnderstandingDI
{
    class Program
    {
        static void Main(string[] args)
        {
            var serPro = new ServiceCollection()
                .AddSingleton&lt;IMessage, Messaging&gt;()
                .BuildServiceProvider();
            var bar = serPro.GetService&lt;IMessage&gt;();
            bar.PrintMessage(""Hello World!----"");
        }
    }
}
</code></pre>

<p>IMessage.cs</p>

<pre><code>namespace UnderstandingDI
{
    public interface IMessage
    {
        public void PrintMessage(string Msg);
    }
}
</code></pre>

<p>Messaging.cs</p>

<pre><code>using System;

namespace UnderstandingDI
{
    public class Messaging : IMessage
    {
        public void PrintMessage(string Msg)
        {
            Console.WriteLine(Msg + ""From Messaging"");
        }
    }
}
</code></pre>

<p>NewMessaging.cs</p>

<pre><code>using System;

namespace UnderstandingDI
{
    class NewMessaging : IMessage
    {
        public void PrintMessage(string Msg)
        {
            if (Msg.StartsWith(""Hello""))
            {
                Console.WriteLine(""Msg starting with Hello"");
            }
            else
            {
                Console.WriteLine(Msg);
            }
        }
    }
}
</code></pre>

<p>Here, if I have to swap <code>Messaging.cs</code> implementation with <code>NewMessaging.cs</code> which both implement <code>IMessage</code> interface, I still need to modify my <code>Program.cs</code> to inject this <code>NewMessaging.cs</code> like this:</p>

<pre><code>var serPro = new ServiceCollection()
                .AddSingleton&lt;IMessage, NewMessaging&gt;()
                .BuildServiceProvider();
</code></pre>

<p>If so, why MS claims that DI addresses one prob of <code>To replace MyDependency with a different implementation, the class must be modified</code>
src:<code>https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1</code></p>

<p>What am I missing?</p>
",https://stackoverflow.com/questions/60704634/understanding-dependency-injection-simple-example,"['c#', 'dependency-injection', 'inversion-of-control']",193,True,1,1
CMake: Compile unit test natively and cross compile code for embedded target,"<p>We are developing an application for an embedded MCU (stm32) and we are trying to set up unit testing with googletest. Is it possible to compile a target using the embedded compiler (gcc-arm-none and some compile options) and compile another target (the unit tests) using the native compiler with CMake? We would abstract and mock the hardware dependencies. This would allow us to run the tests on the host computer and during CI.</p>
<p>I am open to another approach if this is not the way to go or if this approach have issues.</p>
",https://stackoverflow.com/questions/64708390/cmake-compile-unit-test-natively-and-cross-compile-code-for-embedded-target,"['unit-testing', 'gcc', 'cmake', 'embedded', 'googletest']",319,False,1,1
Spring batch test for dynamically created job,"<p>In my application I have multiple jobs So i created Dynamic jobs.I have no issue in running this application. I want to do unit testing for the dynamically created job. </p>

<p>I want to set my job to JobLauncherTestUtils . </p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBatchTest()
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@PropertySource(""classpath:application.yml"")
public class SpringBatchIntegrationTest {
    @Inject
    private JobRepository jobRepository;
    @Inject
    private JobLauncher mJobLauncher;
    private JobLauncherTestUtils jobLauncherTestUtils;
    @Inject
    BatchJobConfig mBatchJobConfig;
    public void initailizeJobLauncherTestUtils() {
        jobLauncherTestUtils = new JobLauncherTestUtils();
        jobLauncherTestUtils.setJobRepository(jobRepository);
        jobLauncherTestUtils.setJob(mBatchJobConfig.createJob());
        jobLauncherTestUtils.setJobLauncher(mJobLauncher);
    }
</code></pre>

<p>This is how im initializing JobLauncherTestUtils . When I run this I get below error
Error creating bean with name 'jobLauncherTestUtils': Unsatisfied dependency expressed through method 'setJob' parameter 0; Can anyone tell me how do I do spring batch test for dynamic jobs.
I don't have much knowledge about Junit. I just started to learn</p>
",https://stackoverflow.com/questions/62015497/spring-batch-test-for-dynamically-created-job,"['java', 'spring-boot', 'unit-testing', 'junit', 'spring-batch']",822,True,1,1
Q-Unit Global Failure,"<p>I have just attempted to set up Q-Unit Testing, for my javascript functions. However, I seem to be getting an error of <strong>Global Failure</strong></p>

<p>Within my JS file : <code>script.js</code>, I have to have the test code above all of my JS code, else the unit tests do not run and I only get the global failure message. However, if I paste the unit tests above all of the JS functions, the tests do then run but I still get the global failure error. 
<a href=""https://i.stack.imgur.com/Ef3D5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Ef3D5.png"" alt=""error2""></a></p>

<p>Can someone guide in the right direction.</p>

<p><strong>test-script.html:</strong></p>

<pre><code>&lt;!doctype html&gt;
&lt;html lang=""en""&gt;
&lt;head&gt;
    &lt;meta charset=""UTF-8""&gt;
    &lt;title&gt;Q-Unit Tests&lt;/title&gt;
    &lt;link rel=""stylesheet"" href=""https://code.jquery.com/qunit/qunit-2.10.0.css""&gt;


&lt;/head&gt;
&lt;body&gt;

    &lt;div id=""qunit""&gt;&lt;/div&gt;
    &lt;div id=""qunit-fixture""&gt;&lt;/div&gt;
    &lt;script src=""https://code.jquery.com/qunit/qunit-2.10.0.js"" integrity=""sha256-X1fQXHSYGxa4V2bqkEAQW0DQGSxJrKveasahr959o28="" crossorigin=""anonymous""&gt;&lt;/script&gt;

    &lt;script src=""script.js""&gt;&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>script.js:</strong></p>

<pre><code> function square(x) {
  return x * x;
}

QUnit.test( ""square"", function( assert ) {
  var result = square(2);
  assert.equal( result, ""4"", ""square(2) should be 4."" );
});

//Normal JS functions are below here
</code></pre>
",https://stackoverflow.com/questions/61680319/q-unit-global-failure,"['javascript', 'unit-testing', 'qunit']",295,False,1,1
How can the existing unit test possibly fail by adding another test?,"<p>This is my source code and I added onWindowClick recently.</p>

<pre><code>  componentDidMount() {
    window.addEventListener('mouseup', this.onWindowMouseUp);
    window.addEventListener('click', this.onWindowClick, true);
   ...

  @bind
  onWindowClick(e) {
    if (!this.mouseInProgress) {
      return;
    }
    e.stopPropagation();
  }

  /**
   * Window mouse up handler.
   */
  @bind
  @debounce(0)
  onWindowMouseUp() {
    this.mousePoint = null;
    this.mouseInProgress = false;
  }
</code></pre>

<p>Feature looks good so I'm trying to add another test for onWindowClick</p>

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

  const e = {
    stopPropagation: jest.fn(),
    clientX: 500,
    clientY: 700,
  };

  beforeEach(() =&gt; {
    instance.mouseInProgress = false;
    instance.onWindowClick();
  });
 test('should not stop propogation', () =&gt; {
    setTimeout(() =&gt; {
      instance.onWindowClick(e);
      expect(e.stopPropagation).toHaveBeenCalled();
    }, 0);
  });

</code></pre>

<p>Somehow this existing test fails on the unit testing and the one above is passing. (VERY WEIRD)</p>

<pre><code>describe('onWindowMouseUp method', () =&gt; {
  beforeEach(() =&gt; {
    instance.mousePoint = null;
    instance.mouseInProgress = false;
    instance.onWindowMouseUp();
  });

  test('should reset mousePoint', (done) =&gt; {
    setTimeout(() =&gt; {
      expect(instance.mousePoint).toBeNull();
      done();
    }, 0);
  });
</code></pre>

<p>The error is </p>

<pre><code>console.error
    Error: Uncaught [Error: expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: &gt;= 1
    Received number of calls:    0]
        at reportException (.:62:24)
        at Timeout.callback [as _onTimeout] .(.)
        at listOnTimeout (..)
.        at processTimers (i.) JestAssertionError: 
    .expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: &gt;= 1
    Received number of calls:    0
        at .:124:33
        at Timeout.callback [as _onTimeout] .(.)
        at listOnTimeout (.:549:17).
 .       at processTimers (..:492:7) {
      matcherResult: { message: [Function (anonymous)], pass: false }
    }

      at VirtualConsole.&lt;anonymous&gt; (..:29:45)
      at reportException (.:66:28)
      at .Timeout.callback [as _onTimeout] (.:645:7)
.

Error: expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: &gt;= 1
Received number of calls:    0

    at /U...:124:33
    at Timeout.callback [as _onTimeout] (/..)
    at listOnTimeout (i.)
    at processTimers (in.).

</code></pre>

<p>If I delete the test case, all tests are passing; It's weird that the newly added test case is somehow affecting other separate test.</p>

<p>I had <code>instance</code> variable outside of tests.</p>

<pre><code>let instance
beforeEach(() =&gt; {
  ...
  wrapper = shallow(&lt;V {...props} /&gt;);
  instance = wrapper.instance();
  instance.rootRef.current = {};
  instance.graphRootRef.current = {};

  wrapper.setState({
    boundsById,
  });
</code></pre>

<p>EDIT: somehow I get the error from the existing method and the stacktrace shows I'm getting an error on here:</p>

<pre><code>expect(e.stopPropagation).not.toHaveBeenCalled();
</code></pre>
",https://stackoverflow.com/questions/61627883/how-can-the-existing-unit-test-possibly-fail-by-adding-another-test,"['javascript', 'reactjs', 'jestjs']",112,False,1,0
Pytest: Using same variable for multiple tests,"<p>I'm currently working on a Flask app and unit testing with pytest. I'm still new to Python class structures, flask and testing.</p>
<p>Please refer to sample code below:</p>
<pre><code>from somewhere import search_person

class TestMethodOne:

    def test_method_with_x(self):
        person = { 
            &quot;first_name&quot;: &quot;John&quot;, 
            &quot;last_name&quot;: &quot;Smith&quot;, 
            &quot;state&quot;: &quot;CA&quot; 
        }
        assert search_person(person) is not None
        

    def test_method_with_y(self):
        person = { 
            &quot;first_name&quot;: &quot;John&quot;, 
            &quot;last_name&quot;: &quot;Smith&quot;, 
            &quot;state&quot;: &quot;CA&quot; 
        }
        assert search_person(person)[&quot;full_name&quot;] == &quot;John M Smith&quot;
</code></pre>
<p>The search_person method utilizes a third party API and takes some time to run, I wish to DRY this so that the test does not make redundant calls. Is there a way I can set this up so the search_person(person) has already been called once pytest creates this class and all the test methods will just reference that variable?</p>
",https://stackoverflow.com/questions/63496674/pytest-using-same-variable-for-multiple-tests,"['python', 'unit-testing', 'class', 'flask', 'pytest']",1771,True,1,1
Spring WebFlux: Unit Testing subscribe function of Mono,"<p>I have the following classes/interfaces:</p>

<pre class=""lang-java prettyprint-override""><code>public interface Api {
    Mono&lt;Object&gt; update();
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>@Service
public class Service {
    @Autowired
    private Api api;
    private List&lt;Object&gt; list;

    public void update() {
        api.update().subscribe(result -&gt; list.add(result), Throwable::printStackTrace);    
    }
}
</code></pre>

<p>I'm trying to perform a unit test using Mockito of the consumer function when I subscribe to the Mono that is being returned by my Api. So far, my test class looks as follows</p>

<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {
    @Mock
    private Mono&lt;Object&gt; mono;
    @MockBean
    private Api api;
    @Autowired
    private Service service;

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

    @Test
    public void testUpdate() {
        when(api.update()).thenReturn(mono);
        doAnswer((Answer&lt;Void&gt;) invocation -&gt; {
            System.out.println(""FOO"");
            Consumer&lt;Object&gt; consumer = invocation.getArgument(0);
            consumer.accept(testObject)
            return null;
        }).when(mono).subscribe(any(Consumer.class), any(Consumer.class));

       service.update();
    }
}
</code></pre>

<p>First, I am seeing that the code inside doAnswer() never gets invoked. Secondly, since Mockito's any() returns null and the error consumer of subscribe function expects non-null I'm running into NullPointerException when I run my test.</p>

<p>What would be the best approach of going about unit testing my subscribe's consumer function?</p>
",https://stackoverflow.com/questions/60606855/spring-webflux-unit-testing-subscribe-function-of-mono,"['java', 'spring', 'testing', 'mockito', 'reactor']",1757,False,1,0
Is it possible to parameterize [TestInitialize]SetUp() in c#?,"<p>I am new to c# unit testing. I am curious if it is possible to parameterize the SetUp method that is decorated by [TestInitialize]</p>
<pre><code>    [TestInitialize]
    public void SetUp(string path)
    {
        fileStream = new FileStream(path, FileMode.Open);
        binaryReader = new BinaryReader(fileStream);
    }
</code></pre>
<p>For example, before each test, I want to be able to pass a unique path to SetUp. Can this be done? I have consulted this post: <a href=""https://stackoverflow.com/questions/9021881/how-to-run-a-test-method-with-multiple-parameters-in-mstest"">How to run a test method with multiple parameters in MSTest?</a> but it does not quite address the problem I am trying to solve, and if it is even possible. Thanks to all of those who respond in advance!</p>
",https://stackoverflow.com/questions/62646585/is-it-possible-to-parameterize-testinitializesetup-in-c,"['c#', 'unit-testing', 'mstest']",273,True,1,1
Unit testing void controller and service methods,"<p>I have built a REST API that does basic CRUD operations on a product database and I am now unit testing all the methods within the controller and service layer. I have realised that methods such as addProduct, updateProduct or deleteProduct return void on both of the layers.</p>
<p>How do I go about mocking the repository when testing the service layer and mocking the service while testing controller layer for these methods?</p>
<p>Controller method:</p>
<pre><code>@RequestMapping(method= RequestMethod.POST,value =&quot;/products&quot;)
public void addProduct(@RequestBody Product product){
    productService.addProduct(product);
}
</code></pre>
<p>Service method:</p>
<pre><code>public void addProduct(Product product){
    productRepository.save(product);
}
</code></pre>
<p>I have commented in the fields where I need help for the addProduct() methods.</p>
<p>Controller tests:</p>
<pre><code>package com.product.controllers;

import com.product.entities.Product;
import com.product.services.ProductService;
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 org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class ProductControllerTest {

@InjectMocks
ProductController productController;

@Mock
ProductService productService;

@Test
public void getHomePage(){
    String homePageText = &quot;Welcome to the home page!&quot;;
    assertEquals(homePageText,productController.getHomePage());
}

@Test
public void getAllProducts(){
    
    Product product1 = new Product();
    product1.setId(&quot;001&quot;);
    product1.setName(&quot;TV&quot;);
    product1.setPrice(999.99);

    Product product2 = new Product();
    product2.setId(&quot;002&quot;);
    product2.setName(&quot;Mobile&quot;);
    product2.setPrice(300D);

    List&lt;Product&gt; listOfProducts = new ArrayList&lt;&gt;();
    listOfProducts.add(product1);
    listOfProducts.add(product2);

    when(productService.getAllProducts()).thenReturn(listOfProducts);
    assertEquals(listOfProducts,productController.getAllProducts());
}

@Test
public void getProductById(){
    
    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    when(productService.getProductById(&quot;001&quot;)).thenReturn(product);
    assertEquals(new ResponseEntity&lt;Product&gt; (product, HttpStatus.OK),productController.getProductById(&quot;001&quot;));
}

@Test
public void addProduct() {
    
    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    // need help with this
}
}
</code></pre>
<p>Service tests:</p>
<pre><code>package com.product.services;

import com.product.entities.Product;
import com.product.repositories.ProductRepository;
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 java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class ProductServiceTest {

@InjectMocks
ProductService productService;

@Mock
ProductRepository productRepository;

@Test
public void getAllProducts() {

    Product product1 = new Product();
    product1.setId(&quot;001&quot;);
    product1.setName(&quot;TV&quot;);
    product1.setPrice(999.99);

    Product product2 = new Product();
    product2.setId(&quot;002&quot;);
    product2.setName(&quot;Mobile&quot;);
    product2.setPrice(300D);

    List&lt;Product&gt; listOfProducts = new ArrayList&lt;&gt;();
    listOfProducts.add(product1);
    listOfProducts.add(product2);

    when(productRepository.findAll()).thenReturn(listOfProducts);
    assertEquals(listOfProducts, productService.getAllProducts());
}

@Test
public void getProductById() {

    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    when(productRepository.findById(&quot;001&quot;)).thenReturn(java.util.Optional.of(product));
    assertEquals(product, productService.getProductById(&quot;001&quot;));


}

@Test
public void addProduct() {

    Product product = new Product();
    product.setId(&quot;001&quot;);
    product.setName(&quot;TV&quot;);
    product.setPrice(999.99);

    // need help with this
}
}
</code></pre>
",https://stackoverflow.com/questions/63774801/unit-testing-void-controller-and-service-methods,"['java', 'maven', 'junit', 'rest']",3492,True,1,1
CS5001	Program does not contain a static &#39;Main&#39; method suitable for an entry point XUnit,"<p>I have a console Application with a Main method</p>

<pre><code> private static void Main(string[] args)
        {
            #region Variables Initialization

            var sqlService = new SQLService();
            var ruleService = new RuleService();
            var fileService = new FileService();
            var recDetail = new ReconciliationDetails();
            List&lt;string&gt; ListHashesSource = null;
            List&lt;string&gt; ListHashesTarget = null;
            HashSet&lt;string&gt; HashsetSource = new HashSet&lt;string&gt;();
            HashSet&lt;string&gt; HashsetTarget = new HashSet&lt;string&gt;();
            HashSet&lt;string&gt; interceptedRows = new HashSet&lt;string&gt;();
            int numberOfMatchesOnSource = 0;
            int numberOfMatchesOnTarget = 0;

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

<p>And Im trying to install xUnit to do unit testing and integration test to my console application.</p>

<pre><code>namespace SparkPOC.Tests
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            Assert.True(true);
        }
    }
}
</code></pre>

<p>The problem is that this test doesnt appear on my test explorer window of visual studio 2019 and when I do build to my solution it throws this error:
<a href=""https://i.stack.imgur.com/DUw0w.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/DUw0w.png"" alt=""enter image description here""></a></p>

<p>SparkPOC.csproj</p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;TargetFramework&gt;netcoreapp3.1&lt;/TargetFramework&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;None Remove=""Models\AppConfiguration.cs~RF1f4d2dd7.TMP"" /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""BenchmarkDotNet"" Version=""0.12.0"" /&gt;
    &lt;PackageReference Include=""ConsoleTables"" Version=""2.4.0"" /&gt;
    &lt;PackageReference Include=""Dapper"" Version=""2.0.30"" /&gt;
    &lt;PackageReference Include=""EasyConsole"" Version=""1.1.0"" /&gt;
    &lt;PackageReference Include=""Microsoft.Spark"" Version=""0.8.0"" /&gt;
    &lt;PackageReference Include=""System.Data.DataSetExtensions"" Version=""4.5.0"" /&gt;
    &lt;PackageReference Include=""System.Data.SqlClient"" Version=""4.8.0"" /&gt;
    &lt;PackageReference Include=""TrieNet.Core"" Version=""1.0.4"" /&gt;

  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>

<p>SparkPOC.Tests.csproj</p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netcoreapp3.1&lt;/TargetFramework&gt;

    &lt;IsPackable&gt;false&lt;/IsPackable&gt;
    &lt;GenerateProgramFile&gt;false&lt;/GenerateProgramFile&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""16.6.0"" /&gt;
    &lt;PackageReference Include=""Microsoft.TestPlatform.TestHost"" Version=""16.6.0"" /&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.4.1"" /&gt;
    &lt;PackageReference Include=""xunit.runner.visualstudio"" Version=""2.4.1""/&gt;
  &lt;/ItemGroup&gt;
 &lt;ItemGroup&gt;
    &lt;ProjectReference Include=""..\SparkPOC\SparkPOC.csproj"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;

</code></pre>

<p>I added this line </p>

<pre><code>    &lt;GenerateProgramFile&gt;false&lt;/GenerateProgramFile&gt;
</code></pre>

<p>as suggestion in this site </p>

<p><a href=""https://andrewlock.net/fixing-the-error-program-has-more-than-one-entry-point-defined-for-console-apps-containing-xunit-tests/"" rel=""nofollow noreferrer"">https://andrewlock.net/fixing-the-error-program-has-more-than-one-entry-point-defined-for-console-apps-containing-xunit-tests/</a></p>

<p>Solution Structure:</p>

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

<p>My test explorer</p>

<p><a href=""https://i.stack.imgur.com/gjKSV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gjKSV.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/61341304/cs5001program-does-not-contain-a-static-main-method-suitable-for-an-entry-poi,"['c#', '.net-core', 'xunit']",3908,True,1,1
Mock object method by calling another object&#39;s method with the first one&#39;s arguments?,"<p>I just want to do this:</p>
<pre><code>Mockito.when(methodOne.read(Mockito.any(byte[].class)).
thenReturn(methodTwo.read(***The argument methodOne was called with (aka whatever was Mockito.any(byte[].class))***));
</code></pre>
<p>Specifically, I have an inputstream that reads into a byte[] array. However, this inputstream cannot be read from during unit testing, so I need to mock this by reading from another inputstream that I will hardcode some values. This other input stream should also read into the byte[] array. Any way to do this?</p>
<p>I tried the below but it gives me a weird error message: error: incompatible types: no instance(s) of type variable(s) T exist so that Answer conforms to byte[]:</p>
<pre><code>Mockito.when(inStreamOne.read(Mockito.any(byte[].class))).then(inStreamTwo.read(returnsFirstArg()));
</code></pre>
",https://stackoverflow.com/questions/62663330/mock-object-method-by-calling-another-objects-method-with-the-first-ones-argum,"['java', 'unit-testing', 'junit', 'mockito']",308,False,1,1
vert.x testing with TestNg,"<p>i am new to vert.x , i am trying to make unit testing by calling my webservices . 
i need an example of testing webservices with testng. </p>

<p>when i did it with junit5 it works fine with the below code </p>

<pre><code>@BeforeMethod
private static void deploy_verticle(Vertx vertx , VertxTestContext testContext) {
    vertx.deployVerticle(new MainVerticle(), testContext.completing());
}


@Test
public void getTestFalse(Vertx vertx , VertxTestContext testContext) throws InterruptedException {
    Assert.assertTrue(""3"".contains(""tesdfsdf""));

    req = new HttpRequestEntityTest();
    req.setHost(""localhost"");
    req.setPort(8089);
    req.setUri(""/api/data"");
    utilTest = new RestUtilTest();
    response = new HttpResponseEntityTest();
    utilTest.getTestUtil(req, testContext.succeeding(response -&gt; {
        testContext.verify(() -&gt; {
            Assert.assertTrue(response.getBodyStr().contains(""tesdfsdf""));

        });
        testContext.completeNow();

    }));
}


@AfterMethod
public void finish(Vertx vertx , VertxTestContext testContext) {

context.getVertx().close(context.getTestContext().succeeding(response -&gt; {
    context.getTestContext().completeNow();
}));
}
</code></pre>

<p>but when i try to work with TestNg like this : </p>

<pre><code>@SuppressWarnings(""deprecation"")
    @Test
    public void getTestIqvia() throws InterruptedException {
        Future&lt;HttpResponseEntityTest&gt; future = Future.future();
        response = new HttpResponseEntityTest();
        req = new HttpRequestEntityTest();
        req.setHost(""localhost"");
        req.setPort(8089);
        req.setUri(""/api/data"");
        utilTest = new RestUtilTest();

        utilTest.getTestUtil(req, response -&gt; {
            System.out.println(response.result().getBodyStr());

            System.out.println(response.result().getBodyStr().contains(""dsds""));
            Assert.assertTrue(response.result().getBodyStr().contains(""fdsfds""));

        });
</code></pre>

<p>GetTestUtil Function : </p>

<pre><code>public Future&lt;HttpResponseEntityTest&gt; getTestUtil(HttpRequestEntityTest req,
        Handler&lt;AsyncResult&lt;HttpResponseEntityTest&gt;&gt; resultHandler) {
    future = Future.future();

    WebClient client = WebClient.create(vertx);
    response = new HttpResponseEntityTest();
    client.get(req.getPort(), req.getHost(), req.getUri()).send(ar -&gt; {
        if (ar.succeeded()) {

            response.setStatusCode(ar.result().statusCode());
            response.setBodyStr(ar.result().bodyAsString());
            future.complete(response);
            System.out.println(""Received response with status code get"" + response.getStatusCode());
            resultHandler.handle(Future.succeededFuture(response));

        } else {
            response.setErrorMsg(ar.cause().getMessage());
            System.out.println(""Something went wrong "" + ar.cause().getMessage());
            future.complete(response);

        }

    });

    return future;

} 
</code></pre>

<p>always sending to web client not entered in the arrow function ar and always test success because it doesn't go to Assert function . except fewtimes in debugging mode only </p>

<p>can any one has ana example in testNG with Vert.x?? or what's wrong in my code?</p>
",https://stackoverflow.com/questions/60279281/vert-x-testing-with-testng,"['java', 'testng', 'webclient', 'vert.x', 'junit5']",234,True,1,1
C# Unit Test - System.IO.FileNotFoundException: Could not load file or assembly,"<p>I'm currently trying to work myself into unit testing for my firm, who before have never worked with that conecpt.
I've previously written a program that accepts customer IDs and reads the corresponding data (name of the firm, address, etc.) from  our iDB2 database and displays it in the UI. Here I want to implement a unit test that, if I input a certain customer ID, expects a certain customer name as output.</p>

<p>The test unfortunately fails, even though it shouldn't. When I try debugging the test it throws the following exception:</p>

<blockquote>
  <p>System.IO.FileNotFoundException: Could not load file or assembly 'System.Security.Permissions, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. Das System kann die angegebene Datei nicht finden.</p>
</blockquote>

<p>The unit test looks as follows:</p>

<pre><code>using Kundeninformationen;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace KDNAbrufTest
{
[TestClass]
public class UnitTest1
{
    int input = **customerID**;

    public int Aufruf(int input)
    {
        Methoden.AufrufKundenname(input);
        return input;
    }

    [TestMethod]
    public void TestMethod1()
    {
        string expected = ""**customer name**"";

        string result = Methoden.AufrufKundenname(input);

        Assert.AreEqual(expected, result);
    }
}
}
</code></pre>

<p>The method AufrufKundenname connects to the database in another class by using an iDB2Connection, iDB2Command and iDB2DataAdapter. In the program itself there is no problem with connection to the database but I might have overlooked something I would have needed to implement in my test class. </p>

<p>I've gone through a lot of posts of people having similar problems being solved by adding an AppConfig file to the test folder but unfortunately that didn't solve it for me. </p>

<p>I myself am neither expert of unit testing nor an advanced C# programmer nor is English my first language so please excuse any unclear phrasing and beginner's mistakes.</p>
",https://stackoverflow.com/questions/60653807/c-unit-test-system-io-filenotfoundexception-could-not-load-file-or-assembly,"['c#', 'visual-studio', 'unit-testing']",1429,False,2,1
Accessing Files In webapp Folder During Unit Testing,"<p>I've seen several variations of this question on StackOverflow, but none describe my scenario exactly, or offer a solution that works for me.</p>

<p>I'm building a Java EE web game.  I'm using JUnit to do unit testing during the build process.  In my webapp folder, I have assets that users access via HTTP GET requests.  In my source code, I have corresponding Java classes that implement the logic of those assets.</p>

<p>For example, I have a class called CookingPot, which implements the logic for a cooking pot in my game.  In the webapp folder, I have a files that provide media and content for cooking pots to the user, for example:</p>

<pre><code>webapp/assets/items/CookingPot.svg (an image of the cooking pot)
webapp/assets/items/CookingPot.html (an HTML description of the cooking pot)
</code></pre>

<p>During unit testing, I'd like to make sure that for every game item (in this example, the CookingPot item), there is an SVG and HTML file in the correct place in the webapp folder.</p>

<p>How can I implement this test?  The JUnit tests are executed in the Maven build environment, which does not provide a Tomcat server to test against, so accessing them via HTTP won't work.  I've tried:</p>

<pre><code>URL svg = getClass().getResource(""/webapp/assets/items/CookingPot.svg"");
URL svg = getClass().getResource(""webapp/assets/items/CookingPot.svg"");
</code></pre>

<p>But those return null.</p>

<p>I have a feeling that there is something simple I'm missing here, but I don't know what it is.  Surely there's got to be a way to test that these files exist during the build process?</p>

<p>Thanks in advance for any help!</p>
",https://stackoverflow.com/questions/59767662/accessing-files-in-webapp-folder-during-unit-testing,"['junit', 'web-applications', 'java-ee-8']",314,True,2,1
Why are my unit tests not coming through when the original code works fine?,"<p>My unit test keeps on sending error messages even though the initial code works and I wrote other unit tests the same way and they work perfectly.</p>
<p>Initial code:</p>
<pre><code>@Override
    public void newOrder(OrderVO orderVO) {

        OrderProduct orderProduct = new OrderProduct();

        Optional&lt;User&gt; userResponse = userRepository.findById(orderVO.getUserId());
        User user = userResponse.orElse(new User());
        Orders order = new Orders(user);
        orderRepository.save(order);

        orderProduct.setId(new OrderProductId());
        orderProduct.setOrders(order);

        List&lt;ProductVO&gt; productVOS = orderVO.getOrderProducts();
        for (ProductVO p : productVOS) {

            Optional&lt;Product&gt; productResponse = productRepository.findById(p.getId());
            Product product = productResponse.orElse(new Product());
            product.setAmount(product.getAmount() - p.getAmountOfOrderedProducts());
            product.setUser(user);
            productRepository.save(product);

            orderProduct.setProduct(product);
            orderProduct.setAmountOfOrderedProduct(p.getAmountOfOrderedProducts());
            orderProductRepository.saveOrder(orderProduct.getProduct().getId(), orderProduct.getOrders().getId(), orderProduct.getAmountOfOrderedProduct());
        }
    }
</code></pre>
<p>test:</p>
<pre><code>@Test
    void newOrder() {

        User userTest = new User(1);
        Optional&lt;User&gt; optUserTest = Optional.of(userTest);
        Optional&lt;Product&gt; optProductTest = Optional.of(productTest);
        OrderVO orderVO = new OrderVO();
        Orders orders = new Orders(userTest);

        when(userRepository.findById(anyInt())).thenReturn(optUserTest);
        when(productRepository.findById(anyInt())).thenReturn(optProductTest);

        orderService.newOrder(orderVO);

        verify(productRepository, times(1)).save(productTest);
        verify(orderRepository, times(1)).save(orders);
        verify(orderProductRepository, times(1)).saveOrder(1,1,53);

    }
</code></pre>
<p>I keep on getting two errors:
first one is pointing to <code>verify(productRepository, times(1)).save(productTest);</code>
and says that</p>
<pre><code>Wanted but not invoked:
productRepository.save(
    com.carlsberg.orderservice.domains.Product@a1db9da0
);
-&gt; at com.carlsberg.orderservice.serviceImpl.OrderServiceImplTest.newOrder(OrderServiceImplTest.java:78)
Actually, there were zero interactions with this mock.
</code></pre>
<p>Second one points to <code>verify(orderRepository, times(1)).save(orders);</code>
and the error message is</p>
<pre><code>Argument(s) are different! Wanted:
orderRepository.save(
    com.carlsberg.orderservice.domains.Orders@d7c7950f
);
</code></pre>
<p>The difference seems to be in <code>d7c7950f</code> part.</p>
<p>This is my first time trying to do unit testing. Really not sure why am I getting this errors since the same concept of writing unit tests worked just fine on other methods.</p>
",https://stackoverflow.com/questions/62940464/why-are-my-unit-tests-not-coming-through-when-the-original-code-works-fine,"['spring-boot', 'unit-testing', 'mockito', 'repository', 'junit5']",35,True,1,1
How to handle a completion handler that never gets called by API?,"<pre><code>APIClient?.update(Record, completion: { response, error in
                dLog(response)
                dLog(error)
           })
</code></pre>

<p>We've been trying to work through a buggy API that is provided by another company. Sometimes, the API works and I get a response record. Occasionally, the update disappears into a blackhole and completion never gets called, so I don't get an error either. </p>

<p>Ultimately we want the API to be fixed, but what is the correct way to catch this in the meantime so I can popup an alert? </p>

<p>I've used XCTest/expectation/waitFor, but I think that's mainly for Unit Testing, not sure if that could apply here.</p>
",https://stackoverflow.com/questions/59904082/how-to-handle-a-completion-handler-that-never-gets-called-by-api,"['swift', 'completionhandler']",30,False,1,0
Expectations Error while unit testing Got Client,"<p>I need your help with this issue that I am having while unit testing a Got client hook
where I do logging of HTTP requests. I am using Jest.
I am getting an expectations error that is seeing the argument to .toBeCalledWith as object whereas it is a string when I console log it. Maybe I am doing something wrong here. Please let me know.</p>
<blockquote>
<p>got-client.js below</p>
</blockquote>
<pre><code>const http = require('http');
const https = require('https');
const got = require('got');
const _ = require('lodash');

const { name: packageName, version: packageVersion } = require('../../package.json');

const keepAliveOptions = { keepAlive: true, keepAliveMsecs: 20000 };
let clients = {};


const allowedHeaders = ['user-agent', 'x-forwarded-for', 'referer', 'content-length'];
const filterHeaders = headers =&gt; _.pick(headers, allowedHeaders);

const gotLoggingHooks = (name, logger) =&gt; ({
  hooks: {
    beforeRequest: [
      options =&gt; {
        const { url, method, headers } = options;
        logger.debug({
          message: `${name} request ${options.method} ${options.url}`,
          http_request: {
            method,
            target: url,
            direction: 'OUT',
            headers: filterHeaders(headers)
          },
          request: _.pick(options, ['url', 'method', 'headers', 'body', 'json'])
        });
      }
    ],
    beforeRetry: [
      (options, error, retryCount) =&gt; {
        const {
          response: { statusCode, ip } = {},
          request: { options: { method, headers = {} } = {}, requestUrl: url } = {},
          timings: {
            // eslint-disable-next-line camelcase
            phases: { total: duration_ms } = {}
          } = {}
        } = error;
        logger.warn({
          message: `${name} will retry request, attempt ${retryCount}/${options.retry.limit} ${method} ${url} (${error.code} ${error.message})`,
          err: error,
          http_request: {
            method,
            target: url,
            status: statusCode,
            server_ip: ip,
            duration_ms,
            direction: 'OUT',
            protocol: headers.via,
            headers: filterHeaders(headers)
          }
        });
      }
    ],
    beforeError: [
      error =&gt; {
        const {
          response: { statusCode, ip } = {},
          request: { options: { method, headers } = {}, requestUrl: url } = {},
          timings: {
            // eslint-disable-next-line camelcase
            phases: { total: duration_ms } = {}
          } = {}
        } = error;
        if (!statusCode) {
          logger.error({
            message: `${name} request error ${method} ${url} (${error.code} ${error.message})`,
            err: error,
            http_request: {
              method,
              target: url,
              status: statusCode,
              server_ip: ip,
              duration_ms,
              direction: 'OUT',
              protocol: headers.via,
              headers: filterHeaders(headers)
            }
          });
        }
        // eslint-disable-next-line no-param-reassign
        error.serviceName = name;
        return error;
      }
    ],
    afterResponse: [
      response =&gt; {
        const {
          statusCode,
          body,
          url,
          ip,
          headers = {},
          request: { options: { method } = {} } = {},
          timings: {
            // eslint-disable-next-line camelcase
            phases: { total: duration_ms } = {}
          } = {},
          retryCount
        } = response;
        logger.debug({
          message: `${name} response ${method} ${url}`,
          response: { body, retryCount, headers },
          http_request: {
            method,
            target: url,
            status: statusCode,
            server_ip: ip,
            duration_ms,
            direction: 'OUT',
            protocol: headers.via,
            headers: filterHeaders(_.get(response, 'request.options.headers'))
          }
        });
        return response;
      }
    ]
  }
});

const gotClient = ({ name, logger, keepAlive = true, gotOptions = {} }) =&gt; {
  if (!clients[name]) {
    clients[name] = got
      .extend({
        headers: {
          'user-agent': `${packageName} ${packageVersion}`
        },
        ...(keepAlive &amp;&amp; {
          agent: {
            http: new http.Agent(keepAliveOptions),
            https: new https.Agent(keepAliveOptions)
          }
        }),
        responseType: 'json',
        timeout: 5000
      })
      .extend(gotLoggingHooks(name, logger))
      .extend(gotOptions);
  }

  return clients[name];
};

gotClient.clearAll = () =&gt; {
  clients = {};
};

module.exports = gotClient;

</code></pre>
<blockquote>
<p>got-client.spec.js below</p>
</blockquote>
<pre><code>const nock = require('nock');
const { name: packageName, version: packageVersion } = require('../../../package.json');
const gotClient = require('../../../src/lib/got-client');

const BASE_URL = 'https://subdomain.domain.com/';
const BASE_ENDPOINT = 'path';

const logger = {
  error: jest.fn(),
  debug: jest.fn(),
  info: jest.fn(),
  log: jest.fn(),
  warn: jest.fn(),
};
describe('got client', () =&gt; {

  afterEach(gotClient.clearAll);

  test('should log requests', async () =&gt; {
    const client = gotClient({
      name: 'test',
      logger,
      gotOptions: {
        prefixUrl: BASE_URL,
      },
    });

    nock(BASE_URL).get(`/${BASE_ENDPOINT}`).reply(200, { success: true });
    await client.get(BASE_ENDPOINT);
    // console.log('mock call 0', logger.debug.mock.calls[0][0]);
    // TODO: match message
    expect(logger.debug).toBeCalled();

    expect(logger.debug).toBeCalledWith(
      expect.objectContaining({
        message: expect.stringContaining(`request GET ${BASE_URL}${BASE_ENDPOINT}`),
      })
    );

    expect(logger.debug).toBeCalledWith(
      expect.objectContaining({
        message: expect.stringContaining(`response GET ${BASE_URL}${BASE_ENDPOINT}`),
      })
    );

    nock(BASE_URL).get(`/${BASE_ENDPOINT}/error`).reply(500, { success: false });
    try {
      await client.get(`${BASE_ENDPOINT}/error`, { retry: 0 });
    } catch (e) {}
    expect(logger.error).toBeCalledWith(
      expect.objectContaining({
        message: expect.stringContaining(`request error GET ${BASE_URL}${BASE_ENDPOINT}/error`),
      })
    );
  });
});

</code></pre>
<blockquote>
<p>Failing Test Error below</p>
</blockquote>
<pre><code>Error: expect(jest.fn()).toBeCalledWith(...expected)

Expected: ObjectContaining {&quot;message&quot;: StringContaining &quot;request error GET https://subdomain.domain.com/path/error&quot;}

Number of calls: 0

    at Object.&lt;anonymous&gt; (/Users/user/Documents/company/teams/team/project/test/unit/lib/got-clients.spec.js:62:26)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

</code></pre>
<p>I will really appreciate help with this. Thank you very much in advance.</p>
",https://stackoverflow.com/questions/64242643/expectations-error-while-unit-testing-got-client,"['javascript', 'unit-testing', 'jestjs', 'nock']",567,True,1,1
How to write Unit Test for UserDefaults,"<p>I have 2 functions where one basically retrieves string in User Defaults and another writes the string in User Defaults. I'm not able to understand that should I do the unit test or no? and I'm pretty new to the concept for Unit testing.</p>

<p>I scoured the internet for testing user defaults but I was advised to mock the test in the end.</p>

<p>My question is <strong>If there is a way to test User Defaults what is the best way to do it?</strong></p>

<p><strong>Constants and Structs</strong></p>

<pre><code>let defaults = UserDefaults.standard
let defaultinformation = ""ABCDEFG""

struct Keys {
    static let Information = ""Information""
}
</code></pre>

<p><strong>Function where saves Information</strong></p>

<pre><code>func SetDefaultInformation() {
    defaults.set(defaultinformation, forKey: Keys.Information)

}
</code></pre>

<p><strong>Function where retrieves Information</strong></p>

<pre><code>func checkForInformation() -&gt; String {
    let Information = defaults.value(forKey: Keys.Information) as? String ?? """"
    return Information
}
</code></pre>

<p><strong>Thanks in Advance</strong></p>
",https://stackoverflow.com/questions/59851675/how-to-write-unit-test-for-userdefaults,"['swift', 'nsuserdefaults', 'xctest', 'swift5', 'userdefaults']",3995,True,6,2
Is there any way in which we can stub meteor functions using cypress for unit testing?,"<p>I am trying to stub meteor methods and API Cypress unit testing.
My api services are deployed on spring container. [produces and consumes JSON]</p>

<p>Tried using the below code for API stubbing: </p>

<pre><code>cy.server()
cy.fixture('samplejson.json').as('sample')
cy.route('POST','https://myURL/host/login', '@sample')
</code></pre>

<p>This doesn't intercept the API call as its not a XHR request (using REST APIs).</p>

<p>Also, since the meteor framework uses a definite template for its template.js file, not sure how to stub the methods with <code>cy.stub()</code>.</p>

<p>If anyone is able to successfully stub Meteor calls such as <code>Meteor.call()</code>(in client side) or <code>HTTP.call()</code>(in methods.js), please share any references or examples.</p>

<p>Thanks</p>

<p><a href=""https://i.stack.imgur.com/HDpzR.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HDpzR.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/59752446/is-there-any-way-in-which-we-can-stub-meteor-functions-using-cypress-for-unit-te,"['javascript', 'unit-testing', 'meteor', 'mocha.js', 'cypress']",191,False,1,0
how to do unit test for functions inside of Resource class in flask-restful?,"<p>I am quite new to unit testing and relatively new to RESTful API development as well. I am wondering how to do unit test for functions inside Resource class in flask restful? I can do unit test for the endpoint's response but I don't know how to do testing for the individual functions inside the endpoint's controller class.</p>

<p>Below is my application code. It has 3 files including test:</p>

<ul>
<li>api.py</li>
<li>controller_foo.py</li>
<li>test_controller_foo.py</li>
</ul>

<pre class=""lang-py prettyprint-override""><code># api.py

from flask import Flask
from flask_restful import Api

from .controller_foo import ControllerFoo


def create_app(config=None):
    app = Flask(__name__)
    app.config['ENV'] ='development'
    return app

application = app = create_app()
api = Api(app)

api.add_resource(ControllerFoo, '/ctrl')

if __name__ == ""__main__"":
    app.run(debug=True)
</code></pre>

<pre class=""lang-py prettyprint-override""><code># controller_foo.py

from flask_restful import Resource
from flask import request

class ControllerFoo(Resource):
    """"""
    basically flask-restful's Resource method is a wrapper for flask's MethodView
    """"""
    def post(self):
        request_data = self.handle_request()
        response = self.process_request(request_data)
        return response

    def handle_request(self):
        json = request.get_json()
        return json

    def process_request(self, data):
         # do some stuffs here
         return {'foo': 'bar'}
</code></pre>

<p>I am using <code>unittest</code></p>

<pre class=""lang-py prettyprint-override""><code># test_controller_foo.py

import unittest

from api import app
from .controller_foo import ControllerFoo

# initiating class to try testing but I don't know how to start
ctrl = ControllerFoo()

class ControllerFooTestCase(unittest.TestCase):
    def setUp(self):
        self.app = app
        self.app.config['TESTING'] = True
        self.client = app.test_client()
        self.payload = {'its': 'empty'}

    def tearDown(self):
        pass

    def test_get_response(self):
        response = self.client.post('/ctrl', json=self.payload)
        expected_resp = {
            'foo': 'bar'
        }
        self.assertEqual(response.status_code, 200)
        self.assertDictEqual(response.get_json(), expected_resp)

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

<p>I want to know how to properly do unit test for <code>handle_request</code> and <code>process_request</code> function</p>

<p>EDIT: Fixing out my buggy code. Thanks <a href=""https://stackoverflow.com/users/1513933/laurent-laporte"">Laurent LAPORTE</a> for the highlights.</p>
",https://stackoverflow.com/questions/61172976/how-to-do-unit-test-for-functions-inside-of-resource-class-in-flask-restful,"['python', 'flask', 'flask-restful']",4493,True,6,1
how to do unit test for functions inside of Resource class in flask-restful?,"<p>I am quite new to unit testing and relatively new to RESTful API development as well. I am wondering how to do unit test for functions inside Resource class in flask restful? I can do unit test for the endpoint's response but I don't know how to do testing for the individual functions inside the endpoint's controller class.</p>

<p>Below is my application code. It has 3 files including test:</p>

<ul>
<li>api.py</li>
<li>controller_foo.py</li>
<li>test_controller_foo.py</li>
</ul>

<pre class=""lang-py prettyprint-override""><code># api.py

from flask import Flask
from flask_restful import Api

from .controller_foo import ControllerFoo


def create_app(config=None):
    app = Flask(__name__)
    app.config['ENV'] ='development'
    return app

application = app = create_app()
api = Api(app)

api.add_resource(ControllerFoo, '/ctrl')

if __name__ == ""__main__"":
    app.run(debug=True)
</code></pre>

<pre class=""lang-py prettyprint-override""><code># controller_foo.py

from flask_restful import Resource
from flask import request

class ControllerFoo(Resource):
    """"""
    basically flask-restful's Resource method is a wrapper for flask's MethodView
    """"""
    def post(self):
        request_data = self.handle_request()
        response = self.process_request(request_data)
        return response

    def handle_request(self):
        json = request.get_json()
        return json

    def process_request(self, data):
         # do some stuffs here
         return {'foo': 'bar'}
</code></pre>

<p>I am using <code>unittest</code></p>

<pre class=""lang-py prettyprint-override""><code># test_controller_foo.py

import unittest

from api import app
from .controller_foo import ControllerFoo

# initiating class to try testing but I don't know how to start
ctrl = ControllerFoo()

class ControllerFooTestCase(unittest.TestCase):
    def setUp(self):
        self.app = app
        self.app.config['TESTING'] = True
        self.client = app.test_client()
        self.payload = {'its': 'empty'}

    def tearDown(self):
        pass

    def test_get_response(self):
        response = self.client.post('/ctrl', json=self.payload)
        expected_resp = {
            'foo': 'bar'
        }
        self.assertEqual(response.status_code, 200)
        self.assertDictEqual(response.get_json(), expected_resp)

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

<p>I want to know how to properly do unit test for <code>handle_request</code> and <code>process_request</code> function</p>

<p>EDIT: Fixing out my buggy code. Thanks <a href=""https://stackoverflow.com/users/1513933/laurent-laporte"">Laurent LAPORTE</a> for the highlights.</p>
",https://stackoverflow.com/questions/61172976/how-to-do-unit-test-for-functions-inside-of-resource-class-in-flask-restful,"['python', 'flask', 'flask-restful']",4493,True,6,1
How does Enzyme setState() works on shallow components?,"<p>I have a component which renders different things according to current local state. I'm pretty new to unit testing and I don't understand why my tests are failing.
Here is my component (simplified for better understanding) : </p>

<pre><code>  state = {
      data: {},
      currentStatus: ""LOADING"",
  }


  render() {
    return (
      &lt;div className={cx(styles.syntheseContainer)}&gt;
        {
            {
                ""SUCCESS"":
                    &lt;div className={styles.successContainer}&gt;something here&lt;/div&gt;,
                    ""EMPTY"": null,
                    ""LOADING"": &lt;div className={styles.fullWidth}&gt;
                                    &lt;TextLoader /&gt;
                               &lt;/div&gt;,
                    ""NOT_STARTED"": &lt;div className={styles.notStartedBox}&gt;
                                &lt;FormattedMessage id=""fallback.not_started"" defaultMessage=""Le débat n'a pas encore commencé"" /&gt;
                             &lt;/div&gt;,
                    ""ERROR"": &lt;div className={styles.errorBox}&gt;
                                &lt;FormattedMessage id=""fallback.error"" defaultMessage=""Une erreur est survenue lors de la récupération du débat"" /&gt;
                            &lt;/div&gt;,
            }[this.state.currentStatus]
        }
      &lt;/div&gt;
    );
  }
} 
</code></pre>

<p>Here, I want to setState in my test file and check if the classNames are correct according to the currentState.</p>

<pre><code>  const wrapper = shallow(
    &lt;Synthese {...mockProps} /&gt;
  );
  wrapper.setState({currentStatus: ""ERROR""});
  expect(wrapper.find('div').hasClass('errorBox')).toBe(true);
})
</code></pre>

<p>I don't understand why it is not working + the shallow rendering seems to not taking into account my setState.</p>

<p>If somebody could give me any clues about how it works or why it is not working.
Thanks!</p>
",https://stackoverflow.com/questions/61614031/how-does-enzyme-setstate-works-on-shallow-components,"['reactjs', 'unit-testing', 'testing', 'enzyme']",280,True,0,1
Passing data between ViewModels in MVVM-C,"<p>I am using MVVM with Coordinator to design an application. One thing that i am having doubts on is on how to pass data between different <code>ViewModels</code>. Normally the previous viewModel would just create the next viewModel and would just do a method dependency injection in <code>prepareforsegue</code>. However now that i am responsible for all the navigation how do i achieve this ?</p>
<pre><code>Class AppCoordinator : NSObject, Coordinator, UINavigationControllerDelegate {

    var childCoordinators = [Coordinator]()
    var navigationController: UINavigationController
    var dependencyContainer : MainDependencyContainer
    
    func start() {
        let vc = ViewController.instantiate()
        vc.coordinator = self
        vc.viewModel = dependencyContainer.makeMainViewModel()
        navigationController.delegate = self
        navigationController.pushViewController(vc, animated: true)
    }

    func createAccount() {
        let vc = CreateAccountViewController.instantiate()
        vc.coordinator = self
        navigationController.pushViewController(vc, animated: true)
    }

}
</code></pre>
<p>I could ofcourse create the <code>ViewModel</code> for <code>CreateAccountViewController</code> in <code>MainViewModel</code> and pass the <code>ViewModel</code> as a paramter in <code>createAccount</code> method but is it the right way to do it here ? What will be the unit testing implications here ?</p>
",https://stackoverflow.com/questions/64001186/passing-data-between-viewmodels-in-mvvm-c,"['ios', 'swift', 'mvvm', 'dependency-injection', 'coordinator-pattern']",1633,True,0,1
Jsoup.Element.text() not correctly encoding utf-8,"<p>I am doing my project in eclipse, JDK 1.8.
My client recently add a new request to enable the saving and retrieval in Arabic letters too. I am have added <code>useUnicode=true&amp;characterEncoding=UTF-8</code>
in jdbc url. Now saving the data works correctly and I am getting the response in UTF-8 encoded form. it is working fine. for that I have added</p>
<p><code>path = &quot;/v2&quot;,consumes=&quot;application/json;charset=UTF-8&quot;, produces = &quot;application/json;charset=UTF-8&quot;</code></p>
<p>In all my controllers. I have an Api to generate labels in which I am using jsoup to edit html template. And then converting to pdf using wkhtmltopdf library. This fuction is working correctly if iam using english,</p>
<pre><code>org.jsoup.nodes.Document doc = Jsoup.parse(template, &quot;UTF-8&quot;, &quot;&quot;);
Element customerName = doc.getElementById(&quot;name&quot;);
customerName.text(orderAddress.getName());
</code></pre>
<p>if <code>orderAddress.getName()</code>
is in Arabic I am getting <code>?????</code> I just tried to print in console is also getting the same.<code>logger.debug(&quot;Name:&quot;+orderAddress.getName());</code><br />
Eclipse is enabled to use utf-8.
I also tried to use like this</p>
<pre><code>customerName.text(new String(orderAddress.getName().getBytes(),&quot;UTF-8&quot;));
logger.debug(&quot;Name:&quot;+new String(orderAddress.getName().getBytes(),&quot;UTF-8&quot;));
</code></pre>
<p>also getting same.
in my unit testing I tried to use like this  <code>customerName.text(&quot;فاسيلة&quot;);</code>working correctly. and generating pdf exactly what I needed.</p>
<p>I have seen few questions similar to this but not none of them solved my issue. Since GET is working fine , I am sure about retrieving data from DB is not an issue. Since unit testing working fine encoding in that end also working fine. Now i am missing something related to jsoup.
What is I am missing in my attempt?
Some one know please help me.</p>
",https://stackoverflow.com/questions/64549061/jsoup-element-text-not-correctly-encoding-utf-8,"['java', 'utf-8', 'jsoup']",547,True,1,2
Unit testing method with async,"<p>I am writing a unit test for a method using <code>Moq</code> framework.  </p>

<p>The method calls the method <code>Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request)</code> of <code>System.Net.Http</code> with <code>await</code>.</p>

<p>When I execute my test case the method does not return anything. Certainly, I am doing something wrong. Please help me to find it.</p>

<p>Please note that this call is not loosely coupled.</p>

<p>I did check the other answers like <a href=""https://stackoverflow.com/questions/19365479/unit-testing-async-method-test-never-completes"">Unit testing async method - test never completes</a> which have it as loosely coupled and could be mocked.</p>

<p><strong>Edit 1</strong>: 
The method similar to which I am trying to unit test</p>

<pre><code>class Class1
    {
        public async Task&lt;string&gt; Method(string url)
        {

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,url);
            HttpResponseMessage response = await new HttpClient().SendAsync(request);
            return System.Convert.ToString( response);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/60995119/unit-testing-method-with-async,"['unit-testing', 'asynchronous', 'moq']",384,True,0,1
Error while performing angular Unit testing with SpyOn document,"<p>I am trying to do the unit testing for component, I mocked the data and expecting some result but getting an error, below is my unit test.</p>

<pre><code>it('should call getData method ', () =&gt; {
    const usageService = TestBed.get(UsageService);
    component.slug = 'slugName';
    spyOn(document, 'getElementById').and.returnValue(""slugName"");
    component.ngOnInit();
    expect(usageService.getData).toHaveBeenCalled();
    });
</code></pre>

<p>In above I am getting an error at line <code>spyOn(document, 'getElementById').and.returnValue(""slugName"");</code></p>

<p>Error is: </p>

<blockquote>
  <p>Argument of type ""slugName"" is not assignable to parameter of type
  'HTMLElement'.</p>
</blockquote>

<p>This issue comes after upgrading jasmine version from <strong>2.8</strong> to <strong>3.5.10</strong></p>

<p>I don't know what's wrong in this code, why previously it was working fine and now after upgrading it won't work.</p>

<p>please help me to resolve the issue.</p>
",https://stackoverflow.com/questions/61954745/error-while-performing-angular-unit-testing-with-spyon-document,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-mocha']",645,True,0,2
Gtest C++ - Can we mock the non virtual functions of same class which we are testing,"<p>I was trying to do the unit testing in Gtest for the function BaseClass::Start. I have 2 doubts.</p>
<p>While doing Gtest with C++,</p>
<p>1.Can we mock the non virtual functions of same class which we are testing?</p>
<p>i.e; In my example code method IsInitialized() of the same class which I am testing.</p>
<p>2.Can we mock the non virtual functions of other classes which have dependency in the function we are testing?</p>
<p>i.e; In my example code CheckerClass::IsParamSupported(m_randomId) which is a method of the class CheckerClass</p>
<p>My code is given below:</p>
<pre><code> std::string BaseClass::Start(std::vector&lt;int&gt; iv) 
  {
    auto requiredIVSize = GetIvSize();

    if(!IsInitialized())
    {
        return &quot;notInitialised&quot;;
    }
    
    if((!CheckerClass::IsParamSupported(m_randomId)) &amp;&amp; (iv.empty() == false))
    {
        return &quot;unsupportedParam&quot;;
    }

    if(iv.size() != requiredIVSize)
    {
        return &quot;sizeNotCorrect&quot;;
    }
    else return &quot;Ok&quot;;
 }
</code></pre>
",https://stackoverflow.com/questions/64658512/gtest-c-can-we-mock-the-non-virtual-functions-of-same-class-which-we-are-tes,"['c++', 'googletest', 'googlemock']",175,False,0,0
How to mock PHP&#39;s own methods using PHPUnit,"<p>I want to add test coverage to a method inside a PHP class which invokes a PHP-built-in method. To be able to mock <code>copy()</code>, I had to create a wrapper class. <strong>Is there a better way to mock PHP's built-in methods?</strong> By &quot;better&quot;, I mean that I do not want to introduce a wrapper class just for the sake of the unit testing.</p>
<p>I've checked <a href=""https://phpunit.readthedocs.io/en/9.3/test-doubles.html#mock-objects"" rel=""nofollow noreferrer"">these docs</a> but could not find an answer.</p>
<p>I use PHP and PHPUnit only for a side project, therefore I might overlook something obvious?</p>
",https://stackoverflow.com/questions/65401034/how-to-mock-phps-own-methods-using-phpunit,"['mocking', 'phpunit']",173,True,0,1
RSpec Testing for Slack-Ruby-Bot Commands,"<p>I have been implementing a basic slack bot to a channel and as the code is very simple I have no public methods. Just commands from slack-ruby-bot gem. But as project requirement I need to add several unit testing to my project. Basically when I give command of @ruby_codes strings it gives me the wiki page of that area. how can I test this? attached my version but tests fail everytime.</p>
<p>My command example is as follows:</p>
<pre><code>module RubyCodes
  # SlackBot command methods#
  class GetWiki &lt; SlackRubyBot::Commands::Base
    command 'strings' do |client, data, _match|
      client.say(channel: data.channel, text: 'https://en.wikipedia.org/wiki/Ruby_(programming_language)#Strings')
    end
</code></pre>
<p>My test case is as follows:</p>
<pre><code>describe SlackRubyBot::Commands do
  it 'returns ruby strings wiki page' do
    expect(message: &quot;#{SlackRubyBot.config.user} strings&quot;).to respond_with_slack_message('https://en.wikipedia.org/wiki/Ruby_(programming_language)#Strings')
  end
end
</code></pre>
<p>Thanks in advance!</p>
<p>also, this is the error I get:</p>
<pre><code>expected to receive message with text: https://en.wikipedia.org/wiki/Ruby_(programming_language)#Strings once,
        received:[{:text=&gt;&quot;Sorry &lt;@user&gt;, I don't understand that command!&quot;, :channel=&gt;&quot;channel&quot;}]
</code></pre>
",https://stackoverflow.com/questions/63702179/rspec-testing-for-slack-ruby-bot-commands,"['ruby', 'rspec', 'slack-api']",250,False,0,0
Whats the benefit or purpose of unit testing a void method like doFilter?,"<p>I am on the java tomcat stack and creating a new filter. <a href=""https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpFilter.html"" rel=""nofollow noreferrer"">https://javaee.github.io/javaee-spec/javadocs/javax/servlet/http/HttpFilter.html</a> I am interested in unit testing it because I want to have 100% branch coverage.</p>

<p>This filter wraps the response object. We override the default behavior of the response such that whenever we call response.addCookie(cookie), we append the string ""happy"" to the cookie name:</p>

<pre><code>HappyCookieFilter implements Filter {
HappyCookieResponseWrapper happyCookieResponseWrapper;
...

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    chain.doFilter(req, happyCookieResponseWrapper.wrap(res));
}

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

<ol>
<li>Assuming the HappyCookieResponseWrapper is already unit tested, what would be the benefit of testing doFilter method?</li>
<li>How would I test the HappyCookieFilter.doFilter and what should I assert?</li>
</ol>
",https://stackoverflow.com/questions/59783797/whats-the-benefit-or-purpose-of-unit-testing-a-void-method-like-dofilter,"['java', 'unit-testing', 'tomcat']",49,True,-1,3
Typescript imported objects are undefined,"<p>I have a file called <code>mock_event</code> which is used to create an event object to be used in unit testing. You can see it being created below:</p>
<p><strong>mock_event.ts</strong></p>
<pre><code>import {Event} from &quot;../../../models/src/event&quot;;
import {EventUserView} from &quot;../../../models/src/event_user_view&quot;;


let validEvent: Event;
validEvent = new Event({
    'eventId': '123',
    'organizer': new EventUserView({
        'displayName': 'Jim'
    })
});

export {validEvent};
</code></pre>
<p>Now, when I import the object <code>validEvent</code>, it is <code>undefined</code>. I'm pretty new to typescript, I'm sure I'm missing something, but this doesn't seem complicated. It's even undefined if I put a breakpoint on the export statement, which is pretty weird, because the object is instantiated on the line immediately prior. I don't get any exceptions. Does anyone know what is happening here?</p>
",https://stackoverflow.com/questions/63909379/typescript-imported-objects-are-undefined,"['typescript', 'import']",539,True,0,1
Unit test BizTalk Schemas &amp; Maps using Visual Studio 2019,"<p>I have a requirement to unit test BizTalk Schemas &amp; Maps using Visual Studio 2019.
We are now upgrading to BizTalk 2020 and working on few items to get this done.</p>
<p>I am following this document but could not find the unit test wizard as mentioned in steps 6 &amp; 7</p>
<p><a href=""https://learn.microsoft.com/en-us/biztalk/core/using-the-unit-testing-feature-with-schemas-and-maps"" rel=""nofollow noreferrer"">Using the Unit Testing Feature with Schemas and Maps</a> (learn.microsoft.com)</p>
<p>i.e I have created a new Unit test Project, but under the Test Menu, I could not see New test-&gt;Unit Test Wizard.</p>
<p>Am I missing something?</p>
<p>Can anyone provide information on this, please?</p>
",https://stackoverflow.com/questions/63589813/unit-test-biztalk-schemas-maps-using-visual-studio-2019,"['unit-testing', 'schema', 'visual-studio-2019', 'biztalk', 'biztalk-2020']",182,False,0,1
How to test a function running a coroutine in an Android instrumented test?,"<p>In my Android Kotlin project, I have a class, with a function running a coroutine, that I want to test using an instrumented test (not unit test).</p>

<p>Here is what it looks like:</p>

<pre class=""lang-kotlin prettyprint-override""><code>class DemoClass
{
    fun demo(liveData: MutableLiveData&lt;String&gt;)
    {
        CoroutineScope(IO).launch {
            val result = doStuff()
            withContext(Main) { liveData.value = result }
        }
    }
}
</code></pre>

<p>In my instrumented test class, here is what I tried:</p>

<pre class=""lang-kotlin prettyprint-override""><code>@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest
{
    @ExperimentalCoroutinesApi
    @Test
    fun testCoroutine() = runBlockingTest {
        val demoClass = DemoClass()
        val liveData = MutableLiveData&lt;String&gt;()
        demoClass.demo(liveData)
        assertEquals(""demo"", liveData.value)
    }
}
</code></pre>

<p>Unfortunately, it's not working. It seems like <code>runBlockingTest {}</code> is only available for unit testing, not instrumented testing. Here is my error when I run the test:</p>

<pre><code>java.lang.NoClassDefFoundError: Failed resolution of: Lkotlinx/coroutines/test/TestBuildersKt;
</code></pre>

<p>So how can I test <code>DemoClass.demo()</code> and the <code>liveData</code> value in an instrumented test?</p>

<p>Thanks.</p>

<p><strong>EDIT</strong></p>

<p>I also tried this:</p>

<pre class=""lang-kotlin prettyprint-override""><code>@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest
{
    private val testDispatcher = TestCoroutineDispatcher()

    @Before
    fun setup() {
        Dispatchers.setMain(testDispatcher)
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }

    @Test
    fun testCoroutine(): Unit = runBlocking {
        val demoClass = DemoClass()
        val liveData = MutableLiveData&lt;String&gt;()
        demoClass.demo(liveData)
        assertEquals(""demo"", liveData.value)
    }
}
</code></pre>

<p>The test runs, but I got this:</p>

<pre><code>java.lang.AssertionError: 
Expected :demo
Actual   :null
</code></pre>
",https://stackoverflow.com/questions/62358412/how-to-test-a-function-running-a-coroutine-in-an-android-instrumented-test,"['android', 'kotlin', 'kotlin-coroutines', 'instrumented-test']",1100,False,0,1
Is saving roles in local storage safe in Nuxt Js SSR?,"<p>so I have 1 page for the Admin and Supervisor roles, each role has a different component but still one page, then I make the condition v-if = &quot;role === 'Admin'&quot;, and I take the role from local storage.  My question is will it be safe?  then can it be used in SSR?  and will it pass using the unit testing jest?</p>
<p>I have gone too far in working on the project, which I am afraid storing in the local storsge is not safe, thank you. I hope someone helps my question</p>
",https://stackoverflow.com/questions/64888156/is-saving-roles-in-local-storage-safe-in-nuxt-js-ssr,"['vue.js', 'nuxt.js']",213,False,0,0
"Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function in Jamsine","<p>I'm new to Unit testing in Angular using Jasmine and Karma. I've written a spec file but I'm getting an error. Let me first show what I've done so far. I've created a custom component:</p>

<p><strong>TimeselectorComponent</strong></p>

<pre><code>startRange = moment('12-01-01');
endRange = moment ('12-12-01');

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

date = new Date();
currentYear = this.date.getFullYear(); // or simply currentYear = 2020;

@ViewChild('primaryMonthPicker') primaryMonthPicker: MonthpickerComponent; // a child component

primaryDropDown(startRange, endRange) {
    if (this.primaryMode === this.modes[0]) {
        this.initCalendarYear(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[1]) {
        this.initYearToDate(this.primaryMonthPicker, this.currentYear);
    } else if (this.primaryMode === this.modes[2]) {
        this.initRollingYear(this.primaryMonthPicker, this.currentYear);
    }
}
</code></pre>

<p>In the above code <code>MonthpickerComponent</code> is another custom component which is the only child component of <code>TimeselectorComponent</code>.</p>

<p>I just want to check when <code>primaryDropDown</code> is called then <code>initCalendarYear</code> should also be called. Here's the spec file:</p>

<pre><code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () =&gt; {
    let fixture: ComponentFixture&lt;TimeselectorComponent&gt;;

    @Component({
        selector: 'app-monthpicker',
        template: '&lt;div&gt;&lt;/div&gt;'
    })
    class FakeMonthpickerComponent {
        // methods of MonthpickerComponent
    }

    let MODES = [];

    beforeEach(async(() =&gt; {
        MODES = ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
        TestBed.configureTestingModule({
            declarations: [FakeMonthpickerComponent, TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

    // other test cases that are passing

    // need help with this test case
    it('should call initCalendarYear when primaryDropDown is called', () =&gt; {
      const startRange=moment('2020-01-01');
      const endRange= moment('2020-12-01');
      spyOn(fixture.componentInstance, 'initCalendarYear');
      fixture.componentInstance.primaryMode=MODES[0];
      fixture.componentInstance.primaryDropDown(startRange, endRange);
     expect(fixture.componentInstance.initCalendarYear).toHaveBeenCalled();
  });
});
</code></pre>

<p>But I'm getting this error:
<a href=""https://i.stack.imgur.com/sKAAJ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sKAAJ.png"" alt=""enter image description here""></a></p>

<p>I have to test whether correct method is called for associated <code>if-else</code> statement. Please help me.</p>

<p>Here's the <a href=""https://stackblitz.com/edit/angular-ivy-tbpmju"" rel=""nofollow noreferrer"">stackblitz</a>.</p>
",https://stackoverflow.com/questions/62120414/error-tohavebeencalled-expected-a-spy-but-got-function-in-jamsine,"['angular', 'unit-testing', 'karma-jasmine']",554,True,0,2
"&#39;npm run test&#39; works, but &#39;jest --coverage&#39; command does not work","<p>I have MonoRepo project (using <a href=""https://github.com/lerna/lerna"" rel=""nofollow noreferrer"">Lerna</a>) which consists of multiple packages, and one of them is a React application.</p>

<p>Within the React project package, I utilise Jest for unit testing. However, when I run the <code>jest --coverage</code> command on the WebStorm console, it returns me the following error:</p>

<blockquote>
  <p>zsh: command not found: jest</p>
</blockquote>

<p>Strangely enough, if I use <code>npm run test</code>, the test runs, and my test coverage report is generated. Here is part of my <code>package.json</code>:</p>

<pre><code>""scripts"": {
  ""test"": ""jest --coverage"",
  // other stuff
},
</code></pre>

<p>As you can see, <code>npm run test</code> runs <code>jest --coverage</code>, which is the exact command I initially entered. Why won't the <code>jest</code> command work on its own? </p>
",https://stackoverflow.com/questions/60211347/npm-run-test-works-but-jest-coverage-command-does-not-work,"['javascript', 'reactjs', 'npm', 'jestjs', 'lerna']",4567,False,-2,2
Write unit testing for Strapi APIs,"<p>Am trying to start writing Unit test for Strapi endpoint or APIs. Since it is way different from Express and does not have a app.route concept in my view. I am not sure on how to start with.</p>

<p>I have had experience in write unit test suits for APIs with Mocha, Sinon and Chai. But how do they work with Strapi APIs is my question.</p>

<p>If anyone having knowledge on unit testing Strapi API, it will be a great head start for me.</p>

<p>Updating the question with code under test</p>

<p>controllers/checkStatus.js</p>

<pre><code>module.exports = {

    checkStatus: async (ctx) =&gt; {
       return strapi.services.checkstatus.getStatus(ctx.request.body.id);
    }
};
</code></pre>

<p>services/checkstatus.js</p>

<pre><code>module.exports = {

    getStatus: (id) =&gt; {
       return id;
    }
};
</code></pre>
",https://stackoverflow.com/questions/61102055/write-unit-testing-for-strapi-apis,"['node.js', 'unit-testing', 'mocha.js', 'sinon', 'strapi']",557,False,0,1
Testing Input Data in React using Jest,"<p>I have created a simple form in React and I am using Jest to practice my unit testing. I am currently testing my Form Component that renders the input values into the DOM and it keeps on failing because of the TypeError: Cannot read property 'firstName' of undefined. My goal is for all the input labels to be able to pass.</p>
<p><strong>FormComponent.js</strong></p>
<pre><code>import React from 'react'

const FormComponent = (props) =&gt; {
return (
    &lt;main&gt;

        &lt;form&gt;
            &lt;input type=&quot;text&quot; value = {props.data.firstName}  name = &quot;firstName&quot; placeholder = &quot;First Name&quot; onChange = {props.handleChange} /&gt; &lt;br/&gt;
            &lt;input type=&quot;text&quot; value = {props.data.lastName}  name = &quot;lastName&quot; placeholder = &quot;Last Name&quot; onChange = {props.handleChange} /&gt; &lt;br/&gt;
            &lt;input type=&quot;text&quot; value = {props.data.age}  name = &quot;age&quot; placeholder = &quot;Age&quot; onChange = {props.handleChange} /&gt; &lt;br/&gt;
            &lt;input type=&quot;text&quot; value = {props.data.location}  name = &quot;location&quot; placeholder = &quot;Location&quot; onChange = {props.handleChange} /&gt; &lt;br/&gt;
            &lt;br/&gt;
            &lt;label&gt;
                &lt;input 
                    type = &quot;radio&quot;
                    value = &quot;Male&quot;
                    name = &quot;gender&quot;
                    checked = {props.data.gender === &quot;Male&quot;}
                    onChange = {props.handleChange}
                    /&gt; Male
                    &lt;br/&gt;
            &lt;/label&gt;
            &lt;label&gt;
                &lt;input 
                    type = &quot;radio&quot;
                    value = &quot;Female&quot;
                    name = &quot;gender&quot;
                    checked = {props.data.gender === &quot;Female&quot;}
                    onChange = {props.handleChange}
                    /&gt; Female
                    &lt;br/&gt;
            &lt;/label&gt;

            &lt;br /&gt;
            &lt;br /&gt;
            
            &lt;button&gt;Submit&lt;/button&gt;
            &lt;br /&gt;
            &lt;br /&gt;
            &lt;h1&gt;Entered information: &lt;/h1&gt;
            &lt;h3&gt;Your name: {props.data.firstName} {props.data.lastName} &lt;/h3&gt;
            &lt;h3&gt;Your age: {props.data.age} &lt;/h3&gt;
            &lt;h3&gt;Gender: {props.data.gender} &lt;/h3&gt;
            &lt;h3&gt;Location: {props.data.location} &lt;/h3&gt;
                   
        &lt;/form&gt;
    &lt;/main&gt;
  )
}


export default FormComponent
</code></pre>
<p><strong>FormComponent.test.js</strong></p>
<pre><code>import React from 'react'
import FormComponent from './FormComponent'
import Enzyme,{
configure,
shallow,
mount,
render } from 'enzyme'
import Adapter from &quot;enzyme-adapter-react-16&quot;

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

global.React = React;
global.Enzyme = Enzyme;
global.shallow = shallow;
global.render = render;
global.mount = mount;

describe(&quot;Form Input Data&quot;, () =&gt; {
    it(&quot;should render the first name&quot;, () =&gt; {
        const component = shallow(&lt;FormComponent 
          name = &quot;firstName&quot; label = &quot;First Name&quot;  /&gt;)
        const label = component.find('label')
        expect(label).toHaveLength(1);
        expect(label.prop('htmlFor')).toEqual('firstName');
        expect(label.text()).toEqual('First Name');
    
        const input = component.find('input');
        expect(input).toHaveLength(1)
        expect(input.prop('type')).toEqual('text')
        expect(input.prop('name')).toEqual('firstName')
        expect(input.prop('id')).toEqual('firstName')
    })
})
</code></pre>
<p><strong>Testing Results</strong></p>
<p><a href=""https://i.stack.imgur.com/XBPnw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/XBPnw.png"" alt=""Test Results"" /></a></p>
<p>This is my first time testing in React using Jest and I have no idea how to get my component to pass. I really appreciate all possible solutions. Thanks.</p>
",https://stackoverflow.com/questions/64688249/testing-input-data-in-react-using-jest,"['javascript', 'reactjs', 'unit-testing', 'testing', 'jestjs']",2000,False,0,1
&quot;Security&quot; class not found when doing unit testing,"<p>I'm discovering unit testing with phpunit and I want to test some method inside my service. </p>

<p>Here is my test code to do so: </p>

<pre><code>&lt;?php

namespace App\Tests;

use App\Services\SortingDataSearchedProductService;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SearchedProductTest extends WebTestCase
{

    private $sortingDataSearchedProductService;

    public function setUp()
    {
        self::bootKernel();
        $container = self::$container;
        $this-&gt;sortingDataSearchedProductService = $container-&gt;get(SortingDataSearchedProductService::class);
    }

    public function testFindStatusLinkedToGrantedRoles() {
        $grantedRolesList = [];

        $this-&gt;sortingDataSearchedProductService-&gt;findStatusLinkedToGrantedRoles($grantedRolesList);
    }

}
</code></pre>

<p>But when I try my test here is what I get:</p>

<blockquote>
  <p>Cannot autowire service ""App\Form\CpomAf\SearchProductType"": argument ""$security"" of method ""__construct()"" references class ""Symfony\Component\Security\Core\Security"" but no such service exists.</p>
</blockquote>

<p>I think I get this error because the testing is going through the page where the function I want to test is. Here is the service I want to test : </p>

<pre><code>&lt;?php

namespace App\Services;


use App\Entity\Custom\SearchProduct;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Security;
use App\Entity\User;
use Symfony\Component\Yaml\Yaml;

/**
 * Class SortingDataSearchedProductService
 * @package App\Services
 */
class SortingDataSearchedProductService
{
    /**
     * @var Security
     */
    private $security;


    /**
     * SortingDataSearchedProductService constructor
     * @param Security $security
     */
    public function __construct(Security $security)
    {
        $this-&gt;security = $security;
    }

    /**
     * Form Data
     * @param SearchProduct $searchedData
     *
     * @return array
     */
    public function findDataOfSearchWithConditions(SearchProduct $searchedData): array
    {
        /** @var User $user */
        $user = $this-&gt;security-&gt;getUser();
        $userPermissions = $user-&gt;getPermissions();

        return $this-&gt;findStatusLinkedToGrantedRoles(
            $userPermissions
        );
    }

    /**
     * Get array of final list of granted roles
     *
     * @param array $userPermissions
     * @return array
     */
    public function findStatusLinkedToGrantedRoles(array $userPermissions): array
    {
        //Getting the list of role linked to status from yaml file
        $permissionStatusList = Yaml::parseFile(dirname(__DIR__).'/../config/roles.yaml');
        $arrayPermissionListStatus = $permissionStatusList[0];

        //Declaration array status list
        $statusList = [];

        //Getting status linked to permissions
        foreach ($userPermissions as $userPermission) {
            if (array_key_exists($userPermission, $arrayPermissionListStatus)) {
                foreach ($arrayPermissionListStatus[$userPermission] as $status) {
                    array_push($statusList, $status);
                }
            }
        }

        //Deleting double values
        return  array_values(array_unique($statusList));
    }

}
</code></pre>

<p>I understand my error refers to my formtype file but in the service I'm targetting the only thing that links to my form is <strong>$searchedData</strong> which this the data returned by the submission of my form (that I'm not using yet). Hence, I'm not sure why it's going through my form type file and why it doesn't consider Security as a class. </p>

<p>I tried to use MockBuilder like so in my set up but it didn't help. Maybe I'm using unit testing in the wrong way ? </p>

<pre><code>$this-&gt;getMockBuilder('Symfony\Component\Security\Core\SecurityContextInterface')
           -&gt;disableOriginalConstructor()
           -&gt;getMock();
</code></pre>

<p><strong>EDIT</strong> </p>

<p>Here is the content inside my autoload classmap file after I did the dump autoload command : </p>

<pre><code>    &lt;?php

// autoload_classmap.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Collator' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/Collator.php',
    'IntlDateFormatter' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/IntlDateFormatter.php',
    'JsonException' =&gt; $vendorDir . '/symfony/polyfill-php73/Resources/stubs/JsonException.php',
    'Locale' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/Locale.php',
    'NumberFormatter' =&gt; $vendorDir . '/symfony/intl/Resources/stubs/NumberFormatter.php',
    'SqlFormatter' =&gt; $vendorDir . '/jdorn/sql-formatter/lib/SqlFormatter.php',
);
</code></pre>

<p>I if remember correctly it regenerates the list of all classes that need to be included in the project. So it means that security is there isn't it? </p>
",https://stackoverflow.com/questions/61060162/security-class-not-found-when-doing-unit-testing,"['symfony', 'phpunit']",183,False,1,0
Iterate through an IEnumerable that uses yield,"<p>I have started unit testing my system and have a bunch of tests (using Xunit) taking the following TestData(), one vector at a time:</p>
<pre><code>public static IEnumerable&lt;object[]&gt; TestData()
{
   yield return new object[] { true, false };
   yield return new object[] { false, false };
   yield return new object[] { true, true };
   yield return new object[] { false, true };
}
</code></pre>
<p>Now I am wondering if there is a way to (re)use the entire set within a same/single test.<br />
For instance, here is a test I am trying to set up:</p>
<pre><code>[Theory]
public void CanCheckAllInOneGo()
{
    bool error = false;

    // The foreach does not work
    foreach (var a in TestData())
    {
        error |= doSomething(a[0], a[1]);
    }
            
    Assert.True(error != true, &quot;doSomething() failed&quot;);
} 
</code></pre>
<p>Note, in order to run one vector at a time, I previously used the following attributes:</p>
<pre><code>[Theory]
[MemberData(nameof(TestData))]
</code></pre>
<p>Maybe it is not possible because of the &quot;yield&quot;. If not, how would you do that? Thanks.</p>
",https://stackoverflow.com/questions/63412305/iterate-through-an-ienumerable-that-uses-yield,"['c#', 'foreach', 'ienumerable', 'xunit']",390,True,0,2
Vue 3 safe to use for new big projects?,"<p>I will be developing an application for a big company and im wondering if it is safe to use Vue 3 in its current state. Support for global state, routing and unit testing is a must but im not sure if it is supported in a stable manner. The next version of Vue Test Utils supports Vue 3 but is currently in beta. As a fan of Test Driven Development the latter is an absolute must.</p>
<p>Should I stick with Vue 2? Use Vue 3 and progressively enhance?</p>
<p>I would appreciate some feedback.</p>
",https://stackoverflow.com/questions/64459573/vue-3-safe-to-use-for-new-big-projects,"['vue.js', 'vue-test-utils', 'vuejs3']",478,True,0,1
How to handle Status NOT FOUND in client service,"<p>I am new to developing microservice application backend.</p>
<p>I am trying to fetch country details from other service in a spring boot microservice architecture. As part of Unit testing I am writing a negative test case where the CommonData mricroservice I am requesting to would return http status NOT FOUND when passing an non-existing country code.</p>
<p>However the ResponseEntity is throwing a HttpClientErrorExeption$NotFound: 404: [no body].</p>
<p>How should I handle such expected responses?</p>
<p><strong>CommonData MicroService - Controller</strong></p>
<pre><code>@RestController
@RequestMapping(&quot;countries&quot;)
public class CountryController {

    CountryService countryService;

    @Autowired
    CountryController(CountryService countryService) {
        this.countryService = countryService;
    }

    ...
    ...
    ...

    @GetMapping(path = &quot;/{code}&quot;, produces = { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public ResponseEntity&lt;Country&gt; getCountry(@Valid @PathVariable String code) {
        Country country = countryService.getCountry(code);
        if(country == null)
            return new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND);
        return new ResponseEntity&lt;&gt;(country, HttpStatus.FOUND);
    }
}
</code></pre>
<p><strong>User MicroService - CommonDataService</strong></p>
<pre><code>Country getCountryByCode(String code) throws Exception {
    String path = BASE_PATH + &quot;/&quot; + code;
    InstanceInfo instance = eurekaClient.getApplication(serviceId)
                                        .getInstances().get(0);
    
    String host = instance.getHostName();
    int port = instance.getPort();
    
    URI uri = new URI(&quot;http&quot;, null, host, port, path, null, null);
    RequestEntity&lt;Void&gt; request = RequestEntity.get(uri)
                                .accept(MediaType.APPLICATION_JSON).build();
    
    ResponseEntity&lt;Country&gt; response = restTemplate.exchange(request, Country.class);
    
    if(response.getStatusCode() != HttpStatus.FOUND)
        return null;
    
    return response.getBody();
}
</code></pre>
<p><strong>NegativeTestCase</strong></p>
<pre><code>@Test
void shouldReturnNullWhenInvalidCountryCodePassed() throws Exception {
    String countryCode = &quot;GEN&quot;;
    Country actual = commonDataService.getCountryByCode(countryCode);
    assertNull(actual);
}
</code></pre>
<p>Any suggestions to improve the code is also welcome.</p>
",https://stackoverflow.com/questions/64183874/how-to-handle-status-not-found-in-client-service,"['java', 'spring-boot', 'rest', 'microservices', 'spring-resttemplate']",337,False,0,1
"Laravel 8.x, make fake model reationships?","<p>I'm trying to run a faker factory for relationships, but the field always returns NULL. How do fake a model relationship <em>without</em> hitting the database?</p>
<p>I have a Map factory with a one-to-one relationship to a parent Event table. I need to fake this relationship for unit testing:</p>
<pre class=""lang-php prettyprint-override""><code>/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'event' =&gt; 'faker.' . join('_', $this-&gt;faker-&gt;words),
        'category' =&gt; $this-&gt;faker-&gt;word,
        'sub_category' =&gt; $this-&gt;faker-&gt;word,
        'priority' =&gt; $this-&gt;faker-&gt;randomElement(['normal', 'high']),
        'event' =&gt; Event::factory()-&gt;makeOne(),
    ];
}
</code></pre>
<p>This returns a fake model, but <code>event</code> is null, from the debugger:</p>
<pre><code>result = {array} [5]
 event = &quot;faker.eum_voluptatibus_aut&quot;
 category = &quot;libero&quot;
 sub_category = &quot;aut&quot;
 priority = &quot;high&quot;
 event = null
</code></pre>
<p>I tried using states, but the same thing happens:</p>
<pre class=""lang-php prettyprint-override""><code>public function disabled()
{
    return $this-&gt;state([
        'event' =&gt; Event::factory()-&gt;makeOne(['enabled' =&gt; false]),
    ]);
}
</code></pre>
<p>The object is returned with an empty <code>event</code> value. I need a faker object I can transverse down into: <code>if ($object-&gt;event-&gt;enabled) [...]</code>. How do I generate fake model relationships?</p>
",https://stackoverflow.com/questions/63943353/laravel-8-x-make-fake-model-reationships,"['php', 'laravel', 'laravel-8']",1317,True,0,2
"Unit, Integration and Functional Testing","<p>I am working on Test Case and I would like to get clarity about which are the directories &amp; files that come under,</p>

<ol>
<li>Unit Testing.</li>
<li>Integration Testing.</li>
<li>Functional Testing.</li>
</ol>

<p>My application architecture is as follows,</p>

<ul>
<li>controllers (which controls the respective action by calling service file from services directory).</li>
<li>models (model for data tables).</li>
<li>routes (for routing).</li>
<li>services (a layer that communicates with model).</li>
<li>db (holds migration for the database).</li>
<li>index.js (which runs the server).</li>
</ul>

<p>Could anyone help me out by saying which directories &amp; files needs which type of testing (Unit, Integration, Functional)?</p>

<p>Thank you. </p>
",https://stackoverflow.com/questions/62230188/unit-integration-and-functional-testing,"['node.js', 'testing', 'mocha.js', 'chai', 'sinon']",81,True,0,1
dispatchEvent syntax for selectItem($event) in angular unit testing,"<p>I am using <code>NgbTypeAhead</code> to show search results. According to the <a href=""https://ng-bootstrap.github.io/#/components/typeahead/api"" rel=""nofollow noreferrer"">Angular docs</a> I am using <code>selectedItem($event)</code> to get hold on selected value and calling my handler method to catch the event. </p>

<p>Everything works fine from UI. Now I'm having trouble unit testing the same.</p>

<p>Below is the code snippet for the same, I'm creating a fixture for my input tag and calling the <code>dispatchEvent</code> method with event name and the params it is expecting. But this is not working as expected, as the handler method is not getting the param <code>($event)</code>.</p>

<p><strong>html file</strong></p>

<pre class=""lang-html prettyprint-override""><code>&lt;div class=""input-group""&gt;
  &lt;input #teamInput teamInput.value='' type=""text"" class=""form-control"" name=""teamNameInput"" formControlName=""teamNameInput"" id=""teamNameInput"" placeholder=""Search Team Name"" i18n-placeholder=""@@TeamPlaceholder""
      [ngbTypeahead]=""teamFilter"" #teamTypeahead=""ngbTypeahead"" (selectItem)=""addTeam($event)""&gt;
 &lt;/div&gt;
</code></pre>

<p><strong>typescript file</strong></p>

<pre class=""lang-js prettyprint-override""><code>   /**
   * Adds an available team to the boardTeam class variable
   *
   * @param teamName the name of the team
   */
  addTeam(teamNameEvent: any) {
    teamNameEvent.preventDefault();
    console.log(""in addTeam:: "" + teamNameEvent.item);
    this.boardTeam = this.availableTeams.find(team =&gt; team.name === teamNameEvent.item);
    // hidden business logic
  }
</code></pre>

<p><strong>test file</strong></p>

<pre class=""lang-js prettyprint-override""><code>it(""has 2 rows in the table after calling add Team"", () =&gt; {
  const expectedTableRowLength = 2;
  const expectedHeaderRowLength = 1;
  const expectedLength = expectedHeaderRowLength + expectedTableRowLength;
  teamInput.dispatchEvent(new Event('selectItem'),{   //this particular event is not working.
     ""item"": ""testTeam"" - 
  fixtureUnderTest.detectChanges();
  const tableRows = fixtureUnderTest.nativeElement.querySelectorAll(""tr"");
      expect(tableRows.length).toBe(expectedLength);

});
</code></pre>
",https://stackoverflow.com/questions/60676181/dispatchevent-syntax-for-selectitemevent-in-angular-unit-testing,"['angular', 'jasmine', 'dispatchevent']",827,True,0,1
How to unit test a function that is calling other functions?,"<p>I am testing my REST API with jest for the first time and I am having a hard time unit testing the controllers.</p>
<p>How should I go about testing a function that contains other function calls (npm modules as well as other controllers). Here's pseudo code. (I've tried mocking but can't seem to get it right)</p>
<pre><code>async insertUser(uid, userObject){
// Function to check user role and permissions
const isAllowed = await someotherController.checkPermissions(uid);
//Hash password using an npm module
const pass = password.hash;
//const user = new User(userObj)
user.save();
}
</code></pre>
<p>So basically, how to test such a function that contains all these different functions.
I have written tests for simple function and they went all good but I am stuck at these functions.</p>
",https://stackoverflow.com/questions/63341640/how-to-unit-test-a-function-that-is-calling-other-functions,"['javascript', 'node.js', 'mocking', 'jestjs']",257,True,0,1
How to reference to the project in WPF app for unit testing,"<p>I am using Win10, VS Community 2019, latest .NET Core WPF app. I have a very simple WPF app. I would like to test it's ViewModel. I kept MVVM model and keep view and ViewModel separated. Now I would like to unit test the ViewModel. But I can't refer to my project's ViewModel. I have a simple code for as follows:-</p>

<pre><code>namespace Multiples.ViewModel
{
class MultiplesViewModel
{
    public MultiplesViewModel()
    {

    }

    public long GetMultiples(long input)
    {
        long total = 0;
        for (long i = 1; i &lt; input; ++i)
        {
            if (i % 3 == 0 || i % 5 == 0)
            {
                total += i;
            }
        };
        return total;
    }
  }
 }
</code></pre>

<p>Later I add a reference to the unit test project. As you can see in the following pic. 
I can't reference MultiplesViewModel. </p>

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

<p>So how do I add to MultiplesViewModel for the unit testing? </p>
",https://stackoverflow.com/questions/61439451/how-to-reference-to-the-project-in-wpf-app-for-unit-testing,"['c#', 'wpf', '.net-core', 'xunit']",307,True,-1,1
Define common mock objects for many test classes,"<p>I'm learning unit testing with Spring Boot. I've created a stub object from Spring Data repository class using Mockito. All works fine, here's a code:</p>

<pre><code>@SpringBootTest
class UserServiceTest {

@MockBean
private UserRepository userRepository;

@BeforeAll
public void  configureMock() {
    User user = new User(""mishenev"",
            ""Dmitrii"",
            ""Mishenev"",
            ""123"",
            ""mishenev.8@gmailcom"",
            new UserSettings());
    when(userRepository.findById(anyLong())).thenReturn(Optional.of(user));
    when(userRepository.findUserByUserName(anyString())).thenReturn(user);

 // .. Tests
}
</code></pre>

<p>But it's kind of boilerplate style to use this @BeforeAll test repository configuration for each class, if we don't need different stub behaviour. Then i tried to use <strong><em>@TestConfiguration</em></strong></p>

<pre><code>@TestConfiguration
 public class SpringRepositoryTestConfiguration {

@Bean
public UserRepository userRepository () {
    UserRepository userRepository = Mockito.mock(UserRepository.class);
    // Configuring mock's behaviour
    return userRepository;
    }
}
</code></pre>

<p>After that i used</p>

<pre><code>@SpringBootTest(classes = SpringRepositoryTestConfiguration.class)
</code></pre>

<p>But i can't using <code>@MockBean</code> to autowire repository in <code>UserService</code> now.
I want to understand is it possible to take out and use all test <code>Repository</code> type stubs in one configuration class. Thank you in advance!</p>
",https://stackoverflow.com/questions/62436256/define-common-mock-objects-for-many-test-classes,"['java', 'spring', 'unit-testing', 'mockito', 'spring-boot-test']",449,True,0,1
Firestore Security Rules: How should I test that a particular operation (e.g. get:) is completely disabled?,"<p>Is there any way to test that a security rule operation (e.g. <code>get:</code>, <code>delete:</code>) is completely disabled (ie. <code>false</code>)?</p>
<p>No matter how thorough my unit tests, technically I can't guarantee that a new security rule condition doesn't allow the operation.</p>
<p>For example, I'd like my unit test to ensure that the <code>delete</code> operation is completely disabled for a particular collection.</p>
<p>The test below correctly fails. However, how can I reliably guarantee with unit tests that there isn't an arbitrary security rule condition that would allow it?</p>
<pre class=""lang-js prettyprint-override""><code>import &quot;jest&quot;
import * as firebase from &quot;@firebase/rules-unit-testing&quot;

const baseOptions = {projectId: 'my-project'}

function admin() {
  return firebase.initializeAdminApp(baseOptions).firestore()
}

function client(uid: string) {
  const options = Object.assign({uid: uid}, baseOptions)
  return firebase.initializeTestApp(options).firestore()
}

describe(&quot;/theCollection&quot;, () =&gt; {

  const collection = &quot;theCollection&quot;;

  describe(&quot;delete:&quot;, () =&gt; {
    it(&quot;fails&quot;, async () =&gt; {
      // setup
      const uid = '123'
      const docId = 'abc'
      await admin().collection(collection).doc(docId).set({uid: uid})

      // test
      await firebase.assertFails(
        client(uid).collection(collection).doc(docId).delete(),
      )
      // ^--- this doesn't guarantee that deletes are disabled for everyone
    })
  })
})
</code></pre>
<h3>Testing Libraries:</h3>
<ul>
<li><a href=""https://firebase.google.com/docs/firestore/security/test-rules-emulator"" rel=""nofollow noreferrer"">security rules emulator</a></li>
<li><a href=""https://www.npmjs.com/package/@firebase/rules-unit-testing"" rel=""nofollow noreferrer"">@firebase/rules-unit-testing</a></li>
</ul>
",https://stackoverflow.com/questions/65118337/firestore-security-rules-how-should-i-test-that-a-particular-operation-e-g-ge,"['typescript', 'firebase', 'unit-testing', 'google-cloud-firestore', 'firebase-security']",384,True,0,2
Is there a way to add property to the mock object in Python unittest,"<p>I am trying to test the following code:</p>
<pre><code>class ABC:
    def _check_something(cls, doc, doc_type=pqr.Document):
        return isinstance(doc, doc_type) and &quot;xyz&quot; in doc
</code></pre>
<p>A document is a NoSQL object. I am verifying if it is of certain instance and it has &quot;xyz&quot; in its key.</p>
<p>This is what I have got in its test class</p>
<pre><code>class test_ABC(unittest.TestCase):
    def setUp(self):
        self.m_response = MagicMock()
        self.action.client = MagicMock()
        self.action.client.r_session.get.return_value = self.m_response

    def test_check_something(self):
        self.m_response.__class__ = pqr.Document       # Sets up the appropriate class for the mock up object.
        self.m_response.return_value[&quot;xyz&quot;] = &quot;test&quot;.  # Unable to add this key-value pair, hence test is failing on this point.
        self.assertTrue(self._check_something(self.m_response))
</code></pre>
<p>I am fairly new to the unit-testing. I tried couple of different ways mentioned in unittest documentation but nothing clicked yet. Is there a way I can add that property to the mock object which satisfies <code>&quot;xyz&quot; in doc</code> condition?</p>
<p>Please let me know if you need anything for the clarification.</p>
",https://stackoverflow.com/questions/62776200/is-there-a-way-to-add-property-to-the-mock-object-in-python-unittest,"['python-3.x', 'unit-testing']",26,False,0,0
Unit testing an external HTTP request in .NET,"<p>I have the following method:</p>
<pre><code>  private async Task&lt;Result&gt; TryGetResult (string request)
        {
            var httpClient = new HttpClient(); 
            var result = await httpClient.GetAsync(request);
            if (result.IsSuccess)
            {
                var body = await result.Content.ReadAsStringAsync();
                var deserializedResult = JsonConvert.DeserializeObject&lt;Result&gt;(body);
                return deserializedResult ;
            }

            if ( result.StatusCode == (HttpStatusCode)429 )
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
                return await TryGetResult(request);
            }
        }
</code></pre>
<p>This takes in this string request:
<code>var request =  $&quot;https://atlas.microsoft.com/search/address/json ... //(private keys omitted)</code></p>
<p>I want to unit test the method and stub out the request so that I don't make a real call. I have limited experience unit testing C# and am struggling to work out how to stub this? Please can anyone point me in the right direction?</p>
<p>I have tried looking at similar articles and googling but cannot find the stubbing of a string request like this and wonder if I'm going in the wrong direction with trying to test?</p>
",https://stackoverflow.com/questions/62880263/unit-testing-an-external-http-request-in-net,"['c#', '.net', 'nunit']",180,True,0,1
Unit testing DAO layer with Mockito,"<p>A try to test my DAO methods:</p>
<pre><code>@Repository
@ComponentScan(basePackages = {&quot;com.sebhaw.cms.entity&quot;})
public class AuthoritiesDAO extends CommonClass implements IDAO&lt;Authorities&gt;{

    public final Logger logger = LoggerFactory.getLogger(AuthoritiesDAO.class);
    
    public EntityManager entityManager;
    
    
    @Autowired
    public AuthoritiesDAO(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    private CommonClass commonClass;
    
    static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(&quot;HH:mm:ss&quot;);
    
    @Override
    public List&lt;Authorities&gt; getObjects() {
        
        Session currentSession = entityManager.unwrap(Session.class);
        Query&lt;Authorities&gt; theQuery = currentSession.createQuery(&quot;from Authorities&quot;,Authorities.class);
        List&lt;Authorities&gt; authorities = theQuery.getResultList();
        logger.warn(&quot;Query getAuthorities() on table Authorities in day: &quot;+dateTimeFormatter.format(LocalDateTime.now())+&quot; by: &quot;+getPrincipal().toString());
        return authorities;
    }
    
    @Override
    public void saveObjects(Authorities t) {
        
        Session currentSession = entityManager.unwrap(Session.class);
        t.setLastModifier(getPrincipal());
        logger.warn(&quot;Record saved on table Authorities in day: &quot;+dateTimeFormatter.format(LocalDateTime.now())+&quot;, data: &quot;+t.toString()+&quot; by: &quot;+getPrincipal().toString());
        currentSession.saveOrUpdate(t);
    }
    
    @Override
    public Authorities getObjects(int theId) {
        Session currentSession = entityManager.unwrap(Session.class);
        Authorities theAuthorities = currentSession.get(Authorities.class, theId);
        logger.warn(&quot;Query getAuthorities(int theId) on table Authorities in day: &quot;
        +dateTimeFormatter.format(LocalDateTime.now())+&quot;with ID: &quot;+theId+&quot; by: &quot;+getPrincipal().toString());
        return theAuthorities;
    }
    
    @Override
    public void deleteEntities(int theId) {
        
        Session currentSession = entityManager.unwrap(Session.class);
        Query theQuery = currentSession.createQuery(&quot;delete from Authorities where id=:authoritiesId&quot;);
        theQuery.setParameter(&quot;authoritiesId&quot;, theId);
        logger.warn(&quot;Record deleted in table Authorities on day: &quot;+dateTimeFormatter.format(LocalDateTime.now())+&quot;, with ID: &quot;+theId+&quot; by: &quot;+getPrincipal().toString());
        theQuery.executeUpdate();   
    }
}
</code></pre>
<p>And this is my unit test ( not working):</p>
<pre><code>public class AuthoritiesDAOTest {
    
    @Mock
    private Session session;
    
    private EntityManager entityManager;
    
    private CommonClass commonClass;
    
    private AuthoritiesDAO authoritiesDAO;
    
    @BeforeEach
    void init() {
        entityManager = Mockito.mock(EntityManager.class);
        Mockito.when(entityManager.unwrap(Session.class)).thenReturn(session);
        authoritiesDAO = new AuthoritiesDAO(entityManager);
    }
    
    @Test
    void shouldReturnEmptyCollection() {
        Query query = Mockito.mock(Query.class);
        Mockito.when(session.createQuery(ArgumentMatchers.anyString(),ArgumentMatchers.any())).thenReturn(query);
        Mockito.when(query.getResultList()).thenReturn(new ArrayList&lt;Authorities&gt;());
        
        List&lt;Authorities&gt; result = authoritiesDAO.getObjects();
        assertTrue(true);
    }

}
</code></pre>
<p>I am asking for an example of valid unit testing of my dao layer as I am in a dead end.
&quot;Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...&quot;
&quot;Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...&quot;
&quot;Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...&quot;
&quot;Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...&quot;</p>
",https://stackoverflow.com/questions/65128353/unit-testing-dao-layer-with-mockito,"['java', 'spring', 'unit-testing', 'mockito', 'dao']",845,False,-2,1
What does a sealed class do and explanation of the class below,"<p>I have been doing android development for a while but I always looking forward to learning new things.</p>

<p>I came across the code below on codelab for viewmodel unit testing. I really like the code base is arranged but do not understand some codes like the one below.</p>

<p>I will like some guidance on creating a class that has a type of map as below.</p>

<p>Basically I will like to know how Result&lt;*> still relate to Result and why the class is just called/implemented as Success(it).</p>

<p>I will appreciate a kind guidance.</p>

<pre><code>sealed class Result&lt;out R&gt; {


    data class Success&lt;out T&gt;(val data: T) : Result&lt;T&gt;()
    data class Error(val exception: Exception) : Result&lt;Nothing&gt;()
    object Loading : Result&lt;Nothing&gt;()

    override fun toString(): String {
        return when (this) {
            is Success&lt;*&gt; -&gt; ""Success[data=$data]""
            is Error -&gt; ""Error[exception=$exception]""
            Loading -&gt; ""Loading""
        }
    }
}

/**
 * `true` if [Result] is of type [Success] &amp; holds non-null [Success.data].
 */
val Result&lt;*&gt;.succeeded
    get() = this is Success &amp;&amp; data != null

//implementation
 override fun observeTask(taskId: String): LiveData&lt;Result&lt;Task&gt;&gt; {
        return tasksDao.observeTaskById(taskId).map {
            Success(it)
        }
    }
</code></pre>
",https://stackoverflow.com/questions/60241610/what-does-a-sealed-class-do-and-explanation-of-the-class-below,"['android', 'kotlin', 'android-testing', 'google-codelab']",153,True,0,1
Getting a null pointer when testing a controller using MockMvc,"<p>I am getting a null pointer when unit testing a controller. The null pointer is occurring in the controller when calling a mocked service to get an id. I tried many things but I am still getting the same error.</p>

<p>Below is a snippet from the controller code where the null pointer is occurring:</p>

<pre><code>@RestController
@RequestMapping(ELEMENTS_BASE_URI)
@EnableCommonRestHeaders
public class ElementController {
    @Autowired
    private ElementService elementService;
...
public ResponseEntity&lt;ElementDto&gt; createElement(
            @Valid @RequestBody ElementDto elementDto) {

        ElementDto saved = elementService.createElement(elementDto);

        HttpHeaders headers = new HttpHeaders();

        URI location = UriBuilder.builder(ELEMENT_LINK_URI)
                .pathVariable(ELEMENT_ID, saved.getId())
                .create();
        headers.setLocation(location);

        return new ResponseEntity&lt;&gt;(saved, headers, HttpStatus.CREATED);
    }
...

}
</code></pre>

<p>In the controller code above, The null pointer occurs at the line below:
saved is null</p>

<pre><code>   ElementDto saved = elementService.createElement(elementDto);
</code></pre>

<p>The test code is as below:</p>

<pre><code>import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonObject;
import static com.sas.fcs.networkbuild.util.matchers.JSONContentResultMatcher.jsonPath;

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = ElementController.class, excludeAutoConfiguration = MockMvcSecurityAutoConfiguration.class)
@ActiveProfiles(value = {""test"", ""hsql"", ""disable-oauth2""})
@TestPropertySource(""classpath:/test.properties"")
public class ElementControllerTest {


    @MockBean
    private ElementService elementService;

    @Autowired
    ElementController elementController;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper mapper;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders
                .standaloneSetup(elementController)
                .build();
    }

    @Test
    public void testCreateElementSuccess() throws Exception {
        ElementDto element = new ElementDto();
        element.setName(""firstname"");
        element.setModifiedTimeStamp(new Date());

        ElementDto createdElement = new ElementDto();
        String elementId = ""123"";
        createdElement.setId(elementId);
        createdElement.setName(""firstname"");
        createdElement.setLabel(""firstname"");
        createdElement.setAttribute(true);
        createdElement.setKeep(true);


        when(elementService.create(element)).thenReturn(createdElement);

        // make sure returns location with new element id
        mockMvc.perform(
                post(ServiceConstants.ELEMENTS_BASE_URI)
                     .content(mapper.writeValueAsBytes(element))
                     .accept(ElementDto.MEDIA_TYPE_JSON_VALUE)
                     .contentType(ElementDto.MEDIA_TYPE_JSON_VALUE))
                     .andExpect(status().isCreated())
                     .andExpect(header().string(""Location"",
                        Matchers.endsWith(ServiceConstants.SERVICE_URI + ServiceConstants.ELEMENTS_BASE_URI + ""/"" + elementId)))
                     .andExpect(header().string(""Last-Modified"", not(isEmptyString())))
                     .andExpect(jsonObject().is(createdElement))
                     .andExpect(jsonPath(""name"").value(element.getName()))
                     .andReturn();
    }
}
</code></pre>

<p>The line:</p>

<pre><code>when(elementService.create(element)).thenReturn(createdElement);
</code></pre>

<p>does not seem to have any effect. Any help on this is really appreciated.</p>

<p>Regards,
Firas</p>
",https://stackoverflow.com/questions/60304553/getting-a-null-pointer-when-testing-a-controller-using-mockmvc,"['spring-boot', 'spring-mvc', 'mockito']",376,False,0,1
How to test a subject and observable return value in Angular Jasmine Spec?,"<p>In Angular 9, I have a loader service like below.</p>
<pre><code>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

export interface LoaderState {
  show: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class LoaderService {

  private loaderSubject = new Subject&lt;LoaderState&gt;();

  loaderState = this.loaderSubject.asObservable();

  constructor() { }

  show() {
      this.loaderSubject.next({show: true} as LoaderState);
  }

  hide() {
      this.loaderSubject.next({show: false} as LoaderState);
  }
}
</code></pre>
<p>I want to test the <code>show()</code> and <code>hide()</code> methods. For that, I have written a spec like below.</p>
<pre><code>it('should show', (done) =&gt; {
      spyOn(loaderService, 'show').and.callThrough();
      loaderService.show();
      expect(loaderService.show).toHaveBeenCalled();
      loaderService.loaderState.subscribe((state) =&gt; {
          expect(state).toBe({show: true});
          done();
      });
  });
</code></pre>
<p>But I get below error when I run this</p>
<blockquote>
<p>Chrome 86.0.4240 (Windows 10.0.0) LoaderService should show FAILED
Error: Timeout - Async callback was not invoked within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)</p>
</blockquote>
<p>I have searched a lot before asking this question. But can not seem to find the right solution. I am new to Jasmin Unit testing. Any help is appreciated.</p>
<p>Edit: Posting complete spec file for reference.</p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { LoaderComponent } from './loader.component';
import { LoaderService } from './loader.service';

describe('LoaderService', () =&gt; {
  let component: LoaderComponent;
  let fixture: ComponentFixture&lt;LoaderComponent&gt;;
  let loaderService: LoaderService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ LoaderComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LoaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    loaderService = TestBed.inject(LoaderService);
  });

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

  it('should show', (done) =&gt; {
      spyOn(loaderService, 'show').and.callThrough();
      loaderService.show();
      expect(loaderService.show).toHaveBeenCalled();
      loaderService.loaderState.subscribe((state) =&gt; {
          expect(state).toBe({show: true});
          done();
      });
  });
});
</code></pre>
",https://stackoverflow.com/questions/64816989/how-to-test-a-subject-and-observable-return-value-in-angular-jasmine-spec,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",3941,True,0,2
How to test single it() method from a specific spec.ts file,"<p>I'm new to angular Unit testing using jasmine. Wondering if we can test a single it() method from a specific spec.ts file that consists of only one describe.</p>
<p>In order to test a single test case scenario every time I have to run <strong>ng test</strong> and wait for it to complete.</p>
<p>I researched a lot but no luck. I know we can change the karma configuration to a specific spec file and run but then curious to know if there is a way we can do like mentioned above.</p>
",https://stackoverflow.com/questions/65397220/how-to-test-single-it-method-from-a-specific-spec-ts-file,"['angular', 'jasmine', 'karma-jasmine']",196,True,0,2
setUpTestData integrity error; database does not refresh,"<p>I am new to Django unit testing and trying to understand how to instantiate fixtures for a class, that are then removed from the database once the tests in the class are finished.</p>
<p>My understanding is its best to use <a href=""https://docs.djangoproject.com/en/3.0/topics/testing/tools/#django.test.TestCase.setUpTestData"" rel=""nofollow noreferrer"">setUpTestData</a> for this. However, when set up the same fixtures in two different classes, I get a <code>django.db.utils.IntegrityError: duplicate key value violates unique constraint</code> error:</p>
<pre><code>class TestClass1(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.i1 = Issuer.objects.create(issuer_name='Issuer 1')
        cls.i2 = Issuer.objects.create(issuer_name='Issuer 2')
        cls.i3 = Issuer.objects.create(issuer_name='Issuer 3')

    def test_1A(self):
       // etc

class TestClass2(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.i1 = Issuer.objects.create(issuer_name='Issuer 1')
        cls.i2 = Issuer.objects.create(issuer_name='Issuer 2')
        cls.i3 = Issuer.objects.create(issuer_name='Issuer 3')

    def test_2A(self):
       // etc
</code></pre>
<p>Produces:</p>
<blockquote>
<p>django.db.utils.IntegrityError: duplicate key value violates unique constraint &quot;myapp_issuer_pkey&quot;
DETAIL:  Key (id)=(6) already exists.</p>
</blockquote>
<p>Why doesn't the database &quot;reset&quot; after each TestCase class is complete? Where am I going wrong?</p>
",https://stackoverflow.com/questions/62686448/setuptestdata-integrity-error-database-does-not-refresh,"['python', 'django']",182,True,0,1
"enzyme unit test, how to test component without exporting sub-components?","<p><a href=""https://enzymejs.github.io/enzyme/docs/api/mount.html"" rel=""nofollow noreferrer"">https://enzymejs.github.io/enzyme/docs/api/mount.html</a>
<a href=""https://medium.com/@samuelhutama/unit-testing-react-component-with-jest-and-enzyme-without-snapshot-test-5b26b8146abf"" rel=""nofollow noreferrer"">https://medium.com/@samuelhutama/unit-testing-react-component-with-jest-and-enzyme-without-snapshot-test-5b26b8146abf</a></p>

<p>See my main code, i don't want to export sub-components.</p>

<pre><code>import React from 'react';
import PropTypes from 'prop-types';

// eslint-disable-next-line react/prop-types
const DemoMessageBody = ({ inner }) =&gt; (
  // eslint-disable-next-line react/no-danger
  &lt;div dangerouslySetInnerHTML={{ __html: inner }} /&gt;
);

const DemoMessage = ({
  // eslint-disable-next-line react/prop-types
  msgTitle, msgBody,
}) =&gt; (
  &lt;div&gt;
    &lt;p&gt;
      &lt;strong&gt;{msgTitle}&lt;/strong&gt;
    &lt;/p&gt;
    &lt;DemoMessageBody inner={msgBody} /&gt;
  &lt;/div&gt;
);

/**
 * Dispatch to the corresponding alert message box based on message type
 * @param {Object} alert message details including title, type and message body
 */
const Demo = ({ msgTitle, msgBody }) =&gt; {
  return DemoMessage({ msgTitle, msgBody });
};

Demo.propTypes = {
  /**
   * Message box title
   */
  msgTitle: PropTypes.string,
  /**
   * Message type, this can be a html element or plain string
   */
  msgBody: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.element,
  ]),
};

Demo.defaultProps = {
  msgTitle: 'Sth is wrong',
  msgBody: 'Please contact your admin',
};

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

<p>The test is like this</p>

<pre><code>import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Demo from '../Demo';

describe('DisplayMessageFromHtmlElement', () =&gt; {
  let prefix;
  let postfix;
  let testTitle;

  beforeEach(() =&gt; {
    prefix = 'Your request cannot be processed';
    postfix = 'Contact the admin.';
    testTitle = 'Test Title';
  });

  test('should show info message', () =&gt; {
    const msg1 = 'Info msg 1';
    const msg2 = 'Info msg 2';
    const inputMsg = (
      &lt;div&gt;
        &lt;p&gt;{prefix}&lt;/p&gt;
        &lt;ol&gt;
          &lt;li&gt;{msg1}&lt;/li&gt;
          &lt;li&gt;{msg2}&lt;/li&gt;
        &lt;/ol&gt;
        &lt;p&gt;{postfix}&lt;/p&gt;
      &lt;/div&gt;
    );

    const wrapper = mount(&lt;Demo msgTitle={testTitle} msgBody={inputMsg} /&gt;);
    expect(wrapper).toMatchSnapshot();
  });
});
</code></pre>

<p>Now when i run the test, the snapshot doesn't expend to resolve the final html (which works in manual test), it still displays ""DemoMessageBody"", ""dangerouslySetInnerHTML"".</p>

<p>My guess is if i export the sub-components (to their own files), this can work. But i do not want to export them.</p>

<p>Any suggestions ?</p>
",https://stackoverflow.com/questions/60516865/enzyme-unit-test-how-to-test-component-without-exporting-sub-components,"['reactjs', 'enzyme']",206,False,0,0
How to write a unit test an Express controller using Jest?,"<p>Thank you for taking the time to read my question. </p>

<p>I am pretty new to Jest and unit testing for that matter, so before I begin writing unit tests for my controller functions, I wanted to check my understanding. So high level, I understand that the unit test is to test whether the controller function behaves as expected when called.</p>

<p>How would I go about writing a Jest unit test for the following code? I would really appreciate an example so that I can reference it as I write the jest tests for the other controllers. Thank you.</p>

<pre><code>//retrieveMember.js


const debug = require('debug')('get_member');
const MemberService = require('../services/MemberService');
const generateError = require('../lib/generateError');


const retrieveMember = async (req, res, next) =&gt; {
  try {
    if (req.params.id === """"
    || req.params.id === undefined) {
      throw generateError(400, ""invalid."");
    }

    const regex = RegExp(""[^a-zA-Z0-9\-]"");
    if (regex.test(req.params.id)) {
      throw generateError(400, ""invalid format."");
    }

    const memberId = req.params.id;
    const memberRecord = await MemberService.retrieveOneMember(memberId);

    const member_detail = {
      id: memberRecord.id,
      username: memberRecord.username,
    };

    res.status(200).send({member_detail: member_detail});
  } catch (e) {
    if (e) {
      debug('could not get member');
      return next(e);
    }
  }
};


module.exports = retrieveMember;
</code></pre>
",https://stackoverflow.com/questions/61834610/how-to-write-a-unit-test-an-express-controller-using-jest,"['node.js', 'unit-testing', 'express', 'jestjs']",11569,True,5,1
Unit testing express.js routes,"<p>I am new to express and very new to unit testing. Consider the following code:</p>

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

var bookingsController = require (""../controllers/bookings"");

router
   .route('/')
   .get(bookingsController.bookings_get)
   .post(bookingsController.bookings_post)


router
   .route('/:id')
   .get(bookingsController.bookings_get_id)
   .put(bookingsController.bookings_put_id)
   .delete(bookingsController.bookings_delete_id)

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

<p>What is the right/recommended way of writing unit tests for this? I would like to be able to test, for example, that <code>router.route('/:id')</code> does not accept POST calls.</p>

<p>I know I can do this with supertest, but I believe that would be considered an integration test as supertest would start the app the run the test.</p>

<p>I've read and tried multiple node.js/express.js testing tutorials but couldn't find an answer to this. Any pointers to existing tutorials most welcome. Direct answers here, even more :)</p>
",https://stackoverflow.com/questions/61529619/unit-testing-express-js-routes,"['javascript', 'node.js', 'unit-testing', 'express']",2703,True,5,1
How to exclude spec files while getting code coverage [Angular],"<p>I'm trying to get the code coverage of my angular project. I'm not very well versed with the tools. I decided to use <code>""istanbul-instrumenter-loader"": ""^3.0.1""</code>. I tried taking help from this question:</p>

<ol>
<li><a href=""https://stackoverflow.com/questions/42241654/angular-cli-exclude-files-directory-for-ng-test-code-coverage"">angular cli exclude files/directory for <code>ng test--code-coverage</code></a> and</li>
<li><a href=""https://stackoverflow.com/questions/38473025/regex-that-doesnt-match-spec-ts-and-spec-tsx-but-should-match-any-other-ts-and"">Regex that doesn't match spec.ts and spec.tsx but should match any other .ts and .tsx</a></li>
</ol>

<p>And many other solutions given on the same thread. My problem is that I want to exclude spec files which I wrote for unit testing. Here is the screenshot of what I'm getting:
<a href=""https://i.stack.imgur.com/5FXWj.png"" rel=""noreferrer"">screenshot</a>.
Please correct my mistake and feel free to ask for missing information.</p>
",https://stackoverflow.com/questions/61474540/how-to-exclude-spec-files-while-getting-code-coverage-angular,"['angular', 'karma-jasmine', 'code-coverage', 'istanbul', 'angular-test']",7294,True,5,1
Not able to use .ts files with Jasmine and Karma. Getting error &#39;Unable to determine file type..&#39;,"<p>I really need some help to configure karma.conf.js to handle typescript files or not sure what is missing or what I am doing wrong here. Pretty new to unit-testing and learned the Jasmine framework (in the examples it uses *.js and *.spec.js files) but in my ionic-angular project its *.ts files and getting errors (shown below). I have been trying to figure it out for 2 days and not able to get this solved. Any help really appreciated.</p>

<p>[Using ionic 3 (ionic-angular 3.9.+) framework with Angular 6 (6.1.10) and typescript (3.8.+.)]</p>

<p>my tsconfig.json ></p>

<pre><code> {
  ""compilerOptions"": {
    ""allowSyntheticDefaultImports"": true,
    ""declaration"": false,
    ""emitDecoratorMetadata"": true,
    ""experimentalDecorators"": true,
    ""lib"": [
      ""dom"",
      ""es2015""
    ],
    ""module"": ""es2015"",
    ""moduleResolution"": ""node"",
    ""sourceMap"": true,
    ""target"": ""es6""
  },
  ""include"": [
    ""src/**/*.ts""
  ],
  ""exclude"": [
    ""node_modules"",
    ""src/**/*.spec.ts"",
    ""src/**/__tests__/*.ts""
  ],
  ""compileOnSave"": false,
  ""atom"": {
    ""rewriteTsconfig"": false
  }
} 
</code></pre>

<p>my karma.conf.js ></p>

<pre><code>module.exports = function (config) {
  config.set({
    frameworks: ['jasmine', 'jasmine-matchers'],
    files: [
      'src/**/*.ts',
      'src/**/*.spec.ts'
    ],
    plugins: [
      'karma-jasmine',
      'karma-jasmine-matchers',
      'karma-chrome-launcher'
    ],
    reporters: ['dots'],
    colors: true,
    browsers: ['ChromeHeadless'],
    singleRun: true
  })
};
</code></pre>

<p>my package.json devDependencies:</p>

<pre><code>""devDependencies"": {
    ""@ionic/app-scripts"": ""3.2.4"",
    ""jasmine-core"": ""^3.5.0"",
    ""karma"": ""^5.1.0"",
    ""karma-chrome-launcher"": ""^3.1.0"",
    ""karma-jasmine"": ""^3.3.1"",
    ""karma-jasmine-matchers"": ""^4.0.2"",
    ""puppeteer"": ""^1.20.0"",
    ""ts-node"": ""^8.10.2"",
    ""typescript"": ""^3.8.3""
  },
</code></pre>

<p>ERROR I am getting:</p>

<pre><code>15 06 2020 09:40:23.844:WARN [middleware:karma]: Unable to determine file type from the file extension, defaulting to js.
  To silence the warning specify a valid type for C:/Users/USR01/Documents/testing/src/providers/member/member.ts in the configuration file.
  See http://karma-runner.github.io/latest/config/files.html
........
........
15 06 2020 09:40:23.844:WARN [middleware:karma]: Unable to determine file type from the file extension, defaulting to js.
  To silence the warning specify a valid type for C:/Users/USR01/Documents/testing/src/providers/scores/scores.ts in the configuration file.
Chrome 83.0.4103.97 (Windows 10): Executed 0 of 0 SUCCESS (0.001 secs / 0 secs)
npm ERR! Test failed.  See above for more details.
</code></pre>
",https://stackoverflow.com/questions/62394424/not-able-to-use-ts-files-with-jasmine-and-karma-getting-error-unable-to-deter,"['angular', 'typescript', 'unit-testing', 'ionic3', 'karma-jasmine']",4115,True,10,1
How to test angular components in protractor?,"<p>I know that it's recommended to use karma/jasmine for component/unit testing but I want to do the same using protractor because of two reasons:</p>
<ul>
<li>it's not possible to emulate 'Tab' behaviour in javascript to move to the next focusable element (<a href=""https://stackoverflow.com/questions/40454754/is-there-a-way-to-programmatically-trigger-the-tab-key-to-move-the-focus-to-the"">Is there a way to programmatically trigger the TAB key to move the focus to the next focusable element?</a>). I need to be able to test 'Tab', 'Esc', key combinations and  with protractor it's as simple as calling <code>sendKey</code>.</li>
<li>karma/jasmine don't render css. You need to use <code>setStyleFixtures</code> which is a pain. The absence of css causes issues: for instance, jasmine/karma renders elements with 'display: none' and messes up the market (I'm not sure about this part but this is what happens when I create dx-data-grid).</li>
</ul>
<p>I know that protractor is meant to be used to do e2e testing but because of those two key benefits, I wonder if there is an easy way to use a protractor to do unit testing/integration testing.</p>
<p>An ideal solution for me would be to write a regular jasmine test with TestBed(to mock dependencies using angular's DI) and test it using protractor API without creating angular routes and special pages.</p>
<p>Heads-up, I've used jasmine for a couple of months, I'm not very familiar with protractor.</p>
",https://stackoverflow.com/questions/64867147/how-to-test-angular-components-in-protractor,"['angular', 'unit-testing', 'protractor', 'karma-jasmine']",174,False,0,0
Unit test for classes with complex __init__,"<p>I have a class that has several methods and I would like to write unit tests for them. The problem I'm facing is that this class has an <code>__init__</code> method that queries a database, imagine something like this:</p>
<pre class=""lang-py prettyprint-override""><code>class MyClass:

    accepted_values = ['a', 'b', 'c']
    
    def __init__(self, database_name):
        self.database = database_name
        self.data = self.query_database()

    def query_database(self):
        data = query_this_database(self.database)
        # clean data
        return data

    def check_values_in_db(self, column_name):
        column = data.column_name
        
        if any(item not in self.accepted_values for item in column):
            print('Oh noes!')
        else:
            print('All good')
    
</code></pre>
<p>Now, given this, I would like to unit test the last method using some mock data, but I can't because if I initialize the class, it will want to query the database. This is further complicated by the fact that to actually make the query, one needs an API key, permissions, etc., which is exactly what I want to avoid during unit testing.</p>
<p>I'm relatively new to OOP and unit testing in general, so I'm not even sure if I structured my class properly: maybe the method <code>query_database()</code> should only be called at a later stage and not in <code>__init__</code>?</p>
<p><strong>EDIT:</strong></p>
<p>Asked to add some details so here goes:</p>
<p>This class belongs to an AWS lambda function that runs on a schedule. Every hour, this class queries the DB for the last hour, and checks a specific column against some pre-defined values.</p>
<p>If any value in the column does not belong to those pre-defined values, it sends an alert email. I would like to test this specific functionality, but without having to query the database, but just using mock values.</p>
<p>I edited the code accordingly to reflect what I mean.</p>
",https://stackoverflow.com/questions/63156934/unit-test-for-classes-with-complex-init,"['python', 'unit-testing']",809,True,0,2
How to stub Vue component methods for unit testing,"<p>How can I stub certain methods (getters, in particular) from Vue single file components for unit testing with mocha/expect?</p>

<p>The problem I was facing was the following: 
I have a component with a get method <em>someData</em></p>

<pre><code>&lt;script lang=""ts""&gt;
import { Vue, Component } from 'vue-property-decorator'
import SomeService from '@/services/some.service'

@Component()
export default class MyApp extends Vue {
    ...

    mounted () {
      ...
    }

    get someData () {
      return this.$route.path.split('/')[1] || 'main'
    }

    get getLocation () {
      return this.someService.getBaseURL()
    }

    initSomeStringProperty (): string {
      return 'some string'
    }
}
&lt;/script&gt;
</code></pre>

<p>My tests always fail with: </p>

<blockquote>
  <p>[Vue warn]: Error in render: ""TypeError: Cannot read property 'path' of undefined""</p>
</blockquote>

<p>When I try to stub the method using sinon, like following:</p>

<pre><code>describe('MyApp.vue', () =&gt; {
  if('returns main', () =&gt; {
    const dataStub = sinon.stub(MyApp, 'someData')
    listStub.yields(undefined, 'main')
    const wrapper = shallowMount(AppNavBar)
    expect(wrapper.text()).to.include('Some Content')
  })
})
</code></pre>

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

<blockquote>
  <p>TypeError: Cannot stub non-existent own property someData</p>
</blockquote>

<p>In addition, I get the same error for every other method, I want to stub analogously, e.g., initSomeStringProperty().</p>
",https://stackoverflow.com/questions/60150559/how-to-stub-vue-component-methods-for-unit-testing,"['unit-testing', 'vue.js', 'mocha.js', 'sinon']",3515,True,4,2
Python unit testing multiple inputs,"<p>This is a generic question geared towards unit testing specifically in Python. Is it acceptable to place 20 or some number of inputs to test in a dictionary as keys, where the values are the expected result output from the function?</p>

<p>I can't find an answer after scouring the internet. Almost everything I read were toy examples like adding numbers to obtain a sum or concatenating a first and last name. The following is another toyish example to describe my question in a simple way.</p>

<pre><code>import unittest
import some_module

class SomeModuleUnitTest(unittest.TestCase):

    def test_some_function(self):

        input_output_dict = {
            1: 1,
            2: 4,
            3: 9,
            4: 16,
            5: 25,
            6: 36,
            7: 49,
              .
              .
              .

            20: 400
        }

        for input_case, output_expected in input_output_dict.items():
            output_actual = some_module.some_function(input_case)
            self.assertEqual(output_expected, output_actual)
</code></pre>

<p>If this is considered archaic, what would be the Pythonic solution for testing multiple inputs?</p>
",https://stackoverflow.com/questions/61419269/python-unit-testing-multiple-inputs,"['python', 'unit-testing', 'python-unittest', 'multiple-input']",5939,True,4,1
How to pass an array of Integers from Cucumber features file to step definition while writing unit test cases,"<p>I am learning Cucumber for unit testing and was trying to write unit tests for the Radix Sort code. But I am unable to figure out how to provide array of integers as an input to radix sort code from feature file.</p>

<p>I tried providing below input:</p>

<pre><code>  Scenario: Sorting integer array using radix sort within the specified range
    Given The nonnull integer array 10,25,0,1
    When radix sort is performed over the range from 0 to 7
    Then validate if the array is sorted

</code></pre>

<p>For the above scenario cucumber expects below-mentioned code body:</p>

<pre><code>@Given(""The nonnull integer array {double}"")
public void the_nonnull_integer_array(Double double1) {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java.PendingException();
}
</code></pre>

<p>If I try giving input as </p>

<pre><code>    Scenario: Sorting integer array using radix sort within the specified range
    Given The nonnull integer array [10,25,0,1]
    When radix sort is performed over the range from 0 to 7
    Then validate if the array is sorted
</code></pre>

<p>then cucumber expects below-mentioned code body:</p>

<pre><code>@Given(""The nonnull integer array [{double}]"")
public void the_nonnull_integer_array(Double double1) {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java.PendingException();
}

</code></pre>

<p>I also tried providing array within quotes</p>

<pre><code>  Scenario: Sorting integer array using radix sort within the specified range
    Given The nonnull integer array ""[10,25,0,1]""
    When radix sort is performed over the range from 0 to 7
    Then validate if the array is sorted

</code></pre>

<p>But then cucumber expects String as an input</p>

<pre><code>@Given(""The nonnull integer array {string}"")
public void the_nonnull_integer_array(String string) {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java.PendingException();
}
</code></pre>

<p>I tried various other ways without any success. Can anyone suggest any better approach on handling such testing scenario?</p>
",https://stackoverflow.com/questions/61976709/how-to-pass-an-array-of-integers-from-cucumber-features-file-to-step-definition,"['unit-testing', 'junit', 'cucumber', 'cucumber-java', 'cucumber-junit']",11341,True,9,1
"how to write a test function for a function in python, WITHOUT class","<p>I want to test a function to see if it's working properly.</p>
<p>I found many answers such as <a href=""https://stackoverflow.com/questions/46713912/how-to-write-a-unit-testing-function-for-my-function"">how to write a unit testing function for my function?</a> &amp; <a href=""https://docs.python.org/zh-cn/3/library/unittest.html"" rel=""nofollow noreferrer"">unittest</a></p>
<p>But they all write the test functions under a certain class, while mine function isn't a member a any class.</p>
<p>for example I have this under readTool.py:</p>
<pre><code>def extract_frame_dr(dr, frameID):
    return dr[0, frameID], dr[1, frameID]
</code></pre>
<p>How do I write a test_extract_frame_dr for it?
I want to have the feature of <a href=""https://docs.pytest.org/en/stable/"" rel=""nofollow noreferrer"">Auto-discovery of test modules and functions</a>:
Run all the tests in readTool.py at once without calling them one by one in the main function.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/62978041/how-to-write-a-test-function-for-a-function-in-python-without-class,"['python', 'unit-testing', 'testing', 'automated-tests']",2812,True,3,1
Cannot find module &#39;module-name&#39; while running ts-mocha,"<p>When I run <code>npm test</code> which runs <code>ts-mocha -p ./tsconfig.json tests/**/*.ts</code>, I get the following error.</p>
<pre><code>Error: Cannot find module 'random-name'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.&lt;anonymous&gt; (code-location\src\utility.ts:5:1)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Module.m._compile (code-location\node_modules\ts-mocha\node_modules\ts-node\src\index.ts:439:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Object.require.extensions.(anonymous function) [as .ts] (code-location\node_modules\ts-mocha\node_modules\ts-node\src\index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.&lt;anonymous&gt; (code-location\src\give-me-an-avatar.ts:2:1)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Module.m._compile (code-location\node_modules\ts-mocha\node_modules\ts-node\src\index.ts:439:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Object.require.extensions.(anonymous function) [as .ts] (code-location\node_modules\ts-mocha\node_modules\ts-node\src\index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.&lt;anonymous&gt; (code-location\tests\give-me-an-avatar.test.ts:1:1)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Module.m._compile (code-location\node_modules\ts-mocha\node_modules\ts-node\src\index.ts:439:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Object.require.extensions.(anonymous function) [as .ts] (code-location\node_modules\ts-mocha\node_modules\ts-node\src\index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.exports.requireOrImport (code-location\node_modules\mocha\lib\esm-utils.js:20:12)
    at Object.exports.loadFilesAsync (code-location\node_modules\mocha\lib\esm-utils.js:33:34)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
npm ERR! Test failed.  See above for more details.
</code></pre>
<p>I'm unit testing a file called <code>utility.test.ts</code> which uses <code>import { Utility } from &quot;../src/utility&quot;;</code>  This <code>Utility.ts</code> file imports a node module <code>import * as RandomNameGenerator from &quot;random-name&quot;;</code>. This module does exist in the <code>node_modules</code> folder inside the <code>@types</code> folder.</p>
<p>Note: I'm not testing the random-name functionality. I'm testing other util methods in the Utility file.</p>
<p>tsconfig.json looks like this</p>
<pre><code>{
    &quot;compilerOptions&quot;: { 
      &quot;target&quot;: &quot;es6&quot;, 
      &quot;module&quot;: &quot;commonjs&quot;, 
      &quot;strict&quot;: true, 
      &quot;declaration&quot;: true,
      &quot;outDir&quot;: &quot;./lib&quot;
    },  
    &quot;exclude&quot;: [
        &quot;tests&quot;,
        &quot;lib&quot;,
        &quot;node_modules&quot;
    ]
  }
</code></pre>
<p>I tried adding <code>&quot;moduleResolution&quot;: &quot;node&quot;</code> to the config above but that didn't work.</p>
<p>Dependency section in package.json file.</p>
<pre><code>&quot;devDependencies&quot;: {
    &quot;@types/chai&quot;: &quot;^4.2.14&quot;,
    &quot;@types/mocha&quot;: &quot;^8.2.0&quot;,
    &quot;@types/random-name&quot;: &quot;^0.1.0&quot;,
    &quot;chai&quot;: &quot;^4.2.0&quot;,
    &quot;mocha&quot;: &quot;^8.2.1&quot;,
    &quot;mocha-junit-reporter&quot;: &quot;^1.22.0&quot;,
    &quot;nyc&quot;: &quot;^14.1.1&quot;,
    &quot;ts-mocha&quot;: &quot;^8.0.0&quot;,
    &quot;ts-node&quot;: &quot;^9.1.1&quot;,
    &quot;typescript&quot;: &quot;^4.1.3&quot;
  }
</code></pre>
<p>I tried moving <code>&quot;@types/random-name&quot;: &quot;^0.1.0&quot;,</code> to the <code>dependencies</code> instead of <code>devDependencies</code> section but that doesn't work either.</p>
<p>Any idea why it's not able to load the dependencies? What am I missing?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/65270867/cannot-find-module-module-name-while-running-ts-mocha,"['typescript', 'unit-testing', 'npm', 'types', 'mocha.js']",608,False,3,0
Test a react component using test and react-testing-library,"<p>I just joined a team where we use react, redux, recompose to construct components to build UI. There aren't any unit tests in the application and there isn't consistent architecture for the application. I decided to take it upon myself to add unit tests using jest and react-testing-library. I succeed with few snapshot tests but I am struggling with unit testing. I am still learning react and pretty new to redux. I would love some suggestion. I am going to share a component which renders a table with column and row. I would love a feedback.</p>

<pre><code>import React, { useEffect, useState } from 'react';
import { compose } from 'recompose';
import { connect } from 'react-redux';

import { clearAll, fetchContacts } from '~/store/resources/contacts/actions';
import { isDevEnv } from '~/utils';

import Sidebar from './Sidebar';
import Table from './Table';
import Toolbar from './Toolbar';

const Contacts = ({ clearAll, fetchContacts, ...props }) =&gt; {
  const [searchValue, setSearchValue] = useState('');
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [canonicalFormValues, setCanonicalFormValues] = useState({ active: true });

  useEffect(() =&gt; {
    fetchContacts();
    return () =&gt; {
      clearAll();
    };
  }, []);

  const closeSidebar = () =&gt; {
    if (isDevEnv) {
      console.log('hit close function');
    }
    setIsSidebarOpen(false);
  };

  return (
    &lt;div&gt;
      &lt;Toolbar
        searchValue={searchValue}
        setSearchValue={setSearchValue}
        setIsSidebarOpen={setIsSidebarOpen}
      /&gt;
      &lt;Table setCanonicalFormValues={setCanonicalFormValues} /&gt;
      &lt;Sidebar
        isSidebarOpen={isSidebarOpen}
        closeSidebar={closeSidebar}
        canonicalFormValues={canonicalFormValues}
      /&gt;
      {isDevEnv &amp;&amp; (
        &lt;div&gt;
          This is coming from the contact folder
          &lt;br /&gt;
          state values:
          &lt;br /&gt;
          {JSON.stringify({ searchValue })}
          &lt;br /&gt;
          {JSON.stringify({ isSidebarOpen })}
          &lt;br /&gt;
          {JSON.stringify({ canonicalFormValues })}
        &lt;/div&gt;
      )}
    &lt;/div&gt;
  );
};

const mapDispatchToProps = {
  clearAll,
  fetchContacts,
};

export default compose(
  connect(
    null,
    mapDispatchToProps,
  ),
)(Contacts);

</code></pre>
",https://stackoverflow.com/questions/59960031/test-a-react-component-using-test-and-react-testing-library,"['javascript', 'reactjs', 'redux', 'jestjs', 'react-testing-library']",3778,True,2,1
Angular unit testing with custom typings gives Cannot find namespace,"<p>I am using custom typings for my angular project to avoid rework in client side for strict typings. However, it is not working while running unit tests. </p>

<p>I am not sure, how to bring this namespace while running unit tests. Below is the code we have</p>

<p><strong>Component</strong></p>

<pre><code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  title = 'app';
  public employees: Company.Core.DTO.IEmployee[];
}
</code></pre>

<p><strong>SPEC</strong></p>

<pre><code>import { NO_ERRORS_SCHEMA } from ""@angular/core"";
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

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

    let fixture: ComponentFixture&lt;AppComponent&gt;;
    let component: AppComponent; 

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

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

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

  });
</code></pre>

<p><strong>Typings</strong> in file (app/typings/Company.typings.ts) autogenerated by <a href=""http://type.litesolutions.net/"" rel=""nofollow noreferrer"">TypeLite</a></p>

<pre><code>declare module Company.Core.DTO {
  interface IEmployee {
    Number: number;
    Age: number;    
    Name: string;   
  }
}
</code></pre>

<p>Error while executing unit test </p>

<blockquote>
  <p>error TS2503: <strong>Cannot find namespace Company</strong></p>
</blockquote>

<p>This happens only during unit testing compilation. While running application, we are not getting this error. </p>

<p>Tried this <a href=""https://stackoverflow.com/questions/42394697/angular2-cannot-find-namespace-google/42416954#42416954"">Angular2 Cannot find namespace &#39;google&#39;</a> but no luck</p>

<p><strong>NPM packages</strong></p>

<pre><code>Angular : 8.2.12
jasmine-core : ~3.5.0
karma: ^4.4.1
karma-jasmine : ~2.0.1
typescript: 3.5.3
</code></pre>
",https://stackoverflow.com/questions/61206128/angular-unit-testing-with-custom-typings-gives-cannot-find-namespace,"['angular', 'unit-testing', 'angular8']",1325,True,2,1
How to Capture ApplicatonEvent in Spring boot integration test?,"<p>The issue is that Application Event is not being captured in Spring boot test While it works fine for files listening to event in app project. </p>

<p>I want to capture an ApplicationEvent in Spring boot test(don't want to do Unit testing). My goal is to capture this application event and then perform few tasks in my test to verify the end-to-end functionality. Since, the event is not being captured in test case so I am not able to write integration tests.</p>

<p>Please let me know what is wrong with the code.</p>

<p>Thanks All.</p>

<pre class=""lang-java prettyprint-override""><code>package com.example.demo;

import org.springframework.context.ApplicationEvent;

public class CacheRefreshEvent extends ApplicationEvent {
    private String message;

    private static final long serialVersionUID = 1L;

    public CacheRefreshEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>package com.example.demo;

import org.springframework.context.ApplicationEvent;

public class CacheRefreshCompleteEvent extends ApplicationEvent {
    private String message;

    private static final long serialVersionUID = 1L;

    public CacheRefreshCompleteEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>package com.example.demo;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class CaptureCacheRefreshCompleteEvent implements ApplicationListener&lt;CacheRefreshCompleteEvent&gt; {

    private ApplicationEventPublisher applicationEventPublisher;

    void applicationEvent() throws InterruptedException {
        applicationEventPublisher.publishEvent(new CacheRefreshEvent(this, ""event triggered from SolrUtilitiesTest()""));
        Thread.sleep(5000);
        System.out.println(""Finished execution of test."");
    }

    public void onApplicationEvent(CacheRefreshCompleteEvent cs) {
        System.out.println(""gotcha in CaptureCachedRefreshCompleteEvent"");
    }

    public void setApplicationEventPublisher(ApplicationEventPublisher arg0) {
        this.applicationEventPublisher = arg0;
    }

}

</code></pre>

<pre class=""lang-java prettyprint-override""><code>package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>package com.example.demo;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest
class DemoApplicationTests implements ApplicationEventPublisherAware, ApplicationListener&lt;CacheRefreshCompleteEvent&gt; {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Test
    void applicationEvent() throws InterruptedException {
        applicationEventPublisher.publishEvent(new CacheRefreshEvent(this, ""event triggered from Springboot test""));
        for(int i=0; i&lt; 20; i ++) {
            Thread.sleep(1000);
        }
        System.out.println(""Finished execution of test."");
    }

    public void onApplicationEvent(CacheRefreshCompleteEvent cs) {
        System.out.println(""gotcha"");
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher arg0) {
        this.applicationEventPublisher = arg0;
    }

}
</code></pre>
",https://stackoverflow.com/questions/60389327/how-to-capture-applicatonevent-in-spring-boot-integration-test,"['spring', 'spring-boot', 'integration-testing']",2443,True,2,1
Jest Express testing middleware with arguments,"<p>I'm pretty new to node and this is my first time unit testing an app. I'm doing well with Jest faking the request with Jest function as below</p>

<pre><code>// Create a fake request
 const mockRequest = (sessionData, body) =&gt; ({
  session: { data: sessionData },
  body
});

// Create a fake response
 const mockResponse = () =&gt; {
  const res = {};
  res.status = jest.fn().mockReturnValue(res);
  res.json = jest.fn().mockReturnValue(res);
  return res;
};

const mockNext = () =&gt; {
  const next = jest.fn();
  return next;
};
</code></pre>

<p>So I can use them like follows</p>

<pre><code>doSomething(req, res, next);
expect(res.status).toHaveBeenCalledWith(201);
//or
expect(next).toHaveBeenCalled();
</code></pre>

<p>That's enough for all the cases until I found that my authorisation middleware includes a couple of parameters so I can not pass the fake res and req as below</p>

<pre><code>exports.isAllowedTo = (par1, par2) =&gt; {
    return async (req, res, next) =&gt; {
        try {
            //
            // Grant logic here that needs par1 and par2
            //

            if(granted)
                next();
            else
                return res.status(401).json({
                    error: ""You don't have enough permission to perform this action""
                });

        } catch (err) {
            res.status(406).json({
                error: err.toString(),
            })
        }
    }
}
</code></pre>

<p>If I test <code>isAllowTo(req, res, next)</code> with the mock req, res and next then I'm missing the 2 parameters needed by the function. Actually when I do this, the function <code>isAllowTo()</code> is not even called. I don't know how to deal with that. Any suggestion or approach?</p>
",https://stackoverflow.com/questions/60001881/jest-express-testing-middleware-with-arguments,"['node.js', 'unit-testing', 'express', 'jestjs', 'middleware']",7109,True,7,2
Error when running multiple PHPUnit Tests in Laravel 8,"<p>Unit testing in a Laravel 8 project is throwing an error when more than one test is called.
The issue is causing my tests to fail when I run more than one at once. When running a batch of tests the first one runs and passes as expected, Then all subsequent tests fail when trying to run the <code>createApplication()</code> function from the default <code>trait CreatesApplication</code>. All of my tests have been run individually and pass.</p>
<p>Causing this error:</p>
<pre><code>• Tests\Feature\ProjectDashboardTest &gt; dashboard returns200
   Error

  Call to a member function make() on bool

  at tests/CreatesApplication.php:19
     15▕     public function createApplication()
     16▕     {
     17▕         $app = require_once __DIR__.'/../bootstrap/app.php';
     18▕
  ➜  19▕         $app-&gt;make(Kernel::class)-&gt;bootstrap();
     20▕
     21▕         return $app;
     22▕     }
     23▕ }
</code></pre>
<p>This occurs when the two tests run are identical.</p>
<p>So this code:</p>
<pre><code>class DashboardTest extends TestCase
{

    public function testDashboardReturns200()
    {
        $response = $this-&gt;get('/dashboard');
        $response-&gt;assertStatus(200);
    }

    public function testDashboardReturns200V2()
    {
        $response = $this-&gt;get('/dashboard');
        $response-&gt;assertStatus(200);
    }
}
</code></pre>
<p>Gives this result:</p>
<pre><code>
php artisan test ./tests/feature/DashboardTest.php

   FAIL  Tests\Feature\DashboardTest
  ✓ dashboard returns200
  ⨯ dashboard returns200 v2

  ---

  • Tests\Feature\DashboardTest &gt; dashboard returns200 v2
   Error

  Call to a member function make() on bool

  at tests/CreatesApplication.php:19
     15▕     public function createApplication()
     16▕     {
     17▕         $app = require_once __DIR__.'/../bootstrap/app.php';
     18▕
  ➜  19▕         $app-&gt;make(Kernel::class)-&gt;bootstrap();
     20▕
     21▕         return $app;
     22▕     }
     23▕ }


  Tests:  1 failed, 1 passed
  Time:   4.02s
</code></pre>
<p>Is there a fix I am missing?</p>
<p><strong>Edit, Added App file as requested</strong></p>
<pre><code>&lt;?php

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the &quot;glue&quot; for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/

$app-&gt;singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app-&gt;singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app-&gt;singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/

return $app;
</code></pre>
",https://stackoverflow.com/questions/64424860/error-when-running-multiple-phpunit-tests-in-laravel-8,"['php', 'laravel', 'unit-testing', 'phpunit', 'laravel-8']",1495,True,2,1
Disable servlet filters for unit tests,"<p>In Spring Boot application I am unit testing controllers using <code>MockMvc</code>. I have a servlet filter that needs to run for every request but I want to ignore it when running unit tests and making requests through <code>MockMvc</code>. </p>

<p>The reason is that my filter is a <code>@Component</code> and it has got another bean <code>@Autowired</code> (call it <code>theBean</code>) and when the unit tests run some of them fail because if <code>theBean</code> is not in the context and some of them pass because the controllers also use <code>theBean</code></p>

<p>What I am looking to do is to disable the servlet filter when it's running the MVC tests using <code>MockMvc</code>, any ideas? </p>
",https://stackoverflow.com/questions/62299409/disable-servlet-filters-for-unit-tests,"['spring-boot', 'spring-mvc', 'servlet-filters']",3069,True,2,2
"StateFlow tied to application&#39;s lifetime, but without GlobalScope (Android, coroutines)","<p>In the coroutine world, <code>GlobalScope</code> seems to be highly discouraged. I, myself run into lots of issues with it, most notably in unit testing (e.g. <a href=""https://stackoverflow.com/questions/64823459/oneach-changes-the-dispatcher-in-stateflow-kotlin-coroutines"">onEach changes the dispatcher in StateFlow (kotlin coroutines)</a>).</p>
<p>Anyway, I wonder <strong>what I could use instead</strong> for some StateFlows which should generally live longer than the lifetime of a single viewmodel etc. Consider some singleton respository the keeps some state for use by different viewmodels (UDF-style). It should keep that state throughout the app's lifetime. Something like this:</p>
<pre><code>class CartManager(
    private val cartService: CartService,
    dispatchers: DispatcherProvider
) {

    private val cartRefreshChannel = Channel&lt;Unit&gt;()

    val cartFlow = cartRefreshChannel
        .receiveAsFlow()
        .conflate()
        .onStart { emit(Unit) }
        .map { cartService.requestCart() }
        .flowOn(dispatchers.io())
        .stateIn(GlobalScope, SharingStarted.WhileSubscribed(), null)

    suspend fun addItemToCart() {
        cartService.addItemToCart()
        cartRefreshChannel.send(Unit)
    }

    //there should be some error handling and retrying here, generally the cartFlow should never cancel / fail

}
</code></pre>
<p>What I could use here instead of GlobalScope to keep the same functionality but not be bothered with <code>GlobalScope</code> quirks?</p>
",https://stackoverflow.com/questions/64824335/stateflow-tied-to-applications-lifetime-but-without-globalscope-android-coro,"['kotlin', 'kotlin-coroutines']",439,True,2,1
How to make a testable wrapper around Threading.Timer and replace it when unit testing?,"<p>I am struggling more than one day already with testing of my <code>System.Threading.Timer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period);</code> overload.</p>

<p>Basing on <a href=""https://stackoverflow.com/a/2367701/12603542"">this solution</a> I created my <strong>ThreadingTimer</strong>, <strong>FakeTimer</strong>, that implements <strong>ITimer</strong>:</p>

<pre><code>public interface ITimer
    {
        bool Change(int dueTime, int period);
        bool IsDisposed { get; }

        void Dispose();
    }


public class ThreadingTimer : ITimer, IDisposable
    {
        private Timer _timer;

        public ThreadingTimer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
        {
            _timer = new Timer(callback, state, dueTime, period);
        }

        public bool IsDisposed { get; set; }

        public void Dispose()
        {
            IsDisposed = true;
            Dispose();
            GC.SuppressFinalize(this);
        }


        public bool Change(int dueTime, int period)
        {
            _timer.Change(dueTime, period);

            return true;
        }
    }

public class FakeTimer : ITimer
    {
        private object state;

        public FakeTimer(TimerCallback callback, object state)
        {
            this.state = state;
        }

        public bool IsDisposed { get; set; }

        public bool Change(int dueTime, int period)
        {
            return true;
        }

        public void Dispose()
        {
            IsDisposed = true;
            Dispose();
            GC.SuppressFinalize(this);
        }
    }
</code></pre>

<p>In my service class I want to make usage of my <strong>ThreadingTimer</strong>:</p>

<pre><code>public ITimer Timer { get; set; }
private void StartUpdates()
        {
            Task.Run(() =&gt;
            {
                Timer = new ThreadingTimer(StartUpdatingVessels, null, TimeSpan.Zero, TimeSpan.FromHours(24));

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

<p>BUT when it comes to unit testing, I have no idea and understanding how to make usage and advantage of implementing of <strong>ITimer</strong> in my <strong>FakeTimer</strong>. Because if in my test will be called method <code>StartUpdates()</code>, new instance of <strong>ThreadingTimer</strong> will be created, even if already <strong>Timer</strong> prop has assigned <strong>FakeTimer</strong>:</p>

<pre><code>[Fact]
        public void SetUpdatingStarted_CalledWhenUpdatingAlreadyStarted_DisposesTimer()
        {
            _timedUpdateControl.Timer = new FakeTimer(CallbackTestMethod, null);
            bool intendedToStartUpdates = false;

            _timedUpdateControl.StartOrStopUpdates(intendedToStartUpdates); //that methid calls private method StartUpdates() and creates instance for ITimer

            //assert something
        }
</code></pre>

<p>How hould I mock it there? (I am using <strong>Moq</strong> framework in test project).</p>
",https://stackoverflow.com/questions/62331381/how-to-make-a-testable-wrapper-around-threading-timer-and-replace-it-when-unit-t,"['c#', 'unit-testing', 'timer', 'moq', 'wrapper']",540,True,1,1
using Golang context.WithValue in testing for http request,"<p>I am trying to do unit testing, I am using GraphQL <code>gqlgen</code> for this case with Echo, I have been struggle to do test with my context, I can't add <strong>header</strong> in my testing due the GraphQL not using the server endpoint
here is my code to set the context value</p>

<pre><code>var ctx *http.Request
var echo echo.Context

h := context.WithValue(ctx.Context(), ""Token"", token)
tk := ctx.WithContext(h)
echo.SetRequest(tk)
</code></pre>

<p>I do this on middleware function when I run my server, nothing issue,
here is how I call that in my resolver</p>

<pre><code>// c is context.Context
tokenHeader = c.Value(""Token"")
</code></pre>

<p>but in testing I create that codes
always got:</p>

<pre><code>panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1703953]

goroutine 30 [running]:
testing.tRunner.func1.1(0x17b3000, 0x1f47810)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:940 +0x2f5
testing.tRunner.func1(0xc000378900)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:943 +0x3f9
panic(0x17b3000, 0x1f47810)
        /usr/local/Cellar/go/1.14.3/libexec/src/runtime/panic.go:969 +0x166
spur/test.TestCredential.func3(0xc000378900)
        /Users/me/Documents/project/test/main_test.go:144 +0x193
testing.tRunner(0xc000378900, 0xc00034fdf0)
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:991 +0xdc
created by testing.(*T).Run
        /usr/local/Cellar/go/1.14.3/libexec/src/testing/testing.go:1042 +0x357
</code></pre>

<p>is it possible to set the context value during in test? </p>

<p>here is may full testing code:</p>

<pre><code>
func TestCredential(t *testing.T)  {
    config := resolver.Config{
        Resolvers: resolver.New(),
    }

    clientTest := testClient.New(handler.NewDefaultServer(resolver.NewExecutableSchema(config)))

    t.Run(""Should Success Change Password"", func(t *testing.T) {
        var ctx *http.Request
        var echo echo.Context

        h := context.WithValue(ctx.Context(), ""Token"", token)
        tk := ctx.WithContext(h)
        echo.SetRequest(tk)


        var respond map[string]interface{}
        mutation := `mutation {
                      changeCredentialConfirmation(
                        currentPassword: """"
                        newChange: ""newPassword""
                        isForgotPassword: true
                        isChangePassword: false
                      )
                    }`
        clientTest.MustPost(
            mutation,
            &amp;respond,
        )
        require.True(t, respond[""changeCredentialConfirmation""].(bool), ""Check your email"")
    })
}
</code></pre>
",https://stackoverflow.com/questions/62372373/using-golang-context-withvalue-in-testing-for-http-request,"['unit-testing', 'go', 'graphql', 'go-echo', 'go-testing']",5602,False,1,0
How to unit test that a document has a given permission?,"<p>I'm setting up unit testing using marklogic-unit-test and one thing I'd like to do is check a given document has a particular permission. However, when I test my permission against a Sequence of permissions, I get an <code>XDMP-NONMIXEDCOMPLEXCONT</code> error. I assume this has to do with the fact that permissions are complex objects and not something like a simple string, because this works with collections.</p>
<pre><code>const test = require(&quot;/test/test-helper.xqy&quot;);
let p1 = Sequence.from([xdmp.permission(&quot;rest-reader&quot;, &quot;read&quot;, &quot;element&quot;)]);
let p2 = Sequence.from([
  xdmp.permission(&quot;rest-reader&quot;, &quot;read&quot;, &quot;element&quot;), 
  xdmp.permission(&quot;rest-writer&quot;, &quot;update&quot;, &quot;element&quot;)
]);
test.assertAtLeastOneEqual(p1, p2)
</code></pre>
<p>Which returns:</p>
<pre><code>[javascript] XDMP-NONMIXEDCOMPLEXCONT: fn:data(&lt;sec:permission 
xmlns:sec=&quot;http://marklogic.com/xdmp/security&quot;&gt;
&lt;sec:capability&gt;...&lt;/sec:capability&gt;...&lt;/sec:permission&gt;) 
-- Node has complex type with non-mixed complex content
</code></pre>
<p>The best alternative I can come up with is to explicitly loop over the Sequence and do the comparison with <code>fn.deepEqual</code> on each element. Is there a better way?</p>
",https://stackoverflow.com/questions/64760065/how-to-unit-test-that-a-document-has-a-given-permission,"['unit-testing', 'marklogic', 'marklogic-10']",55,True,1,1
How to change #define value from another file,"<p>I have a source and header file:</p>

<pre><code>//boot.h

#define BOOT_DATA_ADDRESS EMBEDDED_ADDRESS

void BootDataReadTable(bootData_t * bootData);

</code></pre>

<pre><code>//boot.c

void BootDataReadTable(bootData_t * bootData)
{
    uint32_t *userPageBootDataTable = (uint32_t *) (BOOT_DATA_ADDRESS );
    uint32_t copiedDataTable[BOOT_DATA_WORDS] = {0U};
    for (uint32_t i = 0; i &lt; BOOT_DATA_WORDS; i++)
    {
        copiedDataTable[i] = userPageBootDataTable[i];
    }
    unpackBootData(copiedDataTable, bootData);
}
</code></pre>

<p>and a test file:</p>

<pre><code>//test_boot.c

#include ""bootdata.h""

#ifdef BOOT_DATA_ADDRESS
#undef BOOT_DATA_ADDRESS
#define BOOT_DATA_ADDRESS (stackpointer)
#endif 

static uint32_t stack[0x2000] = {0};
static uint32_t * stackpointer = &amp;stack[0];

void test_BootDataReadTable(void)
{
    bootData_t lBootData = {0};

    BootDataReadTable(&amp;lBootData, (uint32_t *)addr);

    //test lBootData
}
</code></pre>

<p>This code runs on an embedded platform. The memory access in <code>BootDataReadTable</code> accesses internal flash on the MCU. For unit testing purposes, I want to run this on my host machine. In <code>test_boot.c</code> I want to change the <code>BOOT_DATA_ADDRESS</code> to point to my stack area on my host machine so that <code>BootDataReadTable</code> just accesses some dummy data instead of trying to access internal flash. </p>

<p>I'm compiling/running the unit test with <code>ceedling</code>.</p>

<p>The method I'm using above does not work. What am I doing wrong/how can I accomplish changing the value of <code>BOOT_DATA_ADDRESS</code> from another file?</p>
",https://stackoverflow.com/questions/60859492/how-to-change-define-value-from-another-file,"['c', 'embedded', 'c-preprocessor']",136,True,1,1
Wait for main queue being dispatched before continue unit test,"<p>I have this method in a class :</p>

<pre><code>func handleResp(_ dataGotten: Result&lt;Response?, Error&gt;) {
      ....

           DispatchQueue.main.async {
              ....
                  GlobalStaticStruct.code = 7
              ...
            }
        }
    }
</code></pre>

<p>And then in my unit testing I have this code :</p>

<pre><code>func testhandleResp() {

        subject = SomeClass()
        subject.handleResp(successResponse)
        XCTAssertNotNil(GlobalStaticStruct.code)
    }
</code></pre>

<p>I need to be able to test that <strong>GlobalStaticStruct.code</strong> is not nil but with the code as it is the test completes before the main queue so the field is nil all the time.</p>

<p>I understand the use of expectations to overcome similar issues but in this case there is no handler I can hook up to.</p>

<p>How can I make my test to wait for the main method to get triggered and finished and THEN test the value of <strong>GlobalStaticStruct.code</strong>?</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/60602741/wait-for-main-queue-being-dispatched-before-continue-unit-test,"['swift', 'unit-testing', 'asynchronous']",527,True,1,1
Lit elements&#39; code coverage appears 0 in spite of passing of test cases,"<p>I am using angular 11, lit for web components and jest for unit testing with electron. The problem that I'm facing is that my lit elements' test cases are passing, but it's coverage remains 0 in jest coverage report. Here are my config files below.</p>
<p>jest.config.js</p>
<pre><code>  moduleNameMapper: {
    '@core/(.*)': '&lt;rootDir&gt;/src/app/core/$1',
  },
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['&lt;rootDir&gt;/setup-jest.ts'],
  collectCoverageFrom: [
    &quot;&lt;rootDir&gt;/src/litelements/*.ts&quot;,
    &quot;&lt;rootDir&gt;/src/app/**/*.ts&quot;,
    &quot;!&lt;rootDir&gt;/src/app/app.module.ts&quot;,
    &quot;!&lt;rootDir&gt;/src/app/app-routing.module.ts&quot;,
    &quot;!**/node_modules/**&quot;,
    &quot;!**/vendor/**&quot;
  ],
  setupFiles: ['./dist/angular-lit/main.js'],
  runner: 'jest-electron/runner',
  testEnvironment: 'jest-electron/environment',
}
</code></pre>
<p>setup-jest.ts</p>
<pre><code>import 'jest-preset-angular';

/* global mocks for jsdom */
const mock = () =&gt; {
  let storage: { [key: string]: string } = {};
  return {
    getItem: (key: string) =&gt; (key in storage ? storage[key] : null),
    setItem: (key: string, value: string) =&gt; (storage[key] = value || ''),
    removeItem: (key: string) =&gt; delete storage[key],
    clear: () =&gt; (storage = {}),
  };
};

Object.defineProperty(window, 'localStorage', { value: mock() });
Object.defineProperty(window, 'sessionStorage', { value: mock() });
Object.defineProperty(window, 'getComputedStyle', {
  value: () =&gt; ['-webkit-appearance'],
});

Object.defineProperty(document.body.style, 'transform', {
  value: () =&gt; {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});
</code></pre>
<p>Here is my lit element and it's spec file</p>
<p>first-lit.ts (lit element)</p>
<pre><code>import {LitElement, html, property, customElement} from 'lit-element';

@customElement('str-btn')
export class MyElement extends LitElement {

    @property({ type: String })
    innerTextValue = 'test text';

  render() {
    return html`
      &lt;div&gt;Hello from MyElement!&lt;/div&gt;
      &lt;div&gt;${this.innerTextValue}&lt;/div&gt;
    `;
  }
}
</code></pre>
<p>first-lit.spec.ts (lit element spec file)</p>
<pre><code>import { MyElement } from './first-lit';

describe('lit-button', () =&gt; {

    const FORM_BUTTON = 'str-form-btn';
    let buttonElement: MyElement;

    beforeEach(() =&gt; {
        buttonElement = window.document.createElement(FORM_BUTTON) as MyElement;
        document.body.appendChild(buttonElement);
    });

    afterEach(() =&gt; {
       document.body.getElementsByTagName(FORM_BUTTON)[0].remove();
    });



    it('check set properties', () =&gt; {
        // require('electron').remote.getCurrentWindow().show();
        buttonElement.innerTextValue = 'test';
        expect(buttonElement.innerTextValue).toBe('test');
    });

});
</code></pre>
<p>This is the image of jest coverage report. The tests for lit element are passing but it's coverage is 0.</p>
<p><a href=""https://i.stack.imgur.com/TArj0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/TArj0.png"" alt=""enter image description here"" /></a></p>
<p>Sources I referred:
<a href=""https://www.ninkovic.dev/blog/2020/testing-web-components-with-jest-and-lit-element"" rel=""nofollow noreferrer"">https://www.ninkovic.dev/blog/2020/testing-web-components-with-jest-and-lit-element</a></p>
",https://stackoverflow.com/questions/64964155/lit-elements-code-coverage-appears-0-in-spite-of-passing-of-test-cases,"['angular', 'unit-testing', 'jestjs', 'lit-element']",266,False,1,0
What are the advantages and disadvantages of conducting non-isolated unit testing?,"<p>I created a simple project for conducting unit tests, here is the sample code:</p>

<pre><code>        [TestMethod]
        public async Task GetCountry_ShouldReturnAndorra()
        {
            // Arrange
            int countryId = 1;
            string requestUrl = baseUrl + ""/Countries/"" + countryId;

            // Act
            // GET : /api/v1/Locations/Countries/{countryId} 
            HttpResponseMessage response = await client.GetAsync(requestUrl); 

            // Assert
            Assert.IsTrue(response.IsSuccessStatusCode, ""Response StatusCode is not success"");

            string value = await response.Content.ReadAsStringAsync();
            Assert.IsNotNull(value);

            var country = DeserializeCountryResponse(value);
            Assert.AreEqual(country.data.Id, countryId);

            Assert.AreEqual(country.errors.Count, 0, 0, ""Reponse contains errors"");
        }
</code></pre>

<p>And this project depends on whether the API server is running and its dependencies (databases, etc.)</p>

<p>But the documentation says that this is not the best practice (<a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices#characteristics-of-a-good-unit-test"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices#characteristics-of-a-good-unit-test</a>):</p>

<blockquote>
  <p><strong>Characteristics of a good unit test</strong></p>
  
  <p>...</p>
  
  <p><strong>Isolated.</strong> Unit tests are standalone, can be run in isolation, and have no dependencies on any outside factors such as a file system or database.</p>
  
  <p>...</p>
</blockquote>

<p>So should you go this way or is there another?</p>
",https://stackoverflow.com/questions/61094328/what-are-the-advantages-and-disadvantages-of-conducting-non-isolated-unit-testin,"['c#', 'unit-testing', 'asp.net-web-api']",72,True,1,1
Problem with testing async functions in Angular with Jasmine,"<p>I am unit testing my Ionic 4 app with Jasmine. At the moment I am getting errors when running almost all my tests because I am doing something wrong with the async/await functions. The error that I get is: &quot;Error: Timeout - Async function did not complete within 5000ms.&quot; I have changed this timeout_interval to another larger number and I still get this error.</p>
<p>My code is:</p>
<pre><code>beforeEach(async(() =&gt; {
  const storage = new Storage({         
    // Define Storage
    name: '__mydb',
    driverOrder: ['indexeddb', 'sqlite', 'websql']
  });  
    
  component = new HomepagePage(storage);

  TestBed.configureTestingModule({
    declarations: [ HomepagePage ],
    imports: [
      IonicModule.forRoot(), 
      RouterTestingModule,
      IonicStorageModule.forRoot()
    ]
  }).compileComponents();

  fixture = TestBed.createComponent(HomepagePage);
  component = fixture.componentInstance;
  fixture.detectChanges();
}));

it('should create', async () =&gt; {
  let home = jasmine.createSpyObj('home_spy',['getprice'])
  const result = await home.getprice
  expect(component).toBeTruthy();
});

describe('before logged in', () =&gt; {
  let home = jasmine.createSpyObj('home_spy',['getprice'])
    
  it('shows the price', async () =&gt; {
    const result = await home.getprice
    expect(home.getprice.length).toEqual(2);
  });
});
</code></pre>
<p>My app is working fine when I am using it. However, could it be that the error is in the code itself? An example of the getprice() function is:</p>
<pre><code>async getprice() {
    var price_eth :number
    var price_btc :number

    try {
        var url_btc = &quot;https://api.binance.com/api/v1/klines?symbol=BTCUSDT&amp;interval=1m&quot;;
        var url_eth = &quot;https://api.binance.com/api/v1/klines?symbol=ETHUSDT&amp;interval=1m&quot;
        const btc = await axios.get(url_btc)
        const eth = await axios.get(url_eth)

        if (btc.data.length != 0 &amp;&amp; eth.data.length != 0) {
           this.loaded = 'yes'
        } else { 
            this.loaded='no'
        }
        this.time = new Date(btc.data[btc.data.length-1][0]).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, &quot;$1&quot;);
        price_btc = Math.floor(btc.data[btc.data.length-1][1])
        price_eth = Math.floor(eth.data[eth.data.length-1][1])

       //These global variables are declared so they display the price but they are not used for any other functions.
       this.glob_price_btc = price_btc
       this.glob_price_eth = price_eth

       return {
        'price_btc':price_btc,'price_eth':price_eth
       }

    } catch {
        this.loaded = 'no';
        return
    }
}
</code></pre>
",https://stackoverflow.com/questions/63375216/problem-with-testing-async-functions-in-angular-with-jasmine,"['javascript', 'typescript', 'testing', 'ionic-framework', 'jasmine']",567,False,1,1
Configuring autotools to use the same object files to build two programs,"<p>I have a C++ project using autotools to build, and <a href=""https://github.com/catchorg/Catch2"" rel=""nofollow noreferrer"">Catch2</a> for unit testing. The details of Catch2 are probably not relevant: it's just another program I have to build and run.</p>

<p>I have <code>Makefile.am</code> set up like this (simplified):</p>

<pre><code>AUTOMAKE_OPTIONS = subdir-objects
check_PROGRAMS = catch2
bin_PROGRAMS = lpsdr

common_sources = applicationcontroller.cc flowgraph.cc [...]
lpsdr_SOURCES = $(common_sources) main.cc
catch2_SOURCES = $(common_sources) test.cc
</code></pre>

<p>This works mostly, except it compiles everything twice, creating <code>lpsdr-applicationcontroller.o</code> and <code>catch2-applicationcontroller.o</code>, and so on for each thing in <code>common_sources</code>.</p>

<p>Of course this doubles the build time. I'd prefer to link both <code>catch2</code> and <code>lpsdr</code> with the same object files: it will be faster to build and also ensure I'm testing exactly the same compiled code as I'm running.</p>

<p>Is there any way around this behavior?</p>
",https://stackoverflow.com/questions/61177978/configuring-autotools-to-use-the-same-object-files-to-build-two-programs,"['automake', 'catch2']",103,True,1,1
Object is possibly undefined VS Null Assertion Operator =&gt; What is the correct way to use?,"<p>I have a code example below and at line <strong>const cars = x.cars.filter()</strong> i am getting an error <strong>object is possibly undefined</strong> for x.cars. To overcome this issue i have added an if check like if(x.cars). By adding this i have issue with code coverage karma unit testing for this code. So i researched and found there is an Null assertion operator to overcome this typescript compiler issue. Is it ok to use Null assertion operator in this scenario or is there anything else i need to take into consideration ?   </p>

<pre><code>this.carOptions$().pipe(
  map((result: any): string =&gt; {
    return result
      .filter(x =&gt; x.selected)
      .map(x =&gt; {
        if (x.cars) { //added this condition to overcome object is possibly undefined error
          const cars = x.cars
            .filter(x =&gt; x.selected)
            .map(x =&gt; x.name)
            .join(',');
          return `${x.name}~${cars}`;
        }
      })
  })
).subscribe(result =&gt; {
  this.result = result;
});
</code></pre>

<p>Planning to use Null Assertion Operator as below</p>

<pre><code> const cars = x.cars!
            .filter(x =&gt; x.selected)
            .map(x =&gt; x.name)
            .join(',');
          return `${x.name}~${cars}`;
</code></pre>
",https://stackoverflow.com/questions/60828529/object-is-possibly-undefined-vs-null-assertion-operator-what-is-the-correct-w,"['angular', 'typescript', 'karma-jasmine']",802,True,1,1
Unit testing express.js route with sinon,"<p>I am learning express and sinon (the hard way :) ). I'd like to unit test the following code:</p>

<pre><code>//  ./routers/root.js

var express = require('express');
var router = express.Router();

router
  .route('/')
  .get(function(req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.write(JSON.stringify({Application: ""NodeTours"", Version: ""2.0.0"", Host: host, Port: port}));
    res.end();
  });

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

<p>I've been trying different things without success. I'm back to the basic example. I realize it may seem like a complete newbie question but I'm clueless. Here's the latest try:</p>

<pre><code>//   ./test/test.js

var sinon = require('sinon')
var expect = require('chai').expect

describe('Routers', function() {

  context('/', function() {
    var rootRouter = require('../routers/root')
    var res = {Application: ""NodeTours"", Version: ""2.0.0"", Host: 'host', Port: 'port'};
    it('should call / router', function() {
      rootRouter.route('/').get(null, res);
      // TODO: expect...
    })
  })
})
</code></pre>

<p>It fails with:</p>

<pre><code>  Routers
    /
      1) should call / router


  0 passing (4ms)
  1 failing

  1) Routers
       /
         should call / router:
     Error: Route.get() requires a callback function but got a [object Null]
      at Route.&lt;computed&gt; [as get] (node_modules/express/lib/router/route.js:202:15)
      at Context.&lt;anonymous&gt; (test/test.js:10:29)
      at processImmediate (internal/timers.js:456:21)
</code></pre>

<p>I've tried multiple tutorials without success. I'd appreciate any pointers to how my code could be unit tested. Or how to adjust my code so unit testing is easier/possible.</p>

<p>My main app server.js file for context and reference (removed code not relevant for this question)</p>

<pre><code>//   ./server.js
// npm pacakages
var express = require('express');
var bodyParser = require('body-parser');

// app imports
var { rootRouter } = require('./routers');
// other cut out

//globals
app = express();
app.use(bodyParser.json());
app.use('/', rootRouter);
// other cut out

// Set up Mongo DB connection
// code to st up db connection

// Start server (only if connection to DB established)
var server = MongoClient(url, { useUnifiedTopology: true, poolSize: 10 }).connect().then(client =&gt; {
  const dbo = client.db(dbName);

  // some init code cut out

  // make connection available
  app.locals.dbo = dbo;

  // start server
  app = app.listen(process.env.PORT || 7777, function () {
    host = require('os').hostname();
    port = ""7777"";
    logger.verbose(""Startup: NodeTours listening at http://%s:%s"", host, port)
  });
}).catch(error =&gt; {
  logger.error(""Startup: Couldn't connect to the DB. The app will exit"")
  logger.error(""  Error: "" + error)
  process.exit();
  }
);

</code></pre>
",https://stackoverflow.com/questions/61503864/unit-testing-express-js-route-with-sinon,"['node.js', 'unit-testing', 'express', 'sinon']",989,True,1,1
Trying to mock a service but I get NullPointerException (JUNIT/MOCKITO),"<p>I'm new to Junit and Mockito unit testing. I need to unit test the method &quot;processFiles(final File folder)&quot;</p>
<p>Since I make a call to another service inside this method called myService.isFileOk(data), I think I need to mock this service to make it return true.</p>
<p>But as I run my test, I get a Null pointer exception.</p>
<p>This is a part of the code from the processFiles method:</p>
<pre><code>  @EJB
  private transient MyService myService;

  public void processFiles(final File folder)
  {
     
      File[] fileNames = folder.listFiles();
      List&lt;String&gt; lines = new ArrayList&lt;&gt;();
      boolean isFirstFile = true;
      try
      {
          for (File file : fileNames)
          {
                  List&lt;String&gt; l = readContent(file, isFirstFile);
                  l.forEach(i -&gt; lines.add(i));
                  isFirstFile = false;     
          }

          String[] data = lines.get(0).trim().split(&quot;;&quot;);
          if (!this.myservice.isFileOk(data))
          {
            // ...
          }
          else
          {
              // ...
          }
      }
      catch (IOException e)
      {
          e.printStackTrace();
      }
  }

</code></pre>
<p>And this is how I'm trying to test my processFile method</p>
<pre><code>    @Mock
    public MyService myService ;

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();


    @Test
    public void testWrite2() throws IOException {

        final File tempFile1 = temporaryFolder.newFile(&quot;tempFile.txt&quot;);
        final File tempFile2 = temporaryFolder.newFile(&quot;tempFile2.txt&quot;);

        String[] data = {&quot;a&quot;, &quot;b&quot; , &quot;c&quot; , &quot;d&quot;} ;
        this.myService = new MyService();


       MyService myService = Mockito.mock(MyService.class);
 
       when(myService.isFileOk(data)).thenReturn(true);


//... myclass.processFiles(file);
    }
</code></pre>
<p>Do you know how I should proceed to mock the isFileOk ? Thanks a lot in advance for your help</p>
",https://stackoverflow.com/questions/63236954/trying-to-mock-a-service-but-i-get-nullpointerexception-junit-mockito,"['java', 'junit', 'mockito', 'junit4']",313,False,1,2
Angular unit tests are failing randomly due to Async callback was not invoked with 5000ms(set by jasmine.DEFAULT_TIMEOUT_INTERVAL),"<p>I have written the following code with async unit testing but these are failing randomly not consistently. Can anyone help me what here wrong?</p>
<p><strong>The test case is:</strong> When the user pressed keyboard keys W (go to the previous doc) and S(go to next doc) then on UI selected document(row) should be changed in table.</p>
<pre><code>    it('When user press key W and S then should be able navigate to previous and next document', async () =&gt; {
                createTestBed();
                fixture.detectChanges();
                const searchResultStub = MockNgRedux.getSelectorStub(['documentSearch', 'results']);
                searchResultStub.next(getSearchResult());
                searchResultStub.complete();
                fixture.detectChanges();
    
                const spyPrevElement = spyOn(comp.documentSearchResult._tableService, 'selectPrevElement').and.callThrough();
                const spysNextElement = spyOn(comp.documentSearchResult._tableService, 'selectNextElement').and.callThrough();
    
                await TestUtil.SleepForASecond(0);
                document.dispatchEvent(TestUtil.createKeyUpEvent(&quot;S&quot;));
                fixture.detectChanges();
                expect(spysNextElement).toHaveBeenCalled();
                expect(spysNextElement).toHaveBeenCalledTimes(1);
    
                document.dispatchEvent(TestUtil.createKeyUpEvent(&quot;W&quot;));
                fixture.detectChanges();
                expect(spyPrevElement).toHaveBeenCalled();
                expect(spyPrevElement).toHaveBeenCalledTimes(1);
            });
</code></pre>
<p><strong>TestUtil.ts file</strong>:</p>
<pre><code>static async SleepForASecond(ms) {
    await new Promise(resolve =&gt; setTimeout(resolve, ms);
  }

 static createKeyUpEvent(key: string, isCapsOn: boolean = false) {
    const keyUpEvent: Event = new KeyboardEvent('keyup', {
      'key': key,
      'modifierCapsLock': isCapsOn
    });
    return keyUpEvent;
  }
</code></pre>
<p>Similar for this other tests are failing due to async and await with the following error. Can anyone have an idea?</p>
<pre><code>Error: Timeout - Async callback was not invoked with 5000ms(set by jasmine.DEFAULT_TIMEOUT_INTERVAL) at &lt;Jasmine&gt;
</code></pre>
<p><strong>OBSERVATION:</strong> <em>TEST CASES ARE MORE FAILING INSIDE DOCKER CONTAINER. TESTS WOULD SOMETIMES PASS WITHOUT ANY ISSUES BUT SOMETIMES FAIL.</em></p>
",https://stackoverflow.com/questions/63048721/angular-unit-tests-are-failing-randomly-due-to-async-callback-was-not-invoked-wi,"['angular', 'async-await', 'angular-unit-test']",1053,False,1,1
Jest [Vue warn]: Error in render: &quot;TypeError: Cannot read property &#39;type&#39; of undefined&quot;,"<p>I am relatively new to Jest unit testing. I have a Child component DataList.vue with a Buefy tag that has a v-bind as follows:</p>
<pre><code>&lt;b-tag :type=&quot;currentStatus.type&quot; class=&quot;statustag&quot;&gt;
    {{ currentStatus.statusText }}
    &lt;b-icon
      :icon=&quot;currentStatus.icon&quot;
      size=&quot;is-small&quot;
      class=&quot;tagicon&quot;
    &gt;&lt;/b-icon&gt;
  &lt;/b-tag&gt;
</code></pre>
<p>And in the script tag, I have the following computed property:</p>
<pre><code>get currentStatus() {
    return this.statusOptions
      .filter(status =&gt; status.status == this.item.status)
      .shift();
  }
  private statusOptions = [
    {
      status: 'Success',
      statusText: 'Success',
      type: 'is-primary',
      icon: 'check-circle'
    },
    {
      status: 'Fail',
      statusText: 'Fail',
      type: 'is-primary',
      icon: 'close-circle'
    },
  ];
</code></pre>
<p>When I shallow mount the component and write any unit test and run it, I get the following error:</p>
<pre><code>[Vue warn]: Error in render: &quot;TypeError: Cannot read property 'type' of undefined&quot;
</code></pre>
<p>Similary with <code>statusText</code> and <code>icon</code>.</p>
<p>The component is rendered fine on the browser and the unit tests for the remaining part of the component works when I comment the b-tag element out.
Any help on how to get jest test the b-tag element correctly is appreciated.</p>
",https://stackoverflow.com/questions/63299224/jest-vue-warn-error-in-render-typeerror-cannot-read-property-type-of-und,"['typescript', 'unit-testing', 'vue.js', 'jestjs', 'computed-properties']",399,False,1,0
How to test async methods using sinon,"<p>I'm unit testing a function which is calling another async task inside it without await. The reason for that is because I don't want to wait for that function execution.</p>
<pre class=""lang-js prettyprint-override""><code>const fn1 = async () =&gt; {
  fn2();
  return 'foo';
};

const fn2 = async () =&gt; {
  await fn3();
  await fn4();
};

const fn3 = async () =&gt; {
  await s3.upload(params).promise();
};

const fn4 = async () =&gt; {
  await s3.upload(params).promise();
};

</code></pre>
<p>I want to unit test fn1() &amp; fn2() is an async task, &amp; here is what I've tried:</p>
<pre><code>describe(&quot;unit test fn1&quot;, () =&gt; {
  
  let s3Stub;
   
  beforeEach(() =&gt; {
     s3Stub = sinon.stub(S3, &quot;upload&quot;);
 });

  afterEach(() =&gt; {
    s3Stub.restore();
 });
  
  it(&quot;fn1 test&quot; , async () =&gt; {
     const actualValue = await fn1();
     expect(s3Stub.calledTwice).to.be.true; 
  });

});
</code></pre>
<p>Ideally, the s3Stub should have been called twice, but is being called only once &amp; my test gets completed.</p>
<p>I don't want to use await on fn2(), as I want fn2() to be run as an independent thread. Any ideas on how do we unit test on such cases?</p>
",https://stackoverflow.com/questions/64705245/how-to-test-async-methods-using-sinon,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'sinon-chai']",380,True,1,1
how to make the sql database table reflect in the sqlite db when creating unit testing with Laravel 7?,"<p>I have a database with a few database tables in mysql of my laravel 7 application.
Now am trying to do unit testing , but the problem is, is there a way to make those database tables in mysql reflect in the sqlite db that I prefer to use in phpunit ? .how to do that? ..</p>
<p>in the root directory I created a file and named it .env.testing
then I modified its configuration into this</p>
<pre><code>DB_CONNECTION=sqlite
DB_DATABASE=&quot;C:/wamp64/www/myapplication/test.sqlite&quot;
</code></pre>
<p>when I ran the phpunit existing sample test file/suite in laravel 7,
nothing happened, the test.sqlite has no tables..what did I missed out ?</p>
",https://stackoverflow.com/questions/62947600/how-to-make-the-sql-database-table-reflect-in-the-sqlite-db-when-creating-unit-t,"['laravel', 'phpunit', 'laravel-7']",317,False,1,1
How to use unittest module for a python script which calls mutiple functions and uses global variables,"<p>This is one of the function in my python script for which I am trying to write unit test case, since it uses global variables and audit and big query functions which is written as different utility scripts I am not understanding how to write @patch and execute unit test cases for the same.</p>
<ol>
<li>How will I patch global variables?</li>
<li>How to patch functions which doesn't have any return for eg :audit_event_source_table, can we ignore such functions during unit testing ? if so how to do the same?</li>
<li>How to do assertion as I do not have any return value but have logger.info messages?</li>
</ol>
<pre><code>import logging
from datetime import datetime
from pathlib import Path
import sys
import __main__
from intient_research_rdm_common.utils.audit_utils import audit_event_source_table, audit_event_job_table, \
    get_job_id, get_source_object_id

from intient_research_rdm_kg_core.common_utils.utils.bigquery_utils import bigquery_data_read
from intient_research_rdm_kg_core.common_utils.utils.conf_read import read_args, read_source_config, read_env_config


global project_id, service_account, conn_ip, debug, node_table_list, edge_table_list, source_name

def edge_validation():
    global edge_table_list
    global source_name
    edge_table_na = []
    edge_table_list_rowcount_zero = []
    dataset_e = &quot;prep_e_&quot; + source_name
    row_count = 0
    edge_table = &quot;&quot;
    source_object_start_timestamp = datetime.now()
    source_object_id = get_source_object_id(source_name, source_object_start_timestamp)
    source_object_type = AUDIT_SOURCE_OBJECT_TYPE_BIGQUERY
    job_id = get_job_id(source_object_start_timestamp)
    source_object_name = dataset_e
    try:
        for edge_table in edge_table_list:
            sql_query = &quot; SELECT * FROM &quot; + &quot;`&quot; + project_id + &quot;.&quot; + dataset_e + &quot;.__TABLES__` WHERE table_id =&quot; + &quot;'&quot; + edge_table + &quot;'&quot;
            data_read, col_names = bigquery_data_read(service_account, sql_query, project_id)
            for ind in data_read.index:
                row_count = (data_read['row_count'][ind])
            if len(data_read.index) == 0:
                edge_table_na.append(edge_table)
            elif row_count == 0:
                edge_table_list_rowcount_zero.append(edge_table)

        if len(edge_table_na) &gt; 0:
            logging.info(&quot;Missing Edge tables in preprocessing layer {} &quot;.format(edge_table_na))
        if len(edge_table_list_rowcount_zero) &gt; 0:
            logging.info(&quot;Edge tables with row count as zero in Pre-processing layer  {} &quot;.format(edge_table_list_rowcount_zero))
        if len(edge_table_na) == 0 and len(edge_table_list_rowcount_zero) == 0:
            logging.info(
                &quot;Edge list validation for the source {} has been successfully completed with no discrepancies&quot;.format(
                    source_name))
            audit_event_source_table(source_object_id, source_object_name, source_object_type, source_name,
                                     source_object_name,
                                     job_id, AUDIT_JOB_STATUS_PASS, source_object_start_timestamp,
                                     datetime.now(), 'NA', 'NA', project_id)

        if len(edge_table_na) &gt; 0 or len(edge_table_list_rowcount_zero) &gt; 0:
            audit_event_source_table(source_object_id, source_object_name, source_object_type, source_name,
                                     source_object_name,
                                     job_id, AUDIT_JOB_STATUS_PASS, source_object_start_timestamp,
                                     datetime.now(), 'NA', 'NA', project_id)
            sys.exit(1)
    except Exception as e:
        msg = '{} : Issue with the edge validation for {} is: \n{}\n'.format(datetime.now(), edge_table, e)
        logging.error(msg)
        audit_event_source_table(source_object_id, source_object_name, source_object_type, source_name,
                                 source_object_name,
                                 job_id, AUDIT_JOB_STATUS_FAIL, source_object_start_timestamp,
                                 datetime.now(), AUDIT_ERROR_TYPE_PREPROCESSING_KG_LAYER_VALIDATION, msg,
                                 project_id)
        raise Exception(msg)
</code></pre>
",https://stackoverflow.com/questions/63448108/how-to-use-unittest-module-for-a-python-script-which-calls-mutiple-functions-and,"['python-unittest', 'patch']",55,False,0,1
PHPunit test errors with `Parse error` on CI,"<p>I'm unit testing my code with the help of <code>phpunit 9.3.8</code>. The tests run fine on my local dev environment (I'm running Windows 10, <code>PHP 7.4.2</code> with <code>Xdebug 2.9.2</code>) but fail because of a parse error when I try to run <code>phpunit</code> on Gitlab CI (The CI runs the latest alpine linux image).</p>
<p>The error is:</p>
<pre><code>$ composer run test
&gt; phpunit
PHPUnit 9.3.8 by Sebastian Bergmann and contributors.
Runtime:       PHP 7.3.23 with Xdebug 2.9.8
Configuration: /builds/gaspacchio/back-to-the-future/phpunit.xml
Reporter
 ✘ Can set short message [6.05 ms]
   │
   │ ParseError: syntax error, unexpected 'int' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)
   │
   │ /builds/gaspacchio/back-to-the-future/src/api/utilities/Reporter.php:21
   │ /builds/gaspacchio/back-to-the-future/src/api/tests/ReporterTest.php:12
   │

// More errors

Time: 00:01.970, Memory: 310.00 MB
ERRORS!
Tests: 6, Assertions: 0, Errors: 6.
Generating code coverage report in Clover XML format ... done [00:00.330]
PHP Warning:  fopen(/builds/gaspacchio/back-to-the-future/): failed to open stream: Is a directory in /builds/gaspacchio/back-to-the-future/vendor/phpunit/phpunit/src/Util/Printer.php on line 89
PHP Stack trace:
PHP   1. {main}() /builds/gaspacchio/back-to-the-future/vendor/phpunit/phpunit/phpunit:0
PHP   2. PHPUnit\TextUI\Command::main() /builds/gaspacchio/back-to-the-future/vendor/phpunit/phpunit/phpunit:61
PHP   3. PHPUnit\TextUI\Command-&gt;run() /builds/gaspacchio/back-to-the-future/vendor/phpunit/phpunit/src/TextUI/Command.php:100
PHP   4. PHPUnit\TextUI\TestRunner-&gt;run() /builds/gaspacchio/back-to-the-future/vendor/phpunit/phpunit/src/TextUI/Command.php:147
PHP   5. PHPUnit\Util\Printer-&gt;__construct() /builds/gaspacchio/back-to-the-future/vendor/phpunit/phpunit/src/TextUI/TestRunner.php:756
PHP   6. fopen() /builds/gaspacchio/back-to-the-future/vendor/phpunit/phpunit/src/Util/Printer.php:89
Code Coverage Report:    
  2020-10-13 10:12:09    
                         
 Summary:                
  Classes:  0.00% (0/11) 
  Methods:  0.00% (0/38) 
  Paths:    0.00% (0/7)  
  Branches:    0.00% (0/7)
  Lines:    0.00% (0/397)
Script phpunit handling the test event returned with error code 2
</code></pre>
<p>Line 21 of the <code>Reporter.php</code> file is below:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php namespace utilities\Reporter;

/**
 * The Reporter class is responsible for returning data to the client.
 */
class Reporter
{
    /** This is the code of the answer.
     * (more comments)
     * @var int The status code.
     */
    private int $code; //&lt;-- This is line number 21
</code></pre>
<p>And the line 12 of <code>ReporterTest.php</code> is:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php

use PHPUnit\Framework\TestCase;
use utilities\Reporter\Reporter;

class ReporterTest extends TestCase
{
    protected $reporter;

    protected function setUp(): void
    {
        $this-&gt;reporter = new Reporter(); // &lt;-- Line 12 is here
    }
}
</code></pre>
<p>I'm using the fixtures function of PHPunit, defined as :</p>
<blockquote>
<p>PHPUnit supports sharing the setup code. Before a test method is run, a template method called setUp() is invoked. setUp() is where you create the objects against which you will test.</p>
</blockquote>
",https://stackoverflow.com/questions/64333429/phpunit-test-errors-with-parse-error-on-ci,"['php', 'phpunit', 'gitlab-ci']",1166,True,0,2
J-Unit JavaFX Tookit not Initialized,"<p>I wrote a few J-unit tests for a class I use in my JavaFX project. I am however, running into a ""Tookit not initialized"" again and again. I'm new to JavaFX and J-Unit testing, so I'm not sure where to look. </p>

<p>I edited the VM options from -ea to ""--module-path C:\Users\myName\Desktop\javafx-sdk-14.0.1\lib --add-modules javafx.controls,javafx.fxml"" in order to fix a No suitable pipeline found error. </p>

<p>This is my test class code:</p>

<pre><code>package HHS_PROJ1.models;

import javafx.scene.control.Button;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.*;

class AnimalTest {
private Animal animal;

@BeforeEach
void setUp() {
    animal = new Animal(5, ""Goat"", 32, 10, 0, new Button(""bid""));

}

@Test
void setHighestOffer() {
    try {
        animal.setHighestOffer(8);
        fail(""Entering a lower offer than current highestOffer should throw an exception"");
    } catch (IllegalArgumentException e) {
        System.out.println(""Caught lower offer than current highest in setHighestOffer(): "" + e.getMessage());
    } catch (Exception e) {
        fail(""Wrong exception thrown for entering a lower offer than the current highestOffer"");
    }
}

@Test
void setAmount() {
    try {
        animal.setAmount(-2);
        fail(""Entering a negative number should throw an exception"");
    } catch (IllegalArgumentException e) {
        System.out.println(""Caught negative number in setAmount(): "" + e.getMessage());
    } catch (Exception e) {
        fail(""Wrong exception thrown for entering a negative number"");
    }
}
}
</code></pre>

<p>I would like to be able to run my tests, to see if my code works as intended.</p>
",https://stackoverflow.com/questions/61851261/j-unit-javafx-tookit-not-initialized,"['javafx', 'junit5']",91,True,0,1
Springboot Mockito : Mocked service method returning null,"<p>I'm trying to test my springboot service using mockito but getting null response from my mocked service
The code compiles and also the service runs perfectly but test cases fail as mocked service returns null.</p>

<p>Service class</p>

<pre><code>
    @RestController
    @RequestMapping(path = ""/my-tracker"")
    public class MyTrackerController {

    private static final Logger logger = LoggerFactory.getLogger(MyTrackerController .class); 

    @Autowired
    private TrackerService trackerService;

    @RequestMapping(value = ""/track/{id}"", method = RequestMethod.GET, produces = ""application/json"")
    public String getTrackerDetails(@PathVariable(""id"") String id) 
        {

        String response = trackerservice.track(id);  // &lt;= this is returning null 

        return response;
        }

    }
</code></pre>

<p>Test Class</p>

<pre><code>    @RunWith(SpringRunner.class)
    @WebMvcTest(value = MyTrackerController.class)
public class MyTrackerControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private TrackerService trackerService ;

    @Test
    public void getTrackerDetailsTest() throws Exception {

        String response= ""MyLocation"";


        Mockito.when(
                trackerService.track(
                        Mockito.anyString())).thenReturn(response);


        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                ""/my-tracker/track/123"").accept(
                MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        System.out.println(result.getResponse());

        JSONAssert.assertEquals(response, result.getResponse()
                .getContentAsString(), true);
        }
    }
</code></pre>

<p>Any help / suggestions is highly appreciated.
Springboot version used : 2.3.0.RELEASE.</p>

<p>Blog referred for writing test case : <a href=""https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services"" rel=""nofollow noreferrer"">https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services</a></p>

<p>p.s. : I'am able to run test cases successfully from the above blog code but my mocked service is returning null. Also no additional jars added apart from spring-boot-starter-web and spring-boot-starter- test</p>
",https://stackoverflow.com/questions/61859577/springboot-mockito-mocked-service-method-returning-null,"['spring-boot', 'unit-testing', 'mockito', 'microservices']",552,False,0,1
How to send POST request multipart/form-data field as array for unit testing?,"<p>I'm trying to make unit testing for my Go application that handles form data in multipart/form-data content type using gin (PostForm and PostFormArray) like</p>
<p><code>x, y := c.PostForm(&quot;x&quot;), c.PostFormArray(&quot;y&quot;)</code></p>
<p>I have no problem on making a form field which have non-array value (PostForm) with mime/multipart library which Go provides like this</p>
<pre><code>buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)

x, _ := w.CreateFormField(&quot;x&quot;)
x.Write([]byte(&quot;This is x value&quot;))

w.Close()
</code></pre>
<p>which PostForm handles perfectly, now I'm wondering if there is any way to send a multipart/form-data field with an array as its value like <code>[]string{&quot;this is y 1&quot;, &quot;this is y 2&quot;}</code> for it to work with gin's PostFormArray. Is it possible and how do I do it? Any help would be greatly appreciated. Thanks in advance!</p>
",https://stackoverflow.com/questions/63357842/how-to-send-post-request-multipart-form-data-field-as-array-for-unit-testing,"['unit-testing', 'go', 'multipartform-data', 'go-gin']",1857,True,0,1
"Typescript Mocha Testing, How to solve TypeError: is not a function?","<p>Currently I have the following class:</p>
<pre><code>import * as winston from 'winston';
const { combine, timestamp, printf, label, json} = winston.format;
import {isEmpty, isNil} from 'lodash';
import {Log} from './Log';

export class LoggingService {
  public static initializeKeys() {
    
    this.keys = {tag: 'tag'};
  }

  public static intialize() {
    this.initializeKeys();
    const maskFormat = winston.format((meta) =&gt; {
      meta[this.keys.tag] = 'WebProxyConsumer';
      return meta;
    })();

    const jsonLog = printf((info) =&gt; {
      return JSON.stringify(info);
    });

    this.logger = winston.createLogger({
      level: 'info',
      format: combine(
        timestamp(),
        jsonLog
      ),
      transports: [
        new winston.transports.Console(),
        new winston.transports.File( { filename: 'error.log', level: 'error', maxsize: 10000000})
      ],
      exceptionHandlers: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'exceptions.log', maxsize: 10000000 })
      ]
    });
  }

  public static getDefaultLogger() {
    return this.logger;
  }

  public static error(error, label, data) {
    if (isNil(this.logger)) {
      LoggingService.intialize();
    }
    let logObj = new Log(null, null);
    logObj.level = 'error';

    if (!isNil(label)) {
      logObj.label = label;
    }
    if (!isNil(data)) {
      if (typeof data === 'string') {
        logObj.message = data;
      } else {
        Object.keys(data).forEach((key) =&gt; {
          const value = data[key];
          if (logObj.hasOwnProperty(key)) {
            logObj[key] = value;
          } else {
            logObj.data[key] = value;
          }
        });
      }
    }
    if (error instanceof Error) {
      if (error.hasOwnProperty('message')) {
        logObj.message += ' Error Message: ' + error.message;
      }
      if (error.hasOwnProperty('stack')) {
        logObj.error_stack = error.stack;
      }
    }
    if (typeof error === 'string') {
      logObj.message += ' Error Message: ' + error;
    }

    if (isNil(logObj.device_id)) {
      delete logObj.device_id;
    }
    if (isNil(logObj.data) || isEmpty(logObj.data)) {
      delete logObj.data;
    }
    this.logger.log(logObj);
  }

  public static info(data, label) {
    if (isNil(this.logger)) {
      LoggingService.intialize();
    }
    let logObj = new Log(null, null);
    if (!isNil(label)) {
      logObj.label = label;
    }
    if (!isNil(data)) {
      if (typeof data === 'string') {
        logObj.message = data;
      } else {
        Object.keys(data).forEach((key) =&gt; {
          const value = data[key];
          if (logObj.hasOwnProperty(key)) {
            logObj[key] = value;
          } else {
            logObj.data[key] = value;
          }
        });
      }
      if (isNil(logObj.device_id)) {
        delete logObj.device_id;
      }
      if (isNil(logObj.data) || isEmpty(logObj.data)) {
        delete logObj.data;
      }
      this.logger.log(logObj);
    }
  }

  private static logger: winston.Logger;

  private static keys: any;
}
</code></pre>
<p>I'm using mocha for unit testing and so far this is my unit test for the class:</p>
<pre><code>    describe('LoggingService Tests', () =&gt; {
    const loggingService = new LoggingService();
    const loggingServiceProto = Object.getPrototypeOf(loggingService);
    it('Checking LoggingService Initialization', () =&gt; {
        expect(loggingServiceProto).to.not.be.null;
        expect(loggingServiceProto.combine).to.not.be.null;
        expect(loggingServiceProto.timestamp).to.not.be.null;
        expect(loggingServiceProto.printf).to.not.be.null;
        expect(loggingServiceProto.logger).to.not.be.null;
        expect(loggingServiceProto.keys).to.not.be.null;
    })
    it('Checking initializeKeys', () =&gt; {
        expect(loggingServiceProto.initializeKeys()).to.not.be.null;
    })
    it('Checking initialize', () =&gt; {
        expect(loggingServiceProto.intialize()).to.not.be.null;
        expect(loggingServiceProto.logger).to.not.be.null;
    })
    it('Checking getDefaultLogger', () =&gt; {
        expect(loggingServiceProto.getDefaultLogger()).to.not.be.null;
    })
})
</code></pre>
<p>The importing for mocha is correct and for my first test <code>'Checking LoggingService Initialization'</code>, I'm successfully passing. That's to say I'm able to initialize my class without a problem. The problem is with the rest of the tests I'm running. For those, I get the following errors:</p>
<pre><code>TypeError: loggingServiceProto.initializeKeys is not a function
TypeError: loggingServiceProto.intialize is not a function
TypeError: loggingServiceProto.getDefaultLogger is not a function
</code></pre>
<p>Would anyone know why this is happening? These functions are defined and I'm not experiencing this issue with any other classes I'm testing using mocha.</p>
<p>Any advice would greatly be appreciated!</p>
",https://stackoverflow.com/questions/63064952/typescript-mocha-testing-how-to-solve-typeerror-is-not-a-function,"['node.js', 'typescript', 'mocha.js']",1125,False,0,1
Checking local variable while unit testing on a component in Angular gives error,"<p>Suppose there are 2 components : AppComponent and TestComponent. I am calling TestComponent using it's directive in the HTML template of AppComponent. Now TestComponent has an @Input() property ( let it be myTitle ).</p>

<p>I am doing unit testing for TestComponent only. For title, i am passing a random value in the test itself. Here is the code for the same :</p>

<p>app.component.html </p>

<pre><code>&lt;span&gt;&lt;app-test [myTitle]=""title""&gt;&lt;/app-test&gt;&lt;/span&gt;
</code></pre>

<p>app.component.ts</p>

<pre><code>@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent{
    title = {name: 'hello-world'};
}
</code></pre>

<p>test.component.html</p>

<pre><code>&lt;p&gt;test works!!{{myTitle.name}}&lt;/p&gt;
&lt;button (click)=""onClick()""&gt;Click Please !!!&lt;/button&gt;
</code></pre>

<p>test.component.ts</p>

<pre><code>@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit{
    @Input() myTitle;
    filter;
    constructor(){

    }

    ngOnInit():void{
        this.myTitle.name = ""Hi!!"";
    }
    onClick(){
       this.filter=""GokuSSj3"";
    }
}
</code></pre>

<p>test.component.spec.ts</p>

<pre><code>describe('Test component',() =&gt;{
    let temp;
    let component: TestComponent;
    let fixture: ComponentFixture&lt;TestComponent&gt;;

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

    beforeEach(()=&gt;{
        temp = {name: ""Heloooo""};
       fixture = TestBed.createComponent(TestComponent);
       component = fixture.componentInstance;
    });

    it('should check First',()=&gt;{
       component.myTitle = temp;
       console.log(component.myTitle.name);
       console.log(temp.name);

       fixture.detectChanges();

       console.log(component.myTitle.name);
       console.log(temp.name);
       expect(component.myTitle.name).toEqual(temp.name);
    });

    it('should check whether onClick is called on button click or not and also the value of filter',()=&gt;{
       component.myTitle = temp;
       spyOn(component,'onClick');
       fixture.detectChanges();

       let btn = fixture.debugElement.query(By.css('button'));
       btn.triggerEventHandler('click',null);

       fixture.whenStable().then(()=&gt;{
          expect(component.onClick).toHaveBeenCalled();
          expect(component.filter).toEqual(""GokuSSj3"");
    });
});
</code></pre>

<p>The second test case shows the error : Expected undefined to equal 'GokuSSj3'. Why is it so? Even though onClick has been called.</p>

<p>I am new to this community, so please help me improve the question if there are any fails.</p>
",https://stackoverflow.com/questions/61176688/checking-local-variable-while-unit-testing-on-a-component-in-angular-gives-error,"['angular', 'typescript', 'unit-testing']",3229,True,0,1
How to mock methods from private objects in a tested class,"<p>I have created an abstract class for a Rest client class for which I want to write unit tests.</p>
<p>I want to write tests for the <code>HandleRequest</code> method below but to be able to test certain situations I need to make sure that <code>_client.ExecuteTaskAsync</code> returns a certain value or throws an exception. The private object <code>_policy</code> however is created by <code>Mock&lt;IPollyPolicyFactory&gt;</code> and is <code>private</code> within the abstract class.</p>
<p>The code for the class in question looks like this:</p>
<pre><code>public abstract class AbstractRestClient
{
    private readonly IRestClient _client;
    private readonly IAsyncPolicy _policy;
    private readonly IRestRequestFactory _requestFactory;

    protected AbstractRestClient(RestSettings settings, IRestClientFactory restClientFactory, 
        IPollyPolicyFactory pollyPolicyFactory,
        IRestRequestFactory requestFactory)
    {
        _requestFactory = requestFactory;
        _client = restClientFactory.CreateRestClient(settings);
        _policy = pollyPolicyFactory.CreateAsyncResiliencePolicy(settings);
    }

    protected async Task&lt;T&gt; GetResult&lt;T&gt;(Url url) =&gt;
        await HandleRequest&lt;T&gt;(_requestFactory.CreateGetRequest(url));

    private async Task&lt;T&gt; HandleRequest&lt;T&gt;(IRestRequest request)
    {
        var result = await DoRequest&lt;T&gt;(request);
        if (result.FinalException != null)
        {
            throw result.FinalException;
        }

        if (!result.Result.IsSuccessful)
        {
            throw new HttpRequestException($&quot;Error executing request: {result.Result.StatusCode}; 
                {result.Result.StatusDescription}; {result.Result.ErrorMessage}&quot;);
        }

        return result.Result.Data;
    }

    private async Task&lt;PolicyResult&lt;IRestResponse&lt;T&gt;&gt;&gt; DoRequest&lt;T&gt;(IRestRequest request) =&gt;
        await _policy.ExecuteAndCaptureAsync(cancellationToken =&gt; _client.ExecuteTaskAsync&lt;T&gt; 
            (request, cancellationToken), Token);

    private static CancellationToken Token =&gt; new CancellationToken();
}
</code></pre>
<p>I have created a class for unit testing <code>AbstractRestClientTest</code> which uses an implementation class of <code>AbstractRestClient</code> called <code>MockRestClient</code>.
Right now my test class contains the following code:</p>
<pre><code>public class AbstractRestClientTest
{
    private AbstractRestClient _sut;
    private Mock&lt;IRestRequestFactory&gt; _requestFactoryMock;
    private Mock&lt;IRestClientFactory&gt; _restClientfactoryMock;
    private Mock&lt;IPollyPolicyFactory&gt; _policyFactoryMock;

    [SetUp]
    public void SetUp()
    {
        _requestFactoryMock = new Mock&lt;IRestRequestFactory&gt;();
        _restClientfactoryMock = new Mock&lt;IRestClientFactory&gt;();
        _policyFactoryMock = new Mock&lt;IPollyPolicyFactory&gt;();
        var settings = new MockSettings();

        _sut = new MockRestClient(settings, _restClientfactoryMock.Object, _policyFactoryMock.Object,
            _requestFactoryMock.Object);
    }

    [Test]
    public void HandleRequest_finalexception_not_null_then_throw_finalexception()
    {
        //How do I mock DoRequest throwing an FinalException?
    }
}

public class MockRestClient : AbstractRestClient
{
    public MockRestClient(RestSettings settings, IRestClientFactory restClientFactory, 
        IPollyPolicyFactory pollyPolicyFactory,
        IRestRequestFactory requestFactory) : base(settings, restClientFactory, pollyPolicyFactory, 
            requestFactory) {
    }
}
public class MockSettings : RestSettings
{
    public override string Naam =&gt; &quot;TestSettings&quot;;
}
</code></pre>
",https://stackoverflow.com/questions/63447896/how-to-mock-methods-from-private-objects-in-a-tested-class,"['c#', 'unit-testing', 'mocking']",431,True,0,1
What can be unit tested in this Java method involving pagination of data?,"<p>Beginner here at unit testing. Following is the method to be tested -</p>

<pre><code>public ListBeneficiaryResponseDTO getBeneficiaryOfMerchants(Long merchantId, Integer page, Integer pageSize,
                                                       String sortDirection, String sortField) {
        LOGGER.info(""Inside getBeneficiaryOfMerchants method"");

        // default we are setting to added on desc sort
        Sort sort = Sort.by(Sort.Direction.DESC,""addedOn"");
        if(sortField != null &amp;&amp; sortDirection != null) {
            sort = Sort.by(Sort.Direction.fromString(sortDirection),sortField);
        }

        Pageable pageRequest = PageRequest.of(page-1, pageSize, sort);
        Page&lt;Beneficiary&gt; pageOfBeneficiaries = beneficiaryRepository.findAllByMerchantId(merchantId, pageRequest);

        List&lt;BeneficiaryResponseDTO&gt; benResonseDtoList = new ArrayList&lt;BeneficiaryResponseDTO&gt;();

        for( Beneficiary ben: pageOfBeneficiaries.getContent()) {
            benResonseDtoList.add(this.getBeneficiaryResponseDTO(ben));
        }
        ListBeneficiaryResponseDTO formattedListBen = new ListBeneficiaryResponseDTO(pageOfBeneficiaries.getTotalPages(),pageOfBeneficiaries.getTotalElements(),pageOfBeneficiaries.getNumber(),benResonseDtoList);
        return formattedListBen;
    }
</code></pre>

<p>In order to write tests, I thought, what can this method do wrong, given the underlying method calls work fine.
Well, I am not sure, but may be some error in putting the elements into the list.</p>

<p>So, I thought writing a test to ensure that the expected number of elements are present in the list benResonseDtoList.</p>

<p>Following is what I tried -</p>

<pre><code>@Test
public void testGetBeneficiariesOfMerchant() throws Exception {

    Long merchantId = 2l;
    List&lt;Beneficiary&gt; beneficiaryList = new ArrayList&lt;Beneficiary&gt;();
    beneficiaryList.add(getBeneficiaryDto());
    beneficiaryList.add(getBeneficiaryDto());


    Page&lt;Beneficiary&gt; beneficiaries = new PageImpl&lt;Beneficiary&gt;(beneficiaryList); //But I am not sure how many entries are there in the page created.
Mockito.when(beneficiaryRepository.findAllByMerchantId(any(),any())).thenReturn(beneficiaries);
KeyManager keyManager = Mockito.mock(KeyManager.class);


ListBeneficiaryResponseDTO list = beneficiaryService.getBeneficiaryOfMerchants(merchantId,1,2, ""DESC"",""addedOn"");
</code></pre>

<p>If there were a clear correlation between the number of elements in beneficiaryList and the entries in pageOfBeneficiaries, I could test that.</p>
",https://stackoverflow.com/questions/61696189/what-can-be-unit-tested-in-this-java-method-involving-pagination-of-data,"['java', 'unit-testing', 'jpa', 'pagination', 'mockito']",347,False,0,1
Why can&#39;t I use an anonymous function inside jasmine&#39;s expectAsync?,"<p>I am trying to do unit testing in Jasmine for my Nodejs Mongoose models. Everything works unless I transfer the code from a function block to an anonymous / arrow function. I cannot understand why it does not work using anonymous / arrow functions.</p>
<p>Here is my basic spec file:</p>
<pre><code>const MongoDbTest = require('../lib/mongodb-tests.lib');
const Info = require(&quot;../models/info.model&quot;);

async function addTupleWithoutValue() {
  await new Info({ name: 'trududu' }).save();
}

describe(&quot;Le modèle Info&quot;, () =&gt; {
  const mongod = new MongoDbTest();

  beforeAll(async () =&gt; {
    await mongod.connect(); // This takes care of connecting to the database, etc.
  } );

  afterAll(async () =&gt; {
    await mongod.close(); // This takes care of closing the connection, etc.
  } );

  // ... other tests removed

  it(&quot;a absolument besoin du champ 'value'&quot;, async () =&gt; {
    await expectAsync(async function() {
      await new Info({ name: 'trududu' }).save();
    } ).toBeRejectedWithError(/value: Path `value` is required/); // This does not work

    await expectAsync(addTupleWithoutValue()).toBeRejectedWithError(/value: Path `value` is required/); // this works
  } );
} );
</code></pre>
<p>And here is my model:</p>
<pre><code>const mongoose = require('mongoose');
const Mixed = mongoose.Mixed;

const InfoSchema = new mongoose.Schema( {
  name: { type: String, unique: true },
  value: { type: Mixed, required: true }
} );

module.exports = mongoose.model('Info', InfoSchema);
</code></pre>
<p>When I use the anonymous function (or an arrow function), Jasmine give me the following error message: <code>Error: Expected toBeRejectedWithError to be called on a promise.</code> Looking at the source code for Jasmine, the value returned by a function is checked by <code>function(obj) { return !!obj &amp;&amp; j$.isFunction_(obj.then); }</code>. Does that mean that an anonymous function return a different kind of promise?</p>
",https://stackoverflow.com/questions/64583164/why-cant-i-use-an-anonymous-function-inside-jasmines-expectasync,"['javascript', 'node.js', 'unit-testing', 'mongoose', 'jasmine']",226,True,0,1
Postgres extension missing after upgrade,"<p>I have just upgraded my development postgres cluster from postgreSQL 9.6 to 11. Everything went fine except that I got an error around the pgtap extension that I use for unit testing.</p>
<p>Now when I try to restore a database I'm getting an error
&quot;ERROR: could not open extension control file &quot;/usr/share/postgresql/11/extension/pgtap.control&quot;</p>
<p>When I look in the file system I can see all the pgtap files are still in /usr/share/postgresql/9.6/extension.
I tried uninstalling pgtap running <code>sudo apt-get purge --auto-remove pgtap</code> and then re-installing but this hasn't worked, all the files are still in the 9.6 directory.</p>
",https://stackoverflow.com/questions/64123271/postgres-extension-missing-after-upgrade,"['postgresql', 'pgtap']",637,True,0,1
Why gcov is not covering logical &amp;&amp; operator?,"<p>My piece of code which I am doing unit testing on is something like this:</p>

<pre><code>     if(((State !=TCPIP_IPADDR_STATE_ASSIGNED)&amp;&amp; (State !=TCPIP_IPADDR_STATE_ONHOLD) &amp;&amp; (State !=TCPIP_IPADDR_STATE_UNASSIGNED)) ||(SoConId==DOIP_INVALID_16))
       {
        }
</code></pre>

<p>And my unit test case includes following :</p>

<pre><code>`DoIP_LocalIpAddrAssignmentChg(12,0xFF);`
</code></pre>

<p>Where DoIP_LocalIpAddrAssignmentChg is the function name in which if is located and 0xFF is for invalid state which is obviously not equal to all 3 : <strong>TCPIP_IPADDR_STATE_ASSIGNED</strong>, <strong>TCPIP_IPADDR_STATE_ONHOLD</strong>, <strong>TCPIP_IPADDR_STATE_UNASSIGNED</strong>. 
The value of <strong>SoConId</strong> is <strong>12</strong>. The value of <strong>DOIP_INVALID_16</strong> = <strong>0xFF</strong>.</p>

<p>So when I check my unit test report, its gives this result:
<img src=""https://i.stack.imgur.com/fC1rv.png"" alt=""code coverage for if condition"">
My question is why it's not covering condition for <strong>TCPIP_IPADDR_STATE_UNASSIGNED</strong> as value for state I am passing is <strong>0xFF</strong> which is invalid value.</p>
",https://stackoverflow.com/questions/61073843/why-gcov-is-not-covering-logical-operator,"['c', 'unit-testing', 'gcov', 'gcovr', 'ceedling']",194,True,0,1
Highcharts function not covered with unit tests with Karma + Jasmine,"<p>Since I'm trying to use your Highcharts package, I'm facing an issue when unit testing the component that use Highcharts function.</p>

<p>Here is my context:</p>

<p>I have a component (the only one) that use Highcharts. In the Web client, When I run unit test on this component, chart function legendItemClick not getting covered.</p>

<p>Code below are the Javascript transpilled code. Here is my original typescript file:</p>

<pre><code>let dsCapacityChartOptions = {
  chart: {
    type: 'pie',
    spacing: [0, 10, 2, 10],
    margin: [-10, 0, 30, 0]
  },
  title: {
    text: ''
  },
  credits: {
    enabled: false
  },
  plotOptions: {
    pie: {
      shadow: false,
      colors: ['#3E7BBF', '#CBCBCB', '#92B2D9'],
      point: {
        events: {
          legendItemClick: function () {
            return false;
          }
        }
      }
    },
    series: {
      states: {
        hover: {
          enabled: false
        },
        inactive: {
          opacity: 1
       }
      }
    }
  },
  tooltip: {
    outside: true,
    style: {
      color: '#000000',
      opacity: 1,
      fontSize: '12px',
      fontFamily: 'Metropolis,Avenir Next,Helvetica Neue,Arial,sans-serif'
    },
    formatter:
      function () {
        return '&lt;b&gt;' + this.point.x + '&lt;/b&gt;: ' + this.point.formattedCapacity + "" ("" + this.percentage.toFixed(2) + ""%)"";
      }
  },
  series: [{
    type: 'pie',
    name: this.labelsObj[""vsc.portlet.dsCapacity.label""],
    size: '80%',
    innerSize: '70%',
    showInLegend: true,
    dataLabels: {
      enabled: false
    },
    data: []

  }],
  legend: {
    labelFormatter: function () {
      return this.x + "": "" + this.formattedCapacity;
    },
    align: 'center',
    layout: 'vertical',
    itemStyle: {
      color: '#454545',
      fontWeight: '500',
      fontSize: '12px',
      fontFamily: 'Metropolis,Avenir Next,Helvetica Neue,Arial,sans-serif'
    },
    itemHoverStyle: {
      color: '#454545',
      cursor: 'default'
    }
  },
  exporting: { enabled: false }
};
</code></pre>

<p>Here is what I'm doing to make the unit tests works-</p>

<pre><code>it('should call legendItemClick', () =&gt; {
  let spy = spyOn(component.dsCapacityChartOptions.plotOptions.pie.point.events, 'legendItemClick')
  component.dsCapacityChartOptions.plotOptions.pie.point.events.legendItemClick();
  expect(spy).toHaveBeenCalledTimes(1);
})
</code></pre>

<p>Highcharts function not covered with unit tests with Karma + Jasmine</p>

<p>Please find below snippet of code coverage-
<a href=""https://i.stack.imgur.com/KVlrV.png"" rel=""nofollow noreferrer"">Code coverage</a></p>
",https://stackoverflow.com/questions/60393458/highcharts-function-not-covered-with-unit-tests-with-karma-jasmine,"['highcharts', 'karma-jasmine', 'angular8']",1004,True,0,1
Can you run JUnit Tests for a CLI application?,"<p>I am relatively new to unit tests in Java and I made an application completely with CLI. Example once starting the application the user is given a set of options like so.</p>

<ol>
<li>Register</li>
<li>Login
.
.
. Etc etc.</li>
</ol>

<p>If he choses to login he is transferred to a Register () method that asks for details such as name and surname inside the method itself.
I want to know if there is any way lf simulating user input when creating the unit tests or if I have to override the methods so that I can pass values through the arguments and do unit testing that way.</p>
",https://stackoverflow.com/questions/59625280/can-you-run-junit-tests-for-a-cli-application,"['java', 'unit-testing', 'junit']",53,True,0,1
ReferenceError: WebGLRenderingContext is not defined,"<p><strong>Context:</strong></p>
<p>I'm coding a personal WebGL Api using Typescript with Webpack. WebGL stuffs renders correctly in the browser.</p>
<blockquote>
<p>Everything is ok !</p>
</blockquote>
<p>Now, trying to create some unit tests following this setup with mocha :</p>
<p><a href=""https://journal.artfuldev.com/unit-testing-node-applications-with-typescript-using-mocha-and-chai-384ef05f32b2"" rel=""nofollow noreferrer"">Unit testing node applications with TypeScript — using mocha and chai</a></p>
<p><code>mocha --reporter list -r ts-node/register -r jsdom-global/register 'test/**/*.spec.ts'</code></p>
<p><a href=""https://i.stack.imgur.com/YZUto.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/YZUto.png"" alt=""Mocha result"" /></a></p>
<blockquote>
<p>Everything is also ok !</p>
</blockquote>
<p><strong>Problem :</strong></p>
<p>Until I try to test a code which references <code>WebGLRenderingContext</code>where the following error arise:</p>
<pre><code>   ReferenceError: WebGLRenderingContext is not defined
    at D:\JEROME\dev\repositories\experiment_typescript\webgl_api\src\webgl_objects\datas\webgl_enum_indexed.ts:7:34
    at Object.&lt;anonymous&gt; (D:\JEROME\dev\repositories\experiment_typescript\webgl_api\src\webgl_objects\datas\webgl_enum_indexed.ts:6:1)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Module.m._compile (D:\JEROME\dev\repositories\experiment_typescript\webgl_api\node_modules\ts-node\src\index.ts:837:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Object.require.extensions.&lt;computed&gt; [as .ts] (D:\JEROME\dev\repositories\experiment_typescript\webgl_api\node_modules\ts-node\src\index.ts:840:12)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
</code></pre>
<p><a href=""https://i.stack.imgur.com/Nubpp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Nubpp.png"" alt=""Mocha result"" /></a></p>
<blockquote>
<p>Breaking &gt; Not ok !</p>
</blockquote>
<p><strong>I don't understand how to make it works, any suggestion ?</strong> <br/></p>
<ul>
<li>Am I missing some way to link reference ? <br/></li>
<li>Should I investigate in another way of testing ?<br/></li>
</ul>
<br/>
<p><strong>Here is my configurations :</strong></p>
<p>package.json :</p>
<pre><code>  &quot;dependencies&quot;: {
    &quot;gl-matrix&quot;: &quot;^3.2.1&quot;,
    &quot;wasm-loader&quot;: &quot;^1.3.0&quot;,
    &quot;css-loader&quot;: &quot;^3.5.1&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/chai&quot;: &quot;latest&quot;,
    &quot;@types/html-webpack-plugin&quot;: &quot;^3.2.2&quot;,
    &quot;@types/jsdom&quot;: &quot;latest&quot;,
    &quot;@types/mocha&quot;: &quot;latest&quot;,
    &quot;@types/webgl2&quot;: &quot;~0.0.5&quot;,
    &quot;canvas&quot;: &quot;^2.6.1&quot;,
    &quot;chai&quot;: &quot;latest&quot;,
    &quot;clean-webpack-plugin&quot;: &quot;^3.0.0&quot;,
    &quot;copy-webpack-plugin&quot;: &quot;^5.1.1&quot;,
    &quot;del-cli&quot;: &quot;^3.0.0&quot;,
    &quot;file-loader&quot;: &quot;^6.0.0&quot;,
    &quot;html-webpack-plugin&quot;: &quot;^4.0.4&quot;,
    &quot;jsdom&quot;: &quot;16.3.0&quot;,
    &quot;jsdom-global&quot;: &quot;3.0.2&quot;,
    &quot;mocha&quot;: &quot;latest&quot;,
    &quot;prettier&quot;: &quot;^2.0.4&quot;,
    &quot;style-loader&quot;: &quot;^1.1.3&quot;,
    &quot;ts-loader&quot;: &quot;^6.2.2&quot;,
    &quot;ts-node&quot;: &quot;^8.8.1&quot;,
    &quot;webpack&quot;: &quot;^4.42.0&quot;,
    &quot;webpack-cli&quot;: &quot;^3.3.11&quot;,
    &quot;webpack-dev-server&quot;: &quot;^3.10.3&quot;,
    &quot;typescript&quot;: &quot;^3.8.3&quot;
  },
</code></pre>
<p>tsconfig.json :</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;outDir&quot;: &quot;./dist/&quot;,
    &quot;target&quot;: &quot;es5&quot;,
    &quot;module&quot;: &quot;commonjs&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;sourceMap&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;lib&quot;: [&quot;es2015&quot;, &quot;dom&quot;],
    &quot;typeRoots&quot;: [
      &quot;./node_modules/@types&quot;,
      &quot;./custom_typings&quot;,
    ],
    &quot;allowJs&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;resolveJsonModule&quot;: true,
    &quot;downlevelIteration&quot;: true
  },
  &quot;include&quot;: [
    &quot;./web/**/*&quot;,
    &quot;./src/**/*&quot;,
    &quot;./custom_typings&quot;,
    &quot;./node_modules/@types&quot;,
  ],
  &quot;exclude&quot;: [
    &quot;node_modules&quot;
  ],
  &quot;compileOnSave&quot;: false
}
</code></pre>
",https://stackoverflow.com/questions/63217172/referenceerror-webglrenderingcontext-is-not-defined,"['typescript', 'webpack', 'mocha.js', 'webgl']",632,True,0,2
How to get message from E11000 DuplicationKeyError?,"<p>So I am writing unittests for a project and I am testing <code>register()</code> function.</p>

<p>Here is it:</p>

<pre><code>def register():
    # Get information about user
    username = request.get_json().get(""username"")
    password = request.get_json().get(""password"")
    name = request.get_json().get(""name"")
    email = request.get_json().get(""email"")

    # Put information about user in a tuple
    values = (
        None, 
        username, 
        User.hash_password(password), 
        name,
        email,
        None
    )

    try:
        # Create user and update session
        User(*values).create()
        ActiveUser.logged_in = True
        ActiveUser.username = username
        info_log.info(""User %s registered successfully."" % username)

        return jsonify(success=True, message=""Registration successful!"")

    except pymongo.errors.DuplicateKeyError as e:
        # Catch pymongo exception
        return jsonify(success=False, message=""Duplicated username or email!""), 403
</code></pre>

<p>I want to have three tests: valid, invalid (duplicate username), invalid (duplicate email).</p>

<pre><code># Register helper function
def register(self, username, password, name, email):
    return self.app.post(
        ""/register"",
        data = json.dumps(dict(username = username, password = password, name = name, email = email)),
        content_type='application/json',
        follow_redirects = True
        )

def test_02_valid_user_registration(self):
    response = self.register('test', '12345678', 'Tester 1', 'test@mail.mail')
    self.assertEqual(response.status_code, 200)
    self.assertIn(b'Registration successful!', response.data)

def test_03_invalid_user_registration_duplicate_username(self):
    response = self.register('test', '12345678', 'Tester 2', 'test1@mail.mail')
    self.assertEqual(response.status_code, 403)
    self.assertIn(b'Duplicate username or email!', response.data)

def test_04_invalid_user_registration_duplicate_email(self):
    response = self.register('test2', '12345678', 'Tester 3', 'test@mail.mail')
    self.assertEqual(response.status_code, 403)
    self.assertIn(b'Duplicate username or email!', response.data)
</code></pre>

<p>As expected I get DuplicateKeyError, because I have set Unique for those parameters in the database.</p>

<pre><code>pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: user.users index: username_1 dup key: { username: ""test"" }
</code></pre>

<p>Is there a way to get which is the duplicated item from the DuplicateKeyError, so I can have separate unit tests for duplicate username and email?</p>

<blockquote>
  <p>I know this is more of a component/integration testing rather than unit testing, but this is the only way I know how to do it in Python 3.</p>
</blockquote>
",https://stackoverflow.com/questions/61499410/how-to-get-message-from-e11000-duplicationkeyerror,"['python', 'python-3.x', 'mongodb', 'flask', 'pymongo']",142,True,0,1
Webmock / RSpec - Net::HTTP - How to assert that read_timeout and open_timeout have been set on Net::HTTP instance in method,"<p>I am new rspec and webmock user!</p>
<p>I am setting the read and open timeout values for a Net::HTTP instance in a method that I am unit testing:</p>
<pre class=""lang-rb prettyprint-override""><code>https = Net::HTTP.new(uri.host, uri.port)
https.open_timeout = timeout #set the timeout from method parameters
https.read_timeout = timeout

# make request etc.
</code></pre>
<p>I am using webmock to mock the request to an external api.</p>
<p>How do I check that the <em>open_timeout</em> and <em>read_timeout</em> properties have been set on the Net::HTTP instance?</p>
<p>I have tried the following in my unit test:</p>
<pre class=""lang-rb prettyprint-override""><code>it &quot;accepts custom timeout period&quot; do
    yamlContent = &quot;image: ruby:latest&quot;
    expectedTimeout = 5
    allow(YAML).to receive(:load_file).with(@fileName).and_return(yamlContent)

    mockHttps = instance_double(Net::HTTP)
    stub_request(:post, @endpointUrl).to_timeout
    
    expect do
        api = Gitlab::Lint::Client::Api.new
        response = api.lint(@endpointUrl, @fileName, @defaultHeaders, expectedTimeout)    
    end.to raise_error(Net::OpenTimeout)

    expect(mockHttps.read_timeout).to eq(expectedTimeout)
    expect(mockHttps.open_timeout).to eq(expectedTimeout)
end
</code></pre>
<p>This uses webmock to simulate a timeout and I see that a timeout error is indeed being raised. However, I <em>read_timeout</em> is an unrecognised property for the <em>mockHttps</em> double:</p>
<pre class=""lang-sh prettyprint-override""><code>   Failure/Error: expect(mockHttps.read_timeout).to eq(expectedTimeout)
       #&lt;InstanceDouble(Net::HTTP) (anonymous)&gt; received unexpected message :read_timeout with (no args)
     # ./spec/gitlab/lint/client/api_spec.rb:83:in `block (4 levels) in &lt;top (required)&gt;'
</code></pre>
",https://stackoverflow.com/questions/62861551/webmock-rspec-nethttp-how-to-assert-that-read-timeout-and-open-timeout-h,"['rspec', 'webmock']",374,False,0,0
Can we use TestBed for services with NativeScript?,"<p>I'm writing an app with NativeScript 6+ and Angular 8+.
I'm trying to write some unit tests and get them up and running.
I have read the documentation on unit testing: <a href=""https://docs.nativescript.org/tooling/testing/testing"" rel=""nofollow noreferrer"">https://docs.nativescript.org/tooling/testing/testing</a>
I've got some unit tests up and running with plain services.
e.g.</p>

<pre><code>import { ItemService } from '../app/item/item.service';

describe('ItemsService Test', () =&gt; {

    let service: ItemService;

    beforeEach(() =&gt; { service = new ItemService(); });

    it('should be defined',() =&gt; {
        expect(service).toBeTruthy();
    });

    it('should have its functions defined',() =&gt; {
        expect(service.getItems).toBeTruthy();
        expect(service.getItem).toBeTruthy();
    });

});
</code></pre>

<p>I see that we can test Services with dependencies by instantiating them in the constructors and with mock services as well. 
<a href=""https://angular.io/guide/testing#service-tests"" rel=""nofollow noreferrer"">https://angular.io/guide/testing#service-tests</a></p>

<p>Is it possible to use TestBed for our services in NativeScript? If so, can you provide an eample of how to do that?</p>
",https://stackoverflow.com/questions/60737607/can-we-use-testbed-for-services-with-nativescript,"['angular', 'unit-testing', 'nativescript', 'karma-jasmine']",135,True,0,2
Mock/Change value of external function pointer variable,"<p>I am trying to mock function pointers from an external library for unit-testing for now with <a href=""https://github.com/meekrosoft/fff"" rel=""nofollow noreferrer"">FFF (Fake Function Framework)</a> but other suggestions are also welcome.</p>
<pre class=""lang-c++ prettyprint-override""><code>//lib.h

...
typedef INT64 (__stdcall *fptr_lib_function) (LONG nItemID, 
    LONG nInfoType, LPBOOL lpSuccess); 
...
extern fptr_lib_function lib_function;
...
</code></pre>
<pre><code>//lib.cpp:

...
fptr_lib_function lib_function;
...
LONG __stdcall RetrieveFunctionPointers()
{
    ...
    lib_function = (fptr_lib_function) GetProcAddress(Hdl, &quot;lib_function&quot;);
    ...
}

</code></pre>
<p>Regardless of what I'm doing, I either get a SEGVAULT, meaning the function was not mocked or a linker error &quot;Multiple definitions&quot;. The example below is throwing a SEGVAULT.</p>
<pre class=""lang-c++ prettyprint-override""><code>// myfile.h

#ifndef MYFILE_H
#define MYFILE_H
bool some_other_function_calling_lib_function();
#endif
</code></pre>
<pre><code>// myfile.cpp

#include &quot;subfolder/lib.cpp&quot;

bool some_other_function_calling_lib_function() {
    bool success = false;
    int result = lib_function(1, 1, &amp;success);
    return result &lt; 0;
}
</code></pre>
<pre><code>// myfile.test.cpp

#include &lt;fff/fff.h&gt;
#include &quot;myfile.h&quot;

FAKE_VALUE_FUNC(INT64, lib_function, LONG, LONG, LPBOOL);

TEST(&quot;My_Test&quot;) {
    lib_function_fake.return_val = -1;
    ASSERT(some_other_function_calling_lib_function());
}
</code></pre>
<p>I have the following structure and compile commands:</p>
<pre class=""lang-none prettyprint-override""><code>&lt;root&gt; &lt;- Execute compile commands here
  |- external
        | - xwf
        |    | - myfile.cpp
        |    | - myfile.test.cpp
        |    | - myfile.h
        |    | - subfolder
        |          | - lib.h
        |          | - lib.cpp
        | - fff
             | - fff.h

g++ -I external -std=c++17 -DUNICODE -D_UNICODE -DSTRICT -DNOMINMAX -DDEBUG -c -MMD -MP -MF build/xwf/myfile.test.d -o build/xwf/myfile.test.o external/xwf/myfile.test.cpp
# rinse and repeat for all the other files.

g++ -I external -std=c++17 -DUNICODE -D_UNICODE -DSTRICT -DNOMINMAX -DDEBUG -ggdb3 -DDEBUG build/test.o build/xwf/myfile.test.o build/xwf/subfolder/lib.o -o build/test.exe
</code></pre>
<p>Basically the only idea I came up with is replacing the entire <code>lib.cpp</code> file with my own implementation for the tests. Is this what I have to do or are there other solutions?</p>
",https://stackoverflow.com/questions/65140502/mock-change-value-of-external-function-pointer-variable,"['c++', 'c', 'unit-testing', 'mocking']",472,True,0,1
Using Patched Method to get called arguments?,"<p>I was doing some unit testing against database calls, I was essentially doing a patch for cursors.  The issue I was having is that I want to patch the return variable but also check what the arguments are in order to ensure they are valid.</p>
<p>Is this possible?  I was going through the documents but didnt anything other than <code>side_effect</code> and <code>return_value</code>.</p>
<p>I mostly was flipping through the docs at: <a href=""https://docs.python.org/3/library/unittest.mock.html"" rel=""nofollow noreferrer"">https://docs.python.org/3/library/unittest.mock.html</a></p>
<p>Since patch is a wrapper for mock, when looking at the Mock class, I was thinking there might be something else there which could prove useful.</p>
",https://stackoverflow.com/questions/64125329/using-patched-method-to-get-called-arguments,"['python', 'python-3.x', 'python-unittest']",40,False,0,1
Test a RichCoFlatMapFunction in Apache Flink,"<p>i'm trying to test a RichCoFlatMapFunction that i'm using to make a left join of two streams it is something like this:</p>

<pre class=""lang-java prettyprint-override""><code>    private ValueState&lt;Card&gt; currentValueState;
    private ListState&lt;Card&gt; historicListState;

    @Override
    public void open(Configuration parameters) throws Exception {
        currentValueState = getRuntimeContext().getState(new ValueStateDescriptor&lt;&gt;(""Current State"", Card.class));
        historicListState = getRuntimeContext().getListState(new ListStateDescriptor&lt;&gt;(""historic state"", Card.class));
    }

    @Override
    public void flatMap1(Card currentCard, Collector&lt;Tuple2&lt;Card, List&lt;Card&gt;&gt;&gt; out) throws Exception {
        Iterable&lt;Card&gt; historicCardList =  historicListState.get();
        if (Iterables.size(historicCardList) &gt; 0) {
            out.collect(new Tuple2&lt;&gt;(currentCard, Lists.newArrayList(historicCardList) ));
        } else {
            currentValueState.update(currentCard);
            out.collect(new Tuple2&lt;&gt;(currentCard, null));
        }
    }

    @Override
    public void flatMap2(Card historicCard, Collector&lt;Tuple2&lt;Card, List&lt;Card&gt;&gt;&gt; out) throws Exception {
        historicListState.add(historicCard);
    }
</code></pre>

<p>In the Method flatMap1 i'm returning a null when a historic Card is not found</p>

<pre><code>out.collect(new Tuple2&lt;&gt;(currentCard, null));
</code></pre>

<p>The problem is that when i'm trying to test this whole functionality i'm receiving this error:</p>

<blockquote>
  <p>Automatic type extraction is not possible on candidates with null values. Please specify the types directly.</p>
</blockquote>

<p>This is how i'm trying to test the richCoFlatMapFunction</p>

<pre class=""lang-java prettyprint-override""><code>    @Test
    public void testFlatMap() throws Exception {
        final Card current = currentCard(2L);
        final Card historic = historicCard(2L);
        final List&lt;Card&gt; historicList = new ArrayList&lt;&gt;();
        historicList.add(historic);
        CoStreamFlatMap&lt;Card, Card, Tuple2&lt;Card, List&lt;Card&gt;&gt;&gt; operator = new CoStreamFlatMap&lt;&gt;(new LeftJoin());
        KeyedTwoInputStreamOperatorTestHarness&lt;Long, Card, Card, Tuple2&lt;Card, List&lt;Card&gt;&gt;&gt; testHarness =
                new KeyedTwoInputStreamOperatorTestHarness&lt;&gt;(
                        operator,
                        (Card c) -&gt; c.getCardHash(),
                        (Card h) -&gt; h.getCardHash(),
                        BasicTypeInfo.LONG_TYPE_INFO);
        testHarness.setup();
        testHarness.open();
        testHarness.processElement1(new StreamRecord&lt;&gt;(current));
        testHarness.processElement2(new StreamRecord&lt;&gt;(historic));
        ConcurrentLinkedQueue&lt;Object&gt; expectedOutput = new ConcurrentLinkedQueue&lt;&gt;();
        expectedOutput.add(new StreamRecord&lt;&gt;(new Tuple2&lt;&gt;(current, historicList)));
        // Check that the result is correct
        ConcurrentLinkedQueue&lt;Object&gt; actualOutput = testHarness.getOutput();
        TestHarnessUtil.assertOutputEquals(""Output was not correct."", expectedOutput, actualOutput);
    }
</code></pre>

<p>Any help would me much appreciated, i'm kinda new on Apache Flink and Unit Testing with it
Thanks.</p>
",https://stackoverflow.com/questions/61001261/test-a-richcoflatmapfunction-in-apache-flink,"['testing', 'apache-flink', 'flink-streaming']",744,True,0,1
Unit testing supposed to be &quot;passed&quot;? Why is it failing?,"<pre><code>  function renderInventory(inventory) {
  //create a flat list
  var flatList = '';
  //iterate over the inventory
  for (var i = 0; i &lt; inventory.length; i++) {
    var designerObject = inventory[i];
    var shoes = designerObject.shoes;
    //iterate over the each shoe in the array
    for (var j = 0; j &lt; shoes.length; j++) {
      var currentShoe = shoes[j];
      //add the designer name, the shoe name, and the shoe price and the new line
      flatList = designerObject.name +"", "" + currentShoe.name +"", "" + currentShoe.price + '\n';
    } 
  }
  //return the flat list
  return flatList;
}
//assertion Function
function assertEqual(actual, expected, testName) {
  if (actual === expected) {
  console.log('passed');
  } else {
  console.log('FAILED [' + testName + '] Expected ""' + expected + '"", but got ""' + actual + ""'"");
  }
}

//test cases

var currentInventory = [{
    name: 'Brunello Cucinelli',
    shoes: [
      {name: 'tasselled black low-top lace-up', price: 1000},
      {name: 'tasselled green low-top lace-up', price: 1100},
      {name: 'plain beige suede moccasin', price: 950},
      {name: 'plain olive suede moccasin', price: 1050}
    ]
  },
  {
    name: 'Gucci',
    shoes: [
      {name: 'red leather laced sneakers', price: 800},
      {name: 'black leather laced sneakers', price: 900}
    ]
  }
];

var actualFlatList = renderInventory(currentInventory);

var expectedFlatList = 'Brunello Cucinelli, tasselled black low-top lace-up, 1000\nBrunello Cucinelli, tasselled green low-top lace-up, 1100\nBrunello Cucinelli, plain beige suede moccasin, 950\nBrunello Cucinelli, plain olive suede moccasin, 1050\nGucci, red leather laced sneakers, 800\nGucci, black leather laced sneakers, 900\n';

assertEqual(actualFlatList, expectedFlatList, ""should render flat list of inventory items"");
</code></pre>

<p><strong>Result:</strong> 
FAILED [should render flat list of inventory items] Expected ""Brunello Cucinelli, tasselled black low-top lace-up, 1000
Brunello Cucinelli, tasselled green low-top lace-up, 1100
Brunello Cucinelli, plain beige suede moccasin, 950
Brunello Cucinelli, plain olive suede moccasin, 1050
Gucci, red leather laced sneakers, 800
Gucci, black leather laced sneakers, 900
"", but got ""Gucci, black leather laced sneakers, 900
'</p>

<p>I tried to add my code properly. Hopefully, I did it right. I'm a newbee in coding. My question is, this unit testing code block supposed to give <strong>'passed'</strong>. Where did I do wrong? Can someone clarify it please.</p>
",https://stackoverflow.com/questions/61112183/unit-testing-supposed-to-be-passed-why-is-it-failing,"['javascript', 'unit-testing', 'tdd']",42,True,0,1
Micronaut declarative client in grails: how do I mock it?,"<p>What is the correct way to mock a declarative REST client when unit testing a Grails service?</p>

<p><strong>Details</strong></p>

<p>I am using Micronaut's declarative HTTP client in my Grails 4 app.</p>

<p>I tried to unit test the client using Ersatz, but I couldn't get it working after several days:
<a href=""https://stackoverflow.com/questions/60782601/how-do-i-configure-micronaut-client-in-a-grails-test-environment"">How do I configure Micronaut @Client in a grails test environment?</a></p>

<p>Now, I'm trying to unit test a service that uses it, using the standard approach for mocking dependencies:</p>

<pre><code>class MyServiceSpec extends Specification implements
        ServiceUnitTest&lt;MyService&gt; {

    MyRestClient myRestClient = Mock()

    def setup() {
        service.myRestClient = myRestClient
    }
    ...
}
</code></pre>

<p>This gives me a <code>NoSuchBeanDefinitionException</code>.</p>

<p>I have found through trial and error that declarative client does not work with <code>def myRestClient</code>, like other Grails beans. It <em>must</em> be <code>@Autowired</code>.</p>

<pre><code>    at org.grails.testing.GrailsUnitTest$Trait$Helper.defineBeans(GrailsUnitTest.groovy:99)
    at grails.testing.services.ServiceUnitTest$Trait$Helper.mockArtefact(ServiceUnitTest.groovy:58)
    at org.grails.testing.ParameterizedGrailsUnitTest$Trait$Helper.getArtefactInstance(ParameterizedGrailsUnitTest.groovy:48)
    at grails.testing.services.ServiceUnitTest$Trait$Helper.getService(ServiceUnitTest.groovy:85)
    at com.mycompany.MyServiceSpec.setup(MyServiceSpec.groovy:##)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.MyRestClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1662)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1221)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
    ... 15 more
</code></pre>
",https://stackoverflow.com/questions/60980883/micronaut-declarative-client-in-grails-how-do-i-mock-it,"['unit-testing', 'grails', 'micronaut', 'grails-4', 'micronaut-client']",465,False,0,1
testthat (&amp; Catch) complains in R CMD check that xml2 library is missing,"<p>I am using testthat to test my R package (<a href=""https://github.com/beerda/hexmatrix"" rel=""nofollow noreferrer"">https://github.com/beerda/hexmatrix</a>). Recently, I started C++ testing: I have executed <code>testthat::use_catch()</code>, which should setup the package for unit testing with C++ Catch, and then I wrote some tests. The tests run correctly if executed by <code>devtools::test()</code>. However, if I try to run <code>R CMD check</code> or <code>devtools::check()</code>, I get the following error message:</p>
<pre><code>    Running ‘testthat.R’ (1.8s)
   Running the tests in ‘tests/testthat.R’ failed.
   Last 13 lines of output:
     &gt; test_check(&quot;hexmatrix&quot;)
     ── Error (test-cpp.R:1:1): (code run outside of `test_that()`) ─────────────────
     Error: The xml2 package must be installed in order to use `run_cpp_tests()`
     ℹ Do you need to run `install.packages('xml2')`?
     Backtrace:
         █
      1. └─testthat::run_cpp_tests(&quot;hexmatrix&quot;) test-cpp.R:1:0
      2.   └─testthat:::check_installed(&quot;xml2&quot;, &quot;run_cpp_tests()&quot;)
     
     ══ testthat results  ═══════════════════════════════════════════════════════════
     Error (test-cpp.R:1:1): (code run outside of `test_that()`)
     
     [ FAIL 1 | WARN 0 | SKIP 0 | PASS 909 ]
     Error: Test failures
     Execution halted
</code></pre>
<p>The xml2 package is installed, rlang::check_installed(&quot;xml2&quot;) returns TRUE.</p>
<p>Not sure if it is somehow connected: when I try to execute manually the command <code>run_cpp_tests(&quot;hexmatrix&quot;)</code>, I get the following error:</p>
<pre><code>Error in read_xml.raw(charToRaw(enc2utf8(x)), &quot;UTF-8&quot;, ..., as_html = as_html,  : 
  XML declaration allowed only at the start of the document [64]
</code></pre>
<p>Does please anybody have the idea what is going wrong? Thanks, in advance.</p>
",https://stackoverflow.com/questions/64704615/testthat-catch-complains-in-r-cmd-check-that-xml2-library-is-missing,"['c++', 'r', 'testthat', 'catch2']",750,True,0,2
How to use initialize a service in a controller during unit testing in grails?,"<p>I'm starting with unit testing in <strong>Grails 3.3.8</strong>, I have the <strong>ControllerSpec</strong>:</p>

<pre><code>class FooControllerSpec extends Specification implements ControllerUnitTest&lt;FooController&gt; {

      void ""test index""() {
        given:
        controller.fooService = new FooServiceImplementation()

        when:
        controller.index()

        then:
        response.json
        status == 200
      }

      void ""test show""() {
        given:
        controller.fooService = new FooServiceImplementation()

        when:
        params['id'] = '000001400'
        controller.show()

        then:
        status == 200
      }
    }
</code></pre>

<p><strong>FooService</strong> is an interface, does not have implementation.</p>

<pre><code>@Service(Foo)
interface FooService {
Foo get(Serializable id)

List&lt;Foo&gt; list(Map args)
}
</code></pre>

<p>I create a <strong>FooServiceImplementation</strong> like this:</p>

<pre><code>class FooServiceImplementation implements FooService {
 Foo get(Serializable id) {/*implementation here*/}

    List&lt;Foo&gt; list(Map args) {/*implementation here*/}
}
</code></pre>

<p>This actually works, but there is another form to initialize the service in my controller?
I want to use the FooService exactly with the implementation that grails would compile when injecting the service into the controller, this to make sure that the results during the execution will be the same as during the testing, since my FooServiceImplementation could generate different results, although I suppose you should write the implementation correctly.</p>
",https://stackoverflow.com/questions/60934184/how-to-use-initialize-a-service-in-a-controller-during-unit-testing-in-grails,"['grails', 'spock']",78,False,0,0
Angular: How to Get Private Methods into Code Coverage?,"<p>Is there anyway to add Private Methods from <code>ng test --code-coverage</code> into Code Coverage Reports in Angular 8?</p>
<p>Our Ng TestCode Coverage is low percentage, since its checking private methods.</p>
<p>According to articles, private methods should not require unit testing. Only the Public methods, which call private methods need to.</p>
<p>*Reading about tags; if any method is prefixed with <code>public</code>, it should be unit tested. Team can also start placing <code>private</code> before methods. Would this method allow ng test to find what requires testing?</p>
<p><a href=""https://softwareengineering.stackexchange.com/questions/100959/how-do-you-unit-test-private-methods"">https://softwareengineering.stackexchange.com/questions/100959/how-do-you-unit-test-private-methods</a></p>
<p><a href=""https://anthonysciamanna.com/2016/02/14/should-private-methods-be-tested.html#:%7E:text=Unit%20Tests%20Should%20Only%20Test,are%20dependent%20on%20the%20object"" rel=""noreferrer"">https://anthonysciamanna.com/2016/02/14/should-private-methods-be-tested.html#:~:text=Unit%20Tests%20Should%20Only%20Test,are%20dependent%20on%20the%20object</a>.
<a href=""https://i.stack.imgur.com/zodyH.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/zodyH.png"" alt=""enter image description here"" /></a></p>
<p>Currently testing Typescript in Angular 8.</p>
",https://stackoverflow.com/questions/62644324/angular-how-to-get-private-methods-into-code-coverage,"['angular', 'typescript', 'karma-jasmine', 'angular8']",1923,True,10,2
Firestore SDK cannot mock DocumentSnapshot,"<p>So I am trying to create a unit test for a firestore trigger, triggered by an <code>onCreate</code> event. The firebase documentation said to do this as so: <a href=""https://firebase.google.com/docs/functions/unit-testing#constructing_test_data"" rel=""nofollow noreferrer"">Firebase Unit Testing Background Functions</a></p>

<p>I copy the documentation pretty closely:</p>

<pre><code>const snapshot = test.firestore.makeDocumentSnapshot(
    {owner: 'testUserA', text: 'response from test user a'}, 
    'users/testUserA/questions/testQuestion/responses/testResponse'
);
</code></pre>

<p>This line gives the error:</p>

<blockquote>
  <p>UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token u in JSON at position 0</p>
</blockquote>

<p>At first I thought it might have to do with the <code>refPath</code> because it starts with u, but after changing it, the error is identical, so I assume it has to do with the first parameter, which seems like correct json, but apparently not. I'm kind of stumped.</p>

<p>Any ideas? Thanks!</p>
",https://stackoverflow.com/questions/61093595/firestore-sdk-cannot-mock-documentsnapshot,"['javascript', 'firebase', 'unit-testing', 'google-cloud-firestore', 'mocha.js']",815,True,0,1
Vue scss style loads fails with mocamapck,"<p>I'm having a problem when unit testing a vue single file component with some scss styling, as it is unable to process the @import statements. It works when I run launch the app using <code>yarn run dev</code> or build for production <code>yarn run build</code>, issue is only with unit test mode, and my setup uses <code>mochapack</code> to run the webpack before executing the test. </p>

<pre><code> WEBPACK  Compiling...

  [=========================] 98% (after emitting)

 ERROR  Failed to compile with 1 errors

 error  in ./src/components/WorkTrigger.vue?vue&amp;type=style&amp;index=0&amp;lang=scss&amp;

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
  ╷
1 │ @import 'themes/default/variables';
  │         ^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  home/xxxxx/src/styles/main.scss 1:9  @import
  /home/xxxxx/src/components/WorkTrigger.vue 39:9                                             root stylesheet

 @ ./node_modules/vue-style-loader??ref--9-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--9-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--9-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--9-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/WorkTrigger.vue?vue&amp;type=style&amp;index=0&amp;lang=scss&amp; 4:14-442
 @ ./src/components/WorkTrigger.vue?vue&amp;type=style&amp;index=0&amp;lang=scss&amp;
 @ ./src/components/WorkTrigger.vue
 @ ./tests/unit/WorkTrigger.spec.ts
 @ ./node_modules/mochapack/lib/entry.js

Type checking in progress...
  [=========================] 100% (completed)

 WEBPACK  Failed to compile with 1 error(s)

Error in ./src/components/WorkTrigger.vue?vue&amp;type=style&amp;index=0&amp;lang=scss&amp;

  Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
  SassError: Can't find stylesheet to import.
    ╷
  1 │ @import 'themes/default/variables';
</code></pre>

<p>Any ideas on how may this be resolved. I don't need to load scss for testing, although I'm unable to disable style processing (null-loader) as I do not have a webpack.config file in the project, and I would not create one unless absolutely necessary. Project is generated with Vue CLI.</p>
",https://stackoverflow.com/questions/61329697/vue-scss-style-loads-fails-with-mocamapck,"['vue.js', 'webpack', 'node-sass', 'sass-loader', 'mochapack']",912,True,4,1
Verifying method calls on lambda with Mockito,"<p>I'm trying to verify and capture the arguments of some method calls within a lambda expression as so:</p>

<pre><code>public Optional&lt;UserDetails&gt; findOne(String userName) {
    String selectStatement =
        ""SELECT * FROM users WHERE userName = :userName;"";

    return jdbi.withHandle(handle -&gt; handle
            .createQuery(selectStatement)
            .bind(""userName"", userName)
            .map(new UserDetailsMapper())
            .findOne());
  }
</code></pre>

<p><code>jdbi.withHandle()</code> takes an argument of <code>HandleCallBack</code>, which looks like this:</p>

<pre><code>public interface HandleCallback&lt;T, X extends Exception&gt; {
  T withHandle(Handle handle) throws X;
}
</code></pre>

<p>For example, I want to verify that <code>.bind()</code> has been called with <code>""userName""</code> and the passed in <code>userName</code> argument string from my <code>findOne</code> method.</p>

<p>It does feel like I'm unit testing the Jdbi class rather than my own class, but I feel like the arguments to <code>.createQuery()</code> <code>.bind()</code> and <code>.map()</code> should be tested as these could be accidentally changed by a developer. </p>

<p>The approach I've currently taken is to create an in-memory database and test what is actually being returned, but this feels more like an integration test than a unit test. I also don't really care what is actually returned by the Jdbi <code>.withHandle()</code> method, as I would essentially be testing a library at that point. </p>

<p>My understanding is that I should be unit testing the arguments passed to <code>.withHandle()</code> (in this case, a lambda expression), which is what I'm trying to do here.</p>

<p>The closest I got was by moving the logic into a method reference, but that won't work as <code>userName</code> is passed into my <code>findOne()</code> method and then used inside the lambda.</p>

<p>I've also played around with Mockito's <code>doAnswer</code> to no avail.</p>

<p>I can only think of creating a new class with helper methods to return <code>userName</code>, <code>selectStatement</code>, etc, and verify that they are called, but it feels unnecessary and will be added simply to provide testability.</p>
",https://stackoverflow.com/questions/60265003/verifying-method-calls-on-lambda-with-mockito,"['java', 'unit-testing', 'lambda', 'junit', 'mockito']",416,False,0,2
Test suite failed to run / jest.mock(),"<p>Initially, the client side (TypeScript) of our web application did not write unit test code. This time, only the input parts of the existing screens are re-creating now. We are adding new input components and switching existing screens to use new input components.
For the first time, we plan to write unit test code and conduct unit tests for the newly added new input component classes.</p>
<p>The existing screen classes (before introducing Jest) was implemented by the classes with namespace as follows.
[with namespace(aaa.bbb.ccc.~), <strong>don't export namespace</strong>, export class, <strong>import class(specified namespace)</strong>]</p>
<pre><code>// Entry1.ts : The existing screen class
module aaa.bbb.ccc.ddd.eee {
    import AlertDialog = aaa.bbb.ccc.overlaycomponent.AlertDialog;
    export class Entry1 {
        private alertDialog: AlertDialog;
    }
}
</code></pre>
<p>Since unit testing cannot be performed with Jest in the above implementation, the following implementation is used for the newly added input component classes that performs unit testing with Jest.
[with namespace(aaa.bbb.ccc.~), <strong>export namespace</strong>, export class, <strong>import namespace(specified file path)</strong>]</p>
<pre><code>// zGrid.ts : The newly added input component class 1
import { aaa as aaa1 } from './zRow';
import ZRow = aaa1.bbb.ccc.controls.zGrid.ZRow;

export module aaa.bbb.ccc.controls.zGrid {
    /** Zeta Grid */
    export class ZGrid {
        private rows: ZRow[];
        constructor() {
            this.rows = [new ZRow(), new ZRow(), new ZRow()];
        }
        public getCount(): number {
            let total: number = 0;
            this.rows.forEach((value: ZRow, index: number, array: ZRow[]) =&gt; {
                total += value.getColCount();
            }, this);
            return total;
        }
    }
}
</code></pre>
<pre><code>// zRow.ts : The newly added input component class 2
import { aaa as aaa1 } from './zColumn';
import ZColumn = aaa1.bbb.ccc.controls.zGrid.ZColumn;

export module aaa.bbb.ccc.controls.zGrid {
    /** Zeta Grid Row */
    export class ZRow {
        private cols: ZColumn[];
        constructor() {
            this.cols = [new ZColumn(), new ZColumn()];
        }
        public getColCount(): number {
            return this.cols.length;
        }
    }
}
</code></pre>
<p>Q 1</p>
<p>Unit test code (without Mock) works fine.</p>
<pre><code>// zGrid.test.ts : (for the newly added input component class 1 : zGrid.ts)
import { mocked } from 'ts-jest/utils';

import { aaa as aaa1 } from './zGrid';
import ZGrid = aaa1.bbb.ccc.controls.zGrid.ZGrid;
import { aaa as aaa2 } from './zRow';
import ZRow  = aaa2.bbb.ccc.controls.zGrid.ZRow;

describe(&quot;case1&quot;, () =&gt; {
    it(&quot;pat1&quot;, () =&gt; {
        let grid = new ZGrid();
        expect(grid.getCount()).toBe(6);
    });
});
</code></pre>
<p>Unit test code (with Mock) works too. (Test suite ran.)</p>
<pre><code>// zGrid.test.ts : (for the newly added input component class 1 : zGrid.ts)
import { mocked } from 'ts-jest/utils';

import { aaa as aaa1 } from './zGrid';
import ZGrid = aaa1.bbb.ccc.controls.zGrid.ZGrid;
import { aaa as aaa2 } from './zRow';
import ZRow  = aaa2.bbb.ccc.controls.zGrid.ZRow;

jest.mock('./zRow'); // diff

describe(&quot;case1&quot;, () =&gt; {
    it(&quot;pat1&quot;, () =&gt; {
        let grid = new ZGrid();
        expect(grid.getCount()).toBe(6);
    });
});
</code></pre>
<p>But, Unit test code (with Mock) got fail. What's Going on?</p>
<pre><code>// zGrid.test.ts : (for the newly added input component class 1 : zGrid.ts)
import { mocked } from 'ts-jest/utils';

import { aaa as aaa1 } from './zGrid';
import ZGrid = aaa1.bbb.ccc.controls.zGrid.ZGrid;
import { aaa as aaa2 } from './zRow';
import ZRow  = aaa2.bbb.ccc.controls.zGrid.ZRow;

// diff (begin)
jest.mock('./zRow', () =&gt; {
    return {
        ZRow: jest.fn().mockImplementation(() =&gt; {
            return {
                getColCount: () =&gt; { return 1 },
            };
        })
    };
});
// diff (end)

describe(&quot;case1&quot;, () =&gt; {
    it(&quot;pat1&quot;, () =&gt; {
        let grid = new ZGrid();
        expect(grid.getCount()).toBe(3);
    });
});
</code></pre>
<p>Failed output</p>
<pre><code>&gt;yarn jest zGrid.test.ts
yarn run v1.22.5
$ C:\zzz\Scripts\node_modules\.bin\jest zGrid.test.ts
 FAIL  yyy/controls/zGrid.test.ts
   Test suite failed to run

    TypeError: Cannot read property 'bbb' of undefined

      1 | ﻿import { aaa as aaa1 } from './zRow';
    &gt; 2 | import ZRow = aaa1.bbb.ccc.controls.zGrid.ZRow;
        |                    ^
      3 |
      4 | export module aaa.bbb.ccc.controls.zGrid {
      5 |     /** Zeta Grid */

      at yyy/controls/zGrid.ts:2:20
      at yyy/controls/zGrid.js:3:17
      at Object.&lt;anonymous&gt; (yyy/controls/zGrid.js:9:3)
      at Object.&lt;anonymous&gt; (yyy/controls/zGrid.test.ts:3:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        10.919 s
Ran all test suites matching /zGrid.test.ts/i.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code></pre>
<p>Q 2</p>
<p>We want to use ZGrid class(zGrid.ts) in Entry1 class(Entry1.ts), but we can't find &quot;How to import ZGrid class in Entry1 class&quot;.
Hybrid implementation with &quot;Exporting namespace &amp; class&quot; src code (zGrid.ts) &amp; &quot;Exporting class&quot; src code (Entry1.ts) is impossible?</p>
<p>The development environment is as follows.</p>
<ul>
<li>Windows 10</li>
<li>Visual Studio ver.2017 or 2019</li>
<li>TypeScript ver.2.9.2</li>
<li>Jest ver.26.6</li>
<li>ts-jest ver.26.4.4</li>
<li>Yarn ver.1.22.5</li>
<li>Node.js ver.12.18.4</li>
</ul>
",https://stackoverflow.com/questions/65489204/test-suite-failed-to-run-jest-mock,"['typescript', 'unit-testing', 'jestjs', 'mocking', 'ts-jest']",560,True,0,1
mock fs.readFile - Unit test,"<p>I am using Jest framework for unit testing and came across a scenario to mock the fs.readFile.I have used spyOn and mocked the implementation.My code below</p>

<p><strong>test_file.ts</strong></p>

<pre><code>import * as fs from 'fs';


it('read File',  () =&gt; {

    const spy = jest.spyOn(fs, 'readFile')
                    .mockImplementation((_, callback) =&gt; callback(null, Buffer.from('Sample')));

    // Calling the function
    myFunction('./path');

    expect(spy).toHaveBeenCalled();

});
</code></pre>

<p>The spy is not called when i run the test case and the mock is not working.The original implementation is always working.</p>

<p><strong>My function using fs.readFile</strong> </p>

<pre><code>myFunction = (path) =&gt; {
    // Reading the file
    fs.readFile(path, async (error, file) =&gt; {
        console.log(error)      // No such file error thrown instead  of null
        /**  Block of code with async work**/   
    });
};
</code></pre>

<p><strong>Briefly,what i am trying to do</strong> </p>

<p>How to mock the fs.readFile correctly ?</p>

<p><strong>EDIT</strong><br>
When i tried to console the error in my original callback function,it threw error 'no such file' . But i am expecting the error to be null since I am mocking it to return value as null.</p>
",https://stackoverflow.com/questions/59798339/mock-fs-readfile-unit-test,"['javascript', 'typescript', 'unit-testing', 'jestjs', 'fs']",4827,True,3,1
Testing and mocking asynchronous code that uses async with statement,"<p>I have a simple asynchronous functions that fetches JSON from the web:</p>

<pre><code>async def fetch (session : aiohttp.ClientSession, url : str, pageSize : int = 100, pageNumber : int = 0):
    async with session.get(url, params={'pageSize' : f""{pageSize}"", 'pageNumber' : f""{pageNumber}""}) as response:
        return await response.json()
</code></pre>

<p>How do I write unit tests for it? I am learning how to do that in Python currently and I have settled down on using <code>unittest</code> and <code>aiounittest</code> modules. The scaffolding that I use for testing is as follows:</p>

<pre><code>class AsyncTest(aiounittest.AsyncTestCase):
    async def test_fetch(self):
        mocked_session = ... #no idea how to create
        json = await fetch(mocked_session, ""url_for_mock"", 10, 0)
</code></pre>

<p>I think I would have to somehow mock the <code>session</code> argument using <code>unittest.Mock()</code> functionality to return some harcoded json data but I am a little lost on how to do this so it works inside <code>async with</code> statement. I have never used an unit testing library in Python and an example would be very helpful here. I am using Python 3.8 and <code>aiohttp</code> for networking.</p>
",https://stackoverflow.com/questions/60142034/testing-and-mocking-asynchronous-code-that-uses-async-with-statement,"['python', 'python-3.x', 'unit-testing', 'python-asyncio']",1942,True,3,1
TypeError &quot;styled&quot;: symbol is not a function,"<p>I'm running npm test and getting the following error:</p>
<pre><code> FAIL  src/App.test.js
  ● Test suite failed to run

    TypeError: symbol is not a function
        at String (&lt;anonymous&gt;)

      3 | import styled from &quot;styled-components&quot;;
      4 | 
    &gt; 5 | const NoAccess = styled(NoAccess_)`
        |                  ^
      6 |   width: 100px;
      7 |   height: 75px;
      8 | `;

      at options (node_modules/styled-components/src/models/StyledComponent.js:265:68)
      at je (node_modules/styled-components/src/models/StyledComponent.js:265:68)
      at Object.&lt;anonymous&gt; (src/App.js:5:18)
      at Object.&lt;anonymous&gt; (src/App.test.js:2:1)
</code></pre>
<p>Styled is imported in the component where the error is thrown, so I'm not sure why it is &quot;not a function&quot;.</p>
<p>I have created a minimal example underneath.</p>
<h2>Minimal example</h2>
<p><strong>index.js</strong></p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  &lt;React.StrictMode&gt;
    &lt;App /&gt;
  &lt;/React.StrictMode&gt;,
  document.getElementById('root')
);
</code></pre>
<p><strong>App.js</strong></p>
<pre><code>import React from &quot;react&quot;
import NoAccess_ from './NO_ACCESS.svg';
import styled from &quot;styled-components&quot;;

const NoAccess = styled(NoAccess_)`
  width: 100px;
  height: 75px;
`;

function App() {
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;NoAccess /&gt;
    &lt;/div&gt;
  );
}

export default App;
</code></pre>
<p><strong>App.test.js</strong></p>
<pre><code>import React from &quot;react&quot;
import App from './App'
import { render, screen } from &quot;@testing-library/react&quot;;

test(&quot;renders correct content&quot;, () =&gt; {
  const { getByText, getByLabelText } = render(&lt;App /&gt;)
  screen.debug()
})
</code></pre>
<p><strong>package.json</strong></p>
<pre><code>{
  &quot;name&quot;: &quot;my-app&quot;,
  &quot;version&quot;: &quot;0.1.0&quot;,
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;@babel/plugin-transform-react-jsx&quot;: &quot;^7.12.5&quot;,
    &quot;@testing-library/jest-dom&quot;: &quot;^5.11.4&quot;,
    &quot;@testing-library/react&quot;: &quot;^11.1.0&quot;,
    &quot;@testing-library/user-event&quot;: &quot;^12.1.10&quot;,
    &quot;identity-obj-proxy&quot;: &quot;^3.0.0&quot;,
    &quot;react&quot;: &quot;^17.0.1&quot;,
    &quot;react-dom&quot;: &quot;^17.0.1&quot;,
    &quot;react-scripts&quot;: &quot;4.0.0&quot;,
    &quot;styled-components&quot;: &quot;^5.2.1&quot;,
    &quot;web-vitals&quot;: &quot;^0.2.4&quot;
  },
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;react-scripts start&quot;,
    &quot;build&quot;: &quot;react-scripts build&quot;,
    &quot;test&quot;: &quot;jest&quot;,
    &quot;eject&quot;: &quot;react-scripts eject&quot;
  },
  &quot;eslintConfig&quot;: {
    &quot;extends&quot;: [
      &quot;react-app&quot;,
      &quot;react-app/jest&quot;
    ]
  },
  &quot;browserslist&quot;: {
    &quot;production&quot;: [
      &quot;&gt;0.2%&quot;,
      &quot;not dead&quot;,
      &quot;not op_mini all&quot;
    ],
    &quot;development&quot;: [
      &quot;last 1 chrome version&quot;,
      &quot;last 1 firefox version&quot;,
      &quot;last 1 safari version&quot;
    ]
  },
  &quot;jest&quot;: {
    &quot;verbose&quot;: false,
    &quot;rootDir&quot;: &quot;.&quot;,
    &quot;collectCoverageFrom&quot;: [
      &quot;**/*.{js,jsx,ts,tsx}&quot;,
      &quot;!**/*.d.ts&quot;
    ],
    &quot;moduleFileExtensions&quot;: [
      &quot;js&quot;,
      &quot;jsx&quot;,
      &quot;ts&quot;,
      &quot;tsx&quot;
    ],
    &quot;moduleNameMapper&quot;: {
      &quot;\\.(css|less|scss|sass|svg)$&quot;: &quot;identity-obj-proxy&quot;
    },
    &quot;transform&quot;: {
      &quot;\\.[jt]sx?$&quot;: &quot;babel-jest&quot;,
      &quot;^.+\\.jsx?$&quot;: &quot;babel-jest&quot;,
      &quot;^.+\\.svg$&quot;: &quot;&lt;rootDir&gt;/svgTransform.js&quot;
    },
    &quot;transformIgnorePatterns&quot;: [
      &quot;/node_modules/&quot;
    ],
    &quot;testMatch&quot;: [
      &quot;**/*.{spec,test}.{js,jsx,ts,tsx}&quot;
    ]
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/plugin-proposal-class-properties&quot;: &quot;^7.12.1&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.12.1&quot;,
    &quot;@babel/preset-react&quot;: &quot;^7.12.5&quot;,
    &quot;babel-jest&quot;: &quot;^26.6.3&quot;,
    &quot;jest&quot;: &quot;^26.6.3&quot;
  }
}

</code></pre>
<pre><code>&lt;svg width=&quot;100&quot; height=&quot;75&quot; viewBox=&quot;0 0 100 75&quot; fill=&quot;none&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;
&lt;path fill-rule=&quot;evenodd&quot; clip-rule=&quot;evenodd&quot; d=&quot;M98.333 0H1.66699C0.746094 0 0 0.746094 0 1.66699V58.3335C0 59.2537 0.746094 59.9998 1.66699 59.9998H46.667V73.333C46.667 74.2539 47.4131 75 48.334 75H81.667C82.5879 75 83.334 74.2539 83.334 73.333V59.9998H98.333C99.2539 59.9998 100 59.2537 100 58.3335V1.66699C100 0.746094 99.2539 0 98.333 0ZM50 71.6667V44.9998H80V71.6667H50ZM65 28.3333C60.3994 28.3386 56.6719 32.0664 56.667 36.667V41.6665H53.333V36.667C53.333 30.2231 58.5566 25 65 25C71.4434 25 76.666 30.2239 76.666 36.667V41.6665H73.333V36.667C73.3281 32.0664 69.5996 28.3386 65 28.3333ZM70 36.667V41.6665H60V36.667C60 33.905 62.2383 31.6665 65 31.6665C67.7617 31.6665 70 33.905 70 36.667ZM96.667 56.6665H83.334V43.3335C83.334 42.4126 82.5879 41.6665 81.667 41.6665H80V36.667C80 28.3821 73.2842 21.6667 65 21.6667C56.7158 21.6667 50 28.3821 50 36.667V41.6665H48.334C47.4131 41.6665 46.667 42.4126 46.667 43.3335V56.6665H3.33301V16.6665H96.667V56.6665ZM96.667 13.333H3.33301V3.33325H96.667V13.333ZM10 53.333H26.667C27.5879 53.333 28.334 52.5869 28.334 51.6667V40.0212C28.3242 37.187 26.5273 34.6677 23.8506 33.7363C24.6006 32.6353 25.002 31.333 25 30V21.6665C25 20.7456 24.2539 19.9995 23.333 19.9995H13.334C12.4131 19.9995 11.667 20.7456 11.667 21.6665V30C11.666 31.333 12.0664 32.6353 12.8174 33.7363C10.1396 34.6677 8.34277 37.187 8.33398 40.0212V51.6667C8.33398 52.5869 9.08008 53.333 10 53.333ZM15.001 23.3328H21.667V30C21.667 31.8411 20.1748 33.3335 18.334 33.3335C16.4932 33.3335 15.001 31.8411 15.001 30V23.3328ZM11.667 40.0212C11.6689 38.1697 13.1699 36.6682 15.0215 36.6667H21.6455C23.4971 36.6682 24.999 38.1697 25 40.0212V49.9998H11.667V40.0212ZM93.333 6.66675H90V10H93.333V6.66675ZM83.334 6.66675H86.667V10H83.334V6.66675ZM63.333 66.6665V59.6931C61.9102 59.1897 60.79 58.0696 60.2861 56.646C59.3662 54.042 60.7305 51.1855 63.333 50.2654C65.9375 49.3447 68.7939 50.7095 69.7148 53.3127C70.6348 55.9158 69.2705 58.7729 66.667 59.6931V66.6665H63.333ZM66.667 55.0002C66.667 54.0793 65.9209 53.3333 65 53.3333C64.0791 53.3333 63.333 54.0793 63.333 55.0002C63.333 55.9204 64.0791 56.6665 65 56.6665C65.9209 56.6665 66.667 55.9204 66.667 55.0002Z&quot; fill=&quot;#007079&quot;/&gt;
&lt;/svg&gt;

</code></pre>
<p>I'm guessing something needs to be added to the config, but I'm not sure what.</p>
<h1>What I have tried so far:</h1>
<h2>1. Wrapping svg in brackets made the test go through, but not the compile the project (npm run dev)</h2>
<h2>2. Using moduleMapper (Not working)</h2>
<pre><code>&quot;moduleNameMapper&quot;: {
      &quot;\\.(svg)$&quot;: &quot;&lt;rootDir&gt;/test/__mocks__/svgMock.js&quot;
    }
</code></pre>
<p>and svgMock:</p>
<pre><code>module.exports = '';
</code></pre>
<p>Inspired by <a href=""https://stackoverflow.com/questions/48640647/unit-testing-of-styled-components-with-svg-imports"">Unit testing of styled-components with SVG imports</a>.</p>
<h1>(Working) Dirty solution:</h1>
<h2>Exporting svg with JS:</h2>
<pre><code>export default () =&gt;
(&lt;svg width=&quot;100&quot; height=&quot;75&quot; viewBox=&quot;0 0 100 75&quot; fill=&quot;none&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;
&lt;path fill-rule=&quot;evenodd&quot; clip-rule=&quot;evenodd&quot; d=&quot;M98.333 0H1.66699C0.746094 0 0 0.746094 0 1.66699V58.3335C0 59.2537 0.746094 59.9998 1.66699 59.9998H46.667V73.333C46.667 74.2539 47.4131 75 48.334 75H81.667C82.5879 75 83.334 74.2539 83.334 73.333V59.9998H98.333C99.2539 59.9998 100 59.2537 100 58.3335V1.66699C100 0.746094 99.2539 0 98.333 0ZM50 71.6667V44.9998H80V71.6667H50ZM65 28.3333C60.3994 28.3386 56.6719 32.0664 56.667 36.667V41.6665H53.333V36.667C53.333 30.2231 58.5566 25 65 25C71.4434 25 76.666 30.2239 76.666 36.667V41.6665H73.333V36.667C73.3281 32.0664 69.5996 28.3386 65 28.3333ZM70 36.667V41.6665H60V36.667C60 33.905 62.2383 31.6665 65 31.6665C67.7617 31.6665 70 33.905 70 36.667ZM96.667 56.6665H83.334V43.3335C83.334 42.4126 82.5879 41.6665 81.667 41.6665H80V36.667C80 28.3821 73.2842 21.6667 65 21.6667C56.7158 21.6667 50 28.3821 50 36.667V41.6665H48.334C47.4131 41.6665 46.667 42.4126 46.667 43.3335V56.6665H3.33301V16.6665H96.667V56.6665ZM96.667 13.333H3.33301V3.33325H96.667V13.333ZM10 53.333H26.667C27.5879 53.333 28.334 52.5869 28.334 51.6667V40.0212C28.3242 37.187 26.5273 34.6677 23.8506 33.7363C24.6006 32.6353 25.002 31.333 25 30V21.6665C25 20.7456 24.2539 19.9995 23.333 19.9995H13.334C12.4131 19.9995 11.667 20.7456 11.667 21.6665V30C11.666 31.333 12.0664 32.6353 12.8174 33.7363C10.1396 34.6677 8.34277 37.187 8.33398 40.0212V51.6667C8.33398 52.5869 9.08008 53.333 10 53.333ZM15.001 23.3328H21.667V30C21.667 31.8411 20.1748 33.3335 18.334 33.3335C16.4932 33.3335 15.001 31.8411 15.001 30V23.3328ZM11.667 40.0212C11.6689 38.1697 13.1699 36.6682 15.0215 36.6667H21.6455C23.4971 36.6682 24.999 38.1697 25 40.0212V49.9998H11.667V40.0212ZM93.333 6.66675H90V10H93.333V6.66675ZM83.334 6.66675H86.667V10H83.334V6.66675ZM63.333 66.6665V59.6931C61.9102 59.1897 60.79 58.0696 60.2861 56.646C59.3662 54.042 60.7305 51.1855 63.333 50.2654C65.9375 49.3447 68.7939 50.7095 69.7148 53.3127C70.6348 55.9158 69.2705 58.7729 66.667 59.6931V66.6665H63.333ZM66.667 55.0002C66.667 54.0793 65.9209 53.3333 65 53.3333C64.0791 53.3333 63.333 54.0793 63.333 55.0002C63.333 55.9204 64.0791 56.6665 65 56.6665C65.9209 56.6665 66.667 55.9204 66.667 55.0002Z&quot; fill=&quot;#007079&quot;/&gt;
&lt;/svg&gt;)

</code></pre>
",https://stackoverflow.com/questions/64854258/typeerror-styled-symbol-is-not-a-function,"['reactjs', 'jestjs', 'styled-components']",3209,True,3,1
How to test Validation pipe is throwing the expect error for improperly shaped request on NestJS,"<p>I'm using NestJS 7.0.2 and have globally enabled validation pipes via <code>app.useGlobalPipes(new ValidationPipe());</code>.  </p>

<p>I'd like to be able to have a unit test that verifies that errors are being thrown if the improperly shaped object is provided, however the test as written still passes. I've seen that one solution is to do this testing in e2e <a href=""https://stackoverflow.com/questions/58843038/how-to-manually-test-input-validation-with-nestjs-and-class-validator"">via this post</a>, but I'm wondering if there is anything I'm missing that would allow me to do this in unit testing.</p>

<p>I have a very simple controller with a very simple DTO.</p>

<p>Controller</p>

<pre><code>async myApi(@Body() myInput: myDto): Promise&lt;myDto | any&gt; {
  return {};
}
</code></pre>

<p>DTO</p>

<pre><code>export class myDto {
  @IsNotEmpty()
  a: string;

  @IsNotEmpty()
  b: string | Array&lt;string&gt;
}
</code></pre>

<p>Spec file</p>

<pre><code>  describe('generate', () =&gt; {
    it('should require the proper type', async () =&gt; {
      const result = await controller.generate(&lt;myDto&gt;{});
      // TODO: I expect a validation error to occur here so I can test against it.
      expect(result).toEqual({})
    })
  })
</code></pre>

<p>It also fails if I do not coerce the type of <code>myDto</code> and just do a <code>ts-ignore</code> on a generic object. </p>
",https://stackoverflow.com/questions/60819612/how-to-test-validation-pipe-is-throwing-the-expect-error-for-improperly-shaped-r,"['jestjs', 'nestjs']",6670,True,3,2
Apache Beam Python Unit Testing a ParDo class with_outputs,"<p>I have a ParDo class that checks if a pubsub message contains certain attributes and returns a valid and invalid TaggedOutput (that works fine in the normal flow, using yield for returning the values), and I am not able to do unit testing for this class, I am trying to provide a dummy message (dictionary replicating pubsub message info) and I want to check if the output of the class contains other attributes.</p>

<p>this is what I have so far:</p>

<pre><code>class TestValidateMessage(unittest.TestCase):

def test_not_valid(self):
    with TestPipeline() as p:
        pcoll = (
                p
                | beam.Create([{'attributes':{""imageUrl"":000}}])
                | beam.ParDo(ValidateMessage()).with_outputs(
        'invalid', main='valid'))
    valid, _ = pcoll
    invalid = pcoll['invalid']
    print(invalid)
    assert_that(invalid, {'failure_step':'Message validation'})
</code></pre>

<p>With this I get an error message:</p>

<pre><code>TypeError: Map can be used only with callable objects. Received {'failure_step'} instead.
</code></pre>

<p>When I try to print(invalid), I get <code>PCollection[ParDo(ValidateMessage)/ParDo(ValidateMessage).invalid]</code>
How do I access (for asserting purposes) the content of the PCollection?</p>
",https://stackoverflow.com/questions/60999791/apache-beam-python-unit-testing-a-pardo-class-with-outputs,"['python', 'unit-testing', 'apache-beam', 'google-cloud-pubsub']",1345,True,2,1
Fetching SKProducts while in UITesting,"<p>So it turns out in iOS 14.0 and Xcode 12.0 in order to test in-app purchases and subscriptions on Simulator - I have to add a StoreKit configuration such as <code>StoreKit.configuration</code> and set it in the scheme Run options. This worked great.</p>
<p>However I am running some UITests on my app and unfortunately this configuration will not take effect when running the app from a UITest. And so, my SKProducts cannot be retrieved.</p>
<p>Anyone has an idea how to get that to work?</p>
<p>p.s I know <code>StoreKitTest</code> will allow me to perform unit testing on the in-app purchases but that is not my goal here.</p>
",https://stackoverflow.com/questions/64706110/fetching-skproducts-while-in-uitesting,"['swift', 'xcode-ui-testing', 'storekit', 'ios14']",251,False,2,1
How to test client-side javascript in an ASP.NET MVC application?,"<p><strong>Project Context</strong></p>
<p>I've got an ASP.NET MVC 5 and ASP.NET Web API 2.0 combined web application (i.e. both in the same project). There are pages that I have created where I do custom SPA: Handlebars.js for html templating, Routie.js for hash routing, and the rest custom JavaScript.</p>
<p>How do I go about unit testing my client-side javascript?</p>
<p>I could write functions that I manually kick off that does the action and checks if it succeeded. This has worked for me, but is still very manual. Any searches for how to automate testing of this code leads me to things like jest.js and such which seem to require npm, which to my understanding requires a node.js project.</p>
<p>I explored the node.js project route a little bit and got jest working for tests, but still lacked the understanding of how to use this project to test my client-side javascript and/or reference the code from the main project.</p>
<p><strong>Question</strong></p>
<ul>
<li><p>How do I go about unit testing (preferably automating such tests; e.g. Azure DevOps) in an ASP.NET MVC 5 / Web Api 2.0 project?</p>
</li>
<li><p>If I need to create a node.js project with a test runner like Jest, how do I reference my client-side code from the main project to be tested?</p>
</li>
</ul>
<p>I conceptually know how to write tests, I'm just running into problems understanding how to get the environment setup to do so. I have my C# unit tests setup to automatically run with my Azure DevOps pipeline, I'm just missing on how to get something setup to test my client-side JavaScript.</p>
",https://stackoverflow.com/questions/63039267/how-to-test-client-side-javascript-in-an-asp-net-mvc-application,"['javascript', 'asp.net-mvc', 'unit-testing']",202,False,2,0
Unit testing a component that uses other components (wrapping),"<p>I have not been able to find answers to my question and I'm not sure if its because nobody else struggled with it before? Or my wording is incorrect. So here I am.</p>

<p>Let's say we have a Dialog component that looks like this (some parts were left off for simplicity sake):</p>

<pre><code>import React from 'react';
import Modal from './Modal';

export default class Dialog extends React.Component {
  render() {
    const { children, dialogCss, ...modalProps } = this.props;

    return (
      &lt;Modal role=""dialog"" {...modalProps}&gt;
        &lt;div&gt;
          &lt;div dialogCss={dialogCss}&gt;{children}&lt;/div&gt;
        &lt;/div&gt;
      &lt;/Modal&gt;
    );
  }
}
</code></pre>

<p>As you can see from the code, <code>Dialog</code> component uses <code>Modal</code> component under the hood.</p>

<p>How should I approach unit testing?</p>

<ul>
<li>Do I unit test Dialog specific functionalities only (which is only css)?</li>
<li>Do I unit test Dialog specific functionality AND Modal functionality through Dialog?</li>
</ul>

<p>For example, Modal has a boolean prop called <code>open</code> that renders or doesn't render the component. I already tested Modal, and in that Modal test, I test that <code>open</code> prop set to false or true is respected.</p>

<p>Dialog also uses <code>open</code>, do I need to test that ""Dialog"" also respects the <code>open</code> prop set to false or true? </p>

<p>This is how it is currently being tested and it is testing Dialog specific functionality ONLY because my reasoning is: even though Dialog is using Modal under the hood, since Modal itself has been tested, it will be redundant to test it through Dialog again. Please correct me if I am wrong.</p>

<pre><code>import React from 'react';
import Dialog from './Dialog';

const testCss = {
  'background-color': '#fff',
  color: '#000',
};

test('respects dialogCss prop', () =&gt; {
  const { getByTestId } = render(
    &lt;Dialog open={true} dialogCss={() =&gt; testCss}&gt;
      &lt;div&gt;hello&lt;/div&gt;
    &lt;/Dialog&gt;
  );

  expect(getByTestId('dialogbox')).toHaveStyle({ ...testCss });
});

test('renders children', () =&gt; {
  const { getByTestId } = render(
    &lt;Dialog open={true}&gt;
      &lt;div data-testid=""test""&gt;hello&lt;/div&gt;
    &lt;/Dialog&gt;
  );

  expect(getByTestId('test')).not.toBeNull();
});
</code></pre>

<p>And here is the dispute: someone said <code>your dialog is still a dialog and you'd expect anything that depends on it to not break</code>, meaning we SHOULD be testing that Modal is working through Dialog. Meaning that Dialog should test that <code>open</code> is being respected, even though Modal itself is testing for it.</p>

<p>Two opposing thoughts, and we are all new to front end unit testing. Any help is appreciated!</p>

<p>Thank you for your time and help!</p>
",https://stackoverflow.com/questions/60213494/unit-testing-a-component-that-uses-other-components-wrapping,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",260,False,2,0
Finding ways to reduce duplication,"<p>I'm trying to understand the concept of simplifying design. Below is a code with two classes with the same functionality.</p>
<pre><code>interface Factorial {
   long factorial(long n); 
}

class FactorialA implements Factorial {
   long factorial(long n) {
     // imperative implementation goes here
   }
}
class FactorialB implements Factorial {
   long factorial(long n) {
     // recursive implementation goes here
   }
}
class FactorialB implements Factorial {
   long factorial(long n) {
     // functional implementation goes here
   }
}

...
class FactorialTest {
   @Test
   public void testFactorialA() {
      testFactorial(new FactorialA());
   }
...
   private void testFactorial(Factorial f) {
     assertThat(...)
   }
}
</code></pre>
<p>How would I reduce duplication in this case?
I have tried putting them in one class and making the methods static, but I am stuck on how would I call that. I have also attempted an interface as per above, but in that case, the unit testing would be plagued with duplicate tests. Any helpful tips would be appreciated, as this will help me reduce redundancy in my code. How can I condense the code above into one class, with reduced redundancy in testing?</p>
",https://stackoverflow.com/questions/64600844/finding-ways-to-reduce-duplication,"['java', 'oop', 'inheritance', 'polymorphism']",59,True,1,2
How to use mockito with maven testing harness,"<p>The maven plugin I am developing now injects some dependencies using Google Guice with JSR-330. For unit testing I am using <a href=""https://maven.apache.org/plugin-testing/maven-plugin-testing-harness/"" rel=""nofollow noreferrer"">maven-plugin-testing-harness</a>. The plugin works perfectly. But there is a problem with tests. I want to inject mocked components into mojo, but still there are real objects in tests. </p>

<p>I've tried to write my custom test module as it's said in <a href=""https://github.com/google/guice/wiki/BoundFields"" rel=""nofollow noreferrer"">Google Guice Bound Field</a>, but it didn't work. After some debugging I found out that Plexus container doesn't allow to use custom modules.</p>

<p>There are my mojo:</p>

<pre><code>package my.maven.plugins.myplugin;

import my.maven.plugins.myplugin.component.MyComponent;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

import javax.inject.Inject;

@Mojo(name = ""resolve-property-value"")
public class MyMojo extends AbstractMojo {

    private final MyComponent component;

    @Parameter(readonly = true, defaultValue = ""${project}"" )
    private MavenProject project;

    @Inject
    public MyMojo(MyComponent component) {
        this.component = component;
    }

    @Override
    public void execute() {
        String value = component.resolvePropertyValue();
        project.getProperties().setProperty(""some.property"", value);
    }
}
</code></pre>

<p>Component's interface:</p>

<pre><code>package my.maven.plugins.myplugin.component;

public interface MyComponent {

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

<p>And implementation</p>

<pre><code>package my.maven.plugins.myplugin.component.impl;

import my.maven.plugins.myplugin.component.MyComponent;

import javax.inject.Named;

@Named
public class MyComponentImpl implements MyComponent {

    @Override
    public String resolvePropertyValue() {
        return ""someValue"";
    }
}
</code></pre>

<p>Test:</p>

<pre><code>package my.maven.plugins.myplugin;

import my.maven.plugins.myplugin.component.MyComponent;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.testing.MojoRule;
import org.apache.maven.project.MavenProject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Properties;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;

public class MyMojoTest {

    @Mock
    private MyComponent component;

    @Rule
    public MojoRule mojoRule = new MojoRule();

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

    @Test
    public void should_set_some_property() throws Exception {
        doReturn(""testValue"").when(component).resolvePropertyValue();
        MavenProject project = new MavenProject();
        Mojo goal = mojoRule.lookupConfiguredMojo(project, ""resolve-property-value"");
        goal.execute();
        Properties properties = project.getProperties();
        assertTrue(properties.containsKey(""some.property""));
        assertEquals(""testValue"", properties.get(""some.property""));
    }
}
</code></pre>

<p>pom.xml</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
         xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
         xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;my.maven.plugins&lt;/groupId&gt;
    &lt;artifactId&gt;my-plugin&lt;/artifactId&gt;
    &lt;version&gt;0.1.0-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;maven-plugin&lt;/packaging&gt;

    &lt;properties&gt;
        &lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt;
        &lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&gt;
        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;

        &lt;maven.version&gt;3.6.0&lt;/maven.version&gt;
        &lt;maven-test.version&gt;3.3.0&lt;/maven-test.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.maven&lt;/groupId&gt;
            &lt;artifactId&gt;maven-core&lt;/artifactId&gt;
            &lt;version&gt;${maven.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.maven&lt;/groupId&gt;
            &lt;artifactId&gt;maven-plugin-api&lt;/artifactId&gt;
            &lt;version&gt;${maven.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.maven.plugin-tools&lt;/groupId&gt;
            &lt;artifactId&gt;maven-plugin-annotations&lt;/artifactId&gt;
            &lt;version&gt;${maven.version}&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.google.guava&lt;/groupId&gt;
            &lt;artifactId&gt;guava&lt;/artifactId&gt;
            &lt;version&gt;21.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.maven.resolver&lt;/groupId&gt;
            &lt;artifactId&gt;maven-resolver-api&lt;/artifactId&gt;
            &lt;version&gt;1.3.1&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.maven&lt;/groupId&gt;
            &lt;artifactId&gt;maven-compat&lt;/artifactId&gt;
            &lt;version&gt;${maven.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;!-- Test dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.maven.plugin-testing&lt;/groupId&gt;
            &lt;artifactId&gt;maven-plugin-testing-harness&lt;/artifactId&gt;
            &lt;version&gt;${maven-test.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;version&gt;4.12&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
            &lt;version&gt;2.23.4&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;pluginManagement&gt;
            &lt;plugins&gt;
                &lt;plugin&gt;
                    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                    &lt;artifactId&gt;maven-plugin-plugin&lt;/artifactId&gt;
                    &lt;version&gt;${maven.version}&lt;/version&gt;
                &lt;/plugin&gt;
            &lt;/plugins&gt;
        &lt;/pluginManagement&gt;
    &lt;/build&gt;
&lt;/project&gt;
</code></pre>

<p>Is there any way to use mockito in plugin unit tests?</p>
",https://stackoverflow.com/questions/60718662/how-to-use-mockito-with-maven-testing-harness,"['java', 'maven', 'mockito', 'maven-plugin', 'maven-plugin-testing-harness']",2187,True,1,1
"pytest, user input and exception","<p>I'm very new to unit testing so sorry for my newbie question.
I've written a small class with one instance attribute, ""name"".</p>

<p>The goal here is to ask the user for input if no ""name"" parameter is passed when the class is instantianted, and to verify if the name is formatted as expected.</p>

<p>Here is the class definition:</p>

<pre class=""lang-py prettyprint-override""><code>class Customer:
    def __init__(self, name=None):
        self.name = name

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

    @name.setter
    def name(self, value):
        while True:
            try:
                if not value:
                    value = str(input(""Please enter the customer's name: ""))
                else:
                    print(""Customer name found: {}"".format(value))
                if not bool(re.match(""^[A-Za-z0-9 _-]*$"", value)) or value == """":
                    raise (ValueError)
            except ValueError:
                print(""Invalid customer name."")
                value = None
                continue
            break
        self._name = value
</code></pre>

<p>It's working as expected:</p>

<pre class=""lang-py prettyprint-override""><code>&gt;&gt;&gt; customer = Customer()
Please enter the customer's name: &amp;&amp;invalid
Invalid customer name.
Please enter the customer's name: valid
&gt;&gt;&gt; customer.name
'VALID'
&gt;&gt;&gt; 
</code></pre>

<p>My test file is as follows:</p>

<pre class=""lang-py prettyprint-override""><code>import script
import pytest


class TestCustomer:
    def setup_method(self):
        self.customer = script.Customer(""validname"")

    def teardown_method(self):
        self.customer = """"

    def test_valid_name(self):
        self.customer.name = ""validname""
        assert self.customer.name == ""VALIDNAME""

    def test_invalid_name(self):
        with pytest.raises(ValueError):
            self.customer.name = ""&amp;invalidname&amp;""
</code></pre>

<p>However, when I'm trying to test this with pytest, this happens:</p>

<pre class=""lang-py prettyprint-override""><code>========================================================================= FAILURES =========================================================================
______________________________________________________________ TestCustomer.test_invalid_name ______________________________________________________________

self = &lt;test_script.TestCustomer object at 0x7f1ad68f39a0&gt;

    def test_invalid_name(self):
        with pytest.raises(ValueError):
&gt;           self.customer.name = ""&amp;invalidname&amp;""

test_script.py:18: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
script.py:17: in name
    value = str(input(""Please enter the customer's name: ""))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = &lt;_pytest.capture.DontReadFromInput object at 0x7f1ad693d2e0&gt;, args = ()

    def read(self, *args):
&gt;       raise IOError(
            ""pytest: reading from stdin while output is captured!  Consider using `-s`.""
        )
E       OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.

/usr/local/lib/python3.8/dist-packages/_pytest/capture.py:732: OSError
------------------------------------------------------------------ Captured stdout setup -------------------------------------------------------------------
Customer name found: validname
------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------
Customer name found: &amp;invalidname&amp;
Invalid customer name.
Please enter the customer's name: 
================================================================= short test summary info ==================================================================
FAILED test_script.py::TestCustomer::test_invalid_name - OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.
=============================================================== 1 failed, 1 passed in 0.07s ================================================================
</code></pre>

<p>When I'm using the -s option, and enter a valid name, the exception is not raised:</p>

<pre class=""lang-py prettyprint-override""><code>test_script.py Customer name found: validname
Customer name found: validname
.Customer name found: validname
Customer name found: &amp;invalidname&amp;
Invalid customer name.
Please enter the customer's name: test
F

========================================================================= FAILURES =========================================================================
______________________________________________________________ TestCustomer.test_invalid_name ______________________________________________________________

self = &lt;test_script.TestCustomer object at 0x7f4f2e1f6640&gt;

    def test_invalid_name(self):
        with pytest.raises(ValueError):
&gt;           self.customer.name = ""&amp;invalidname&amp;""
E           Failed: DID NOT RAISE &lt;class 'ValueError'&gt;

test_script.py:18: Failed
================================================================= short test summary info ==================================================================
FAILED test_script.py::TestCustomer::test_invalid_name - Failed: DID NOT RAISE &lt;class 'ValueError'&gt;
=============================================================== 1 failed, 1 passed in 1.96s ================================================================
</code></pre>

<p>I can't get my head around this ...
Any help would be very appreciated :).</p>
",https://stackoverflow.com/questions/62086062/pytest-user-input-and-exception,"['python', 'pytest']",237,False,1,0
How can you test that a function is invoking another function?,"<p>I'm new to unit testing, especially in Dart/Mockito, so maybe I'm approaching this all wrong. I have an authentication system that has a <code>registerPreLogoutCallback(PreLogoutCallback callback)</code> method, which adds the given asynchronous callback to a list. When <code>logOut</code> is called, I use <code>Future.wait</code> to wait until each of these callbacks has executed, then actually log the user out.</p>

<p>When testing the <code>logOut</code> method, I'd like to make sure that any registered callbacks have been called. Therefore, I figured I should call <code>registerPreLogoutCallback</code> a few times in the unit test, and somehow verify that the registered callbacks have been called. Is this possible? Does it violate the purpose of a unit test?</p>
",https://stackoverflow.com/questions/59944581/how-can-you-test-that-a-function-is-invoking-another-function,"['unit-testing', 'flutter', 'dart', 'mockito']",1626,True,1,1
Ionic unit testing alertcontroller,"<p>I am working for an application that uses an alert to tell the user it is using nfc. I am unit testing this app and put a spy on the alertcontroller.create method as follows:</p>
<pre><code>alertController.create = jasmine.createSpy().and.resolveTo({
    present: jasmine.createSpy()
});
</code></pre>
<p>In the unit test I want to check if it is called with the right alert options as follows:</p>
<pre><code>      expect(alertController.create).toHaveBeenCalledWith({
        header: 'NFC aan het lezen...',
        message: 'Hou de pas tegen de achterkant van de telefoon',
        buttons: [
          {
            text: 'Anuleren',
            role: 'cancel',
            handler: () =&gt; nfc.stopRead()
          }
        ]
      });
</code></pre>
<p>The problem however is that it gives an error while running the test because of the handler. How can I effectively test if the alertcontroller.create function is called with the correct values? As right now the test gives the following error:</p>
<pre><code>  Expected $[0].buttons[0].handler = Function to equal Function.
</code></pre>
<p>I want to check if the provided object is correct but the function doesn't check.</p>
",https://stackoverflow.com/questions/64749918/ionic-unit-testing-alertcontroller,"['angular', 'typescript', 'ionic-framework', 'jasmine']",632,True,1,1
Unit Tests for timer triggered Azure Function: provide test data,"<p>To Unit Testing HTTP triggered Azure Functions with test data is well and often described. For example here:
<a href=""https://stackoverflow.com/questions/55232238/how-to-write-unit-test-for-azure-function-v1"">How to write unit test for azure function v1</a></p>
<p>Mock data are given in the http request.</p>
<p>But I have a timer triggerd Azure function which reads data from a FTP server. I would like to Unit Test the function with test data.</p>
<p>My function:</p>
<pre><code>[FunctionName(&quot;MyTimerTriggeredFunction&quot;)]
public static void Run([TimerTrigger(&quot;0 */2 * * * *&quot;)]TimerInfo myTimer, ILogger log, ExecutionContext context)
{
    log.LogInformation($&quot;C# Timer trigger function executed at: {DateTime.Now}&quot;);

    ServiceClass serviceClass = new ServiceClass(log, context);

    List&lt;Order&gt; orderList = serviceClass.getOrdersFromFtp();
...
</code></pre>
<p>a running Unit Test function to test the logger, just to show how I started:</p>
<pre><code>public void TestLogger()
{
    // https://learn.microsoft.com/de-de/azure/azure-functions/functions-test-a-function
    var logger = (ListLogger)TestFactory.CreateLogger(LoggerTypes.List);
    MyTimerTriggeredFunction.Run(null, logger, null);
    var msg = logger.Logs[0];
    bool testString = msg.Contains(&quot;C# Timer trigger function executed at&quot;);
    Assert.IsTrue(testString);
}
</code></pre>
<p>serviceClass.getOrdersFromFtp() return a list of objects. I could create this list with mock data in the unit test but how to give it to the timer triggered azure function?</p>
",https://stackoverflow.com/questions/64302966/unit-tests-for-timer-triggered-azure-function-provide-test-data,"['c#', 'unit-testing', 'azure-functions', 'mstest']",1698,True,1,1
Strapi Unit Testing,"<p>For strapi unit testing (using mysql as a database) i have followed the official documentation, and when i am running the same with <strong>npm run test</strong> i am getting errors like below</p>
<blockquote>
<p>my-project@0.1.0 test D:\Gerrit\website_backend\TE_MCA_DMSWEBV2
jest --forceExit --detectOpenHandles</p>
</blockquote>
<p>●  process.exit called with &quot;1&quot;</p>
<pre><code>  at Strapi.stop (node_modules/strapi/lib/Strapi.js:238:13)
  at Strapi.stopWithError (node_modules/strapi/lib/Strapi.js:224:17)
  at node_modules/strapi-connector-bookshelf/lib/mount-models.js:625:14
</code></pre>
<p>RUNS  tests/app.test.js
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-project@0.1.0 test: <code>jest --forceExit --detectOpenHandles</code>
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the my-project@0.1.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.</p>
<p><strong>database.js</strong></p>
<pre><code>module.exports = ({ env }) =&gt; ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'bookshelf',
      settings: {
        client: 'mysql',
        host: env('DATABASE_HOST', '127.0.0.1'),
        port: env.int('DATABASE_PORT', 3306),
        database: env('DATABASE_NAME', 'myDB'),
        username: env('DATABASE_USERNAME', 'root'),
        password: env('DATABASE_PASSWORD', ''),
        ssl: env.bool('DATABASE_SSL', false),
      },
      options: {}
    },
  },
});
</code></pre>
<p><strong>test/database.json</strong></p>
<pre><code>{
  &quot;defaultConnection&quot;: &quot;default&quot;,
  &quot;connections&quot;: {
    &quot;default&quot;: {
      &quot;connector&quot;: &quot;bookshelf&quot;,
      &quot;settings&quot;: {
        &quot;client&quot;: &quot;mysql&quot;,
        &quot;filename&quot;: &quot;.tmp/test.db&quot;
      },
      &quot;options&quot;: {
        &quot;useNullAsDefault&quot;: true,
        &quot;pool&quot;: {
          &quot;min&quot;: 0,
          &quot;max&quot;: 15
        }
      }
    }
  }
}
</code></pre>
<p><strong>tests/app.test.js</strong></p>
<pre><code>const fs = require('fs');
const { setupStrapi } = require('./helpers/strapi');

/** this code is called once before any test is called */
beforeAll(async (done) =&gt; {
  await setupStrapi(); // singleton so it can be called many times
  done();
});

/** this code is called once before all the tested are finished */
afterAll(async (done) =&gt; {
  const dbSettings = strapi.config.get('database.connections.default.settings');

  //delete test database after all tests
  if (dbSettings &amp;&amp; dbSettings.filename) {
    const tmpDbFile = `${__dirname}/../${dbSettings.filename}`;
    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }
  }
  done();
});

it('strapi is defined', async (done) =&gt; {
  expect(strapi).toBeDefined();
  done();
});
</code></pre>
<p><strong>tests/helpers/strapi.js</strong></p>
<pre><code>const Strapi = require('strapi');
const http = require('http');

let instance;

async function setupStrapi() {
  if (!instance) {
    /** the following code in copied from `./node_modules/strapi/lib/Strapi.js` */
    await Strapi().load();
    instance = strapi; // strapi is global now
    await instance.app
      .use(instance.router.routes()) // populate KOA routes
      .use(instance.router.allowedMethods()); // populate KOA methods

    instance.server = http.createServer(instance.app.callback());
  }
  return instance;
}
module.exports = { setupStrapi };
</code></pre>
",https://stackoverflow.com/questions/62888737/strapi-unit-testing,"['javascript', 'node.js', 'unit-testing', 'strapi']",960,False,1,1
Firestore document query allowed with get() but denied using where(),"<p>I am unit testing the firestore security rules below which allows a member of a group to read the <code>groups</code> collection if their userId is a key in the <code>roles</code> map.</p>

<pre><code>function isMemberOfGroup(userId, groupId) {
    return userId in get(/databases/$(database)/documents/groups/$(groupId)).data.roles.keys();
}

match /groups/{groupId} {
    allow read: if isMemberOfGroup(request.auth.uid, groupId);
}
</code></pre>

<p>Sample groups collection</p>

<pre><code>{
    name: ""Group1""
    roles: {
        uid: ""member""
    }
}
</code></pre>

<p>My unit test performs a <code>get()</code> of a single document which succeeds.</p>

<p>It then performs a <code>get()</code> using a <code>where()</code> query which fails.</p>

<pre><code>it(""[groups] any member of a group can read"", async () =&gt; {
    const admin = adminApp({ uid: ""admin"" });
    const alice = authedApp({ uid: ""alice"" });

    // Groups collection initialisation
    await firebase.assertSucceeds(
        admin.collection(""groups"")
        .doc(""group1"")
        .set({ name: ""Group1"", roles: { alice: ""member"" } })
    );

    // This succeeds
    await firebase.assertSucceeds(
        alice.collection(""groups"")
        .doc(""group1"")
        .get()
    );

    // This fails
    await firebase.assertSucceeds(
        alice.collection(""groups"")
            .where(new firebase.firestore.FieldPath('roles', 'alice'), '==', ""member"")
            .get()
        );
    });
</code></pre>

<p>It fails with the error:</p>

<pre><code>FirebaseError: 
Null value error. for 'list' @ L30
</code></pre>

<p>where <code>L30</code> points to the <code>allow read</code> security rule</p>

<p>I know that firestore rules are not responsible for filtering and will deny any request that could contain documents outside of the rule.
However from what I understand, my where() should be limiting this correctly.</p>

<p>Is there a problem with my <code>where()</code> query or my rules?</p>
",https://stackoverflow.com/questions/61922467/firestore-document-query-allowed-with-get-but-denied-using-where,"['javascript', 'firebase', 'google-cloud-firestore', 'firebase-security']",233,True,1,1
How to write a React Component unit test with useEffect hook and async call?,"<p>I'm starting with a basic create-react-app app and trying to learn the proper unit testing techniques. I updated the initial App component to call a local node API for a basic string response. I can't seem to find in the documentation on how to test that the paragraph tag get's the mocked response in my test.</p>

<p>What's happening is that the component is just stuck with the initial 'Hello World!' text from state message and not updating with the mocked response message. I'm sure I have to trigger an update or finish a digest cycle of sorts, but I'm not sure how to do that quite yet.</p>

<p>App.js</p>

<pre><code>import React from ""react"";
import axios from ""axios"";
import ""./App.css"";

const App = () =&gt; {
  const [message, setMessage] = React.useState(""Hello World!"");

  React.useEffect(() =&gt; {
    const getGreetingFromApi = async () =&gt; {
      const apiResponseGreeting = await axios.get(""api/hello"");
      setMessage(apiResponseGreeting.data);
    };
    getGreetingFromApi();
  });

  return (
    &lt;div className=""App""&gt;
      &lt;header className=""App-header""&gt;
        &lt;p&gt;{message}&lt;/p&gt;
      &lt;/header&gt;
    &lt;/div&gt;
  );
};

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

<p>App.test.js</p>

<pre><code>import React from ""react"";
import ReactDOM from ""react-dom"";
import { act } from ""react-dom/test-utils"";

import axios from ""axios"";
import App from ""./App"";

jest.mock(""axios"");

describe(""App Component Tests"", () =&gt; {

    let container;

    beforeEach(() =&gt; {
        container = document.createElement(""div"");
        document.body.appendChild(container);
    });

    afterEach(() =&gt; {
        document.body.removeChild(container);
        container = null;
    });

    it(""App replaces initial value with greeting response"", async () =&gt; {
        const mockResponse = { data: ""Label Test Text"" };
        axios.get.mockResolvedValue(mockResponse);

        let paragraph;

        act(() =&gt; {
            ReactDOM.render(&lt;App /&gt;, container);
            paragraph = container.querySelector(""p"");
        });

        expect(paragraph.textContent).toEqual(mockResponse.data);
    });
});
</code></pre>
",https://stackoverflow.com/questions/61109030/how-to-write-a-react-component-unit-test-with-useeffect-hook-and-async-call,"['javascript', 'reactjs', 'unit-testing', 'testing', 'react-hooks']",56,False,0,1
How import python script that requires command line arguments before importing?,"<p>Hi am trying to unit test a python script that requires command line arguments. This class is an AWS glue job but still pure python.</p>
<p>Here is my unit test:</p>
<pre><code>import sys
import unittest

import src.UnzipFile # Fails Here


class TestUnzipFile(unittest.TestCase):


    def test_unzipping_file(self):

        &quot;&quot;&quot;
        Tests that it can unzip a tar.gz file
        &quot;&quot;&quot;


if __name__ == &quot;__main__&quot;:
    try:
        unittest.main()
    except Exception:
        TestUnzipFile().tearDownClass()
</code></pre>
<p>Here is the beginning of the script that I am trying to import (short version):</p>
<pre><code>args = getResolvedOptions(sys.argv,

                              [
                                  's3_bucket',
                                  'archive_path',
                                  'destination_path',
                              ])

bucket_name = args['s3_bucket']

tar_file_path = args['archive_path']


if __name__ == &quot;__main__&quot;:
    main()
</code></pre>
<p>I get the following error after trying to import the script:</p>
<pre><code>awsglue.utils.GlueArgumentError: the following arguments are required: --s3_bucket, --archive_path, --destination_path,
</code></pre>
<p>There is not a lot of documentation on unit testing of AWS glue jobs, and when a glue job is setup you cant use environment variables. Whatever parameters you want to use have to be arguments. So my question becomes how can I import a python script that requires arguments to be passed in?</p>
",https://stackoverflow.com/questions/63255492/how-import-python-script-that-requires-command-line-arguments-before-importing,"['python', 'python-unittest', 'aws-glue']",349,False,0,1
Testing Angular Component using JEST,"<p>I have recently started using JEST with Angular and I was not able to find a clear example, so want to share here so it can be helpful for others.</p>

<p>I have the following AppComponent.ts:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { ApiService } from './services/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  public title = 'jestTest';
  public jsonData = [];

  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.apiService.getData().subscribe((data: []) =&gt; {
      if (data) {
        this.jsonData = data;
      } else {
        this.jsonData = [];
      }
    });
  }

}

</code></pre>

<p>Inject a simple http service to fetch some records from a database and has a variable 'title'. On component init, I make the call and get the results.</p>

<p>In my HTML, I am just displaying the test:</p>

<pre><code>&lt;div&gt; 
  &lt;span&gt;{{ title }}&lt;/span&gt;
  &lt;router-outlet&gt;&lt;/router-outlet&gt;
&lt;/div&gt;
</code></pre>

<p>Here is the spec.ts file: AppComponent.spec.ts:</p>

<pre><code>import { render } from '@testing-library/angular';
import { AppComponent } from './app.component';
import { async, TestBed, ComponentFixture, inject } from '@angular/core/testing';
import { AppRoutingModule } from './app-routing.module';
import { APP_BASE_HREF } from '@angular/common';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ApiService } from './services/api.service';
import { of } from 'rxjs';

const dataArray = [
  {
    object1: 'Object one'
  },
  {
    object2: 'Object two'
  },
  {
    object3: 'Object three'
  }
];

const mockAPIService = {
  getData: jest.fn()
};

describe('AppComponent', () =&gt; {
  let component: AppComponent;
  let service: ApiService;
  let fixture: ComponentFixture&lt;AppComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [
        AppRoutingModule,
        HttpClientTestingModule
      ],
      providers: [
        { provide: APP_BASE_HREF, useValue: '/' },
        { provide: ApiService, useValue: mockAPIService },
      ]
    })
      .compileComponents();
  }));

  afterEach(() =&gt; {
    if (fixture) {
      fixture.destroy();
    }
    mockAPIService.getData.mockReset();
  });

  it('should render the component', async () =&gt; {
    mockAPIService.getData.mockImplementationOnce(() =&gt; of(dataArray));
    const { getByText } = await render(AppComponent);
    expect(getByText('jestTest'));
  });

  it('Service injected via inject(...) and TestBed.get(...) should be the same instance',
    inject([ApiService], (injectService: ApiService) =&gt; {
      service = TestBed.get(ApiService);
      expect(injectService).toBe(service);
    })
  );

  it('should return a list if data available', async () =&gt; {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    mockAPIService.getData.mockImplementationOnce(() =&gt; of(dataArray));
    component.ngOnInit();
    expect(component.jsonData.length).toBeGreaterThanOrEqual(1);
  });

  it('should return a empty list if no data available', async () =&gt; {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    mockAPIService.getData.mockImplementationOnce(() =&gt; of(null));
    component.ngOnInit();
    expect(component.jsonData.length).toEqual(0);
  });

});

</code></pre>

<p>Code coverage states that line 14 is not covered. i.e. constructor(private apiService: ApiService) { }</p>

<pre><code>------------------------|---------|----------|---------|---------|-------------------
File                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------------|---------|----------|---------|---------|-------------------
All files               |     100 |       80 |     100 |     100 |                  
 app                    |     100 |    83.33 |     100 |     100 |                  
  app.component.html    |     100 |      100 |     100 |     100 |                  
  app.component.ts      |     100 |    83.33 |     100 |     100 | 14            

</code></pre>

<p>Why is it not covered?</p>

<p>Would be great if it could be verified so that it can be referred by others also for their unit testing.</p>
",https://stackoverflow.com/questions/61422160/testing-angular-component-using-jest,"['javascript', 'angular', 'typescript', 'unit-testing', 'jestjs']",5840,False,5,0
Cmake: Specify a separate build toolchain for testing?,"<p>I am using CMake to build a project for an embedded system, but my unit testing is done on an x86 host. Therefore, I need to use a completely different compiler to build the tests from the one used for the cross-compiled binary.</p>
<p>I have a main CMakeLists.txt file at the top level of my project, and then another one in my testing folder which gets added with <code>add_subdirectory</code> at the top level. Should I just keep them completely separate or is there a better way to accomplish this?</p>
<p>Running my main build without the cross compiler will cause it to fail, so it really needs to be a separate process for the tests.</p>
",https://stackoverflow.com/questions/64326814/cmake-specify-a-separate-build-toolchain-for-testing,"['unit-testing', 'cmake']",546,False,5,1
How to properly unittest in Python,"<p>I have a method which does the following. Question is how do I unit test this method. I am pretty new to this Python unit testing module. </p>

<p>The question and solution are as follows: </p>

<pre><code>Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by ‘0’ or ‘1’.
Example :
Input str = ""1??0?101""
Output: 
        10000101
        10001101
        10100101
        10101101
        11000101
        11001101
        11100101
        11101101
</code></pre>

<p>Solution:</p>

<pre><code>def _print(string, index):
    if index == len(string):
        print(''.join(string))
        return

    if string[index] == ""?"":

        # replace '?' by '0' and recurse
        string[index] = '0'
        _print(string, index + 1)

        # replace '?' by '1' and recurse
        string[index] = '1'
        _print(string, index + 1)

        # NOTE: Need to backtrack as string
        # is passed by reference to the
        # function
        string[index] = '?'
    else:
        _print(string, index + 1)

# Driver code
if __name__ == ""__main__"":

    string = ""1??0?101""
    string = list(string) #don’t forget to convert to string
    _print(string, 0)

</code></pre>

<p>Output: </p>

<pre><code>        10000101
        10001101
        10100101
        10101101
        11000101
        11001101
        11100101
        11101101
</code></pre>

<p><strong>Questions:</strong> </p>

<p><strong>1. Also, is there a way of returning a list as output instead of printing them out?</strong> </p>

<p><strong>2. Which assert test cases are appropriate in this scenario?</strong> </p>

<p><strong>3. What would be the best end to end test cases to cover in this case?</strong> </p>

<p><strong>4. What could be a better approach of solving this in terms of time and space complexity?</strong></p>

<p>I have tried this which doesn't seem to work:</p>

<pre><code>import unittest
from wildcard import _print
class TestWildCard(unittest.TestCase):

    def test_0_print(self):
        print(""Start wildCard _print test: \n"")
        result = 111
        self.assertEquals(_print(""1?1"",0),result,""Results match"")
</code></pre>
",https://stackoverflow.com/questions/60107724/how-to-properly-unittest-in-python,"['python', 'python-3.x', 'python-unittest']",95,True,0,1
why is bad to avoid introducing shared state in test classes?,"<p>I was reading a book on unit testing, below is denoted as bad code in the book:</p>

<pre><code>public class CustomerTests
{
   private Store _store;

   [Fact]
   public void Test1()
   {
      //act 
      _store = new Store(5);
      ...
   }

   [Fact]
   public void Test2()
   {
      //act 
      _store = new Store(100);
      ...
   }
}
</code></pre>

<p>As we know that when xUnit or other testing frameworks, a new instance of test class is created(constructor runs before each test in the class) for each test, so in my example, since I have two test methods, so there are two instances of <code>CustomerTests</code>, since they are different object/instance, so <code>_store</code> instance/property in different instance are therefore also independent, which means one test methods modifies its <code>_store</code>, the other <code>_store</code> in other instance is not affected. So they technically are not ""shared state"", why we need to avoid that?</p>
",https://stackoverflow.com/questions/61694374/why-is-bad-to-avoid-introducing-shared-state-in-test-classes,"['c#', 'unit-testing', 'xunit', 'xunit.net']",233,False,0,0
How to tear down a Docker container using pytest fixture?,"<p>With Python Unit testing, I would use the classical setUp and tearDown methods. I prefer though pytest as to use test parametrization with the data I get from the container.</p>

<p>To setup a container, I could use the fixture function. But how to tell it to destroy the container after test execution ends?</p>

<p>The following code works not as expected:</p>

<ul>
<li>Pytest seems to recreate the fixture for each test parametrization.</li>
<li>As it seems, no actual container is created.</li>
</ul>

<p>More words on what I'm trying to achieve:</p>

<ul>
<li>Need to test an ingredient parser, tests reflected in the variable <code>local_data</code></li>
<li>The ingredient parser is wrapped in the Docker container (fixture)</li>
</ul>

<pre><code>import pprint
import json
import requests
import pytest
import time


local_testdata = [
    (""1/2 of an apple"", {""product"": ""apple"", ""unit"": ""item"", ""quantity"": ""1/2""}),
    (""12 oz frozen spinach"", {""product"": ""spinach"", ""unit"": ""oz"", ""quantity"": ""12""}),
    (""24 oz frozen strawberries"", {""product"": ""strawberries"", ""unit"": ""oz"", ""quantity"": ""24""})
]

def parse_ingredient(ingredient_string):

    ingreedy_path = ""http://localhost:5000/query""
    for tupl in ingredient_string:
        payload = {""query"": ingredient_string}
        result = requests.post(ingreedy_path, data=json.dumps(payload))
        obj = json.loads(result.text)


@pytest.fixture
def ingreedy_service():
    import docker
    client = docker.from_env()
    ingreedy = client.containers.create(""openfoodbroker/ingreedy.service"", name=""ingreedy_service"", detach=True)
    print(""launch Docker container with Ingreedy service"")
    time.sleep(2)
    pprint.pprint(client.containers.list())
    yield ""ingreedy""
    print(""destroy Docker container"")
    ingreedy.remove()


@pytest.mark.parametrize(""ingredient_string, expected_result"", local_testdata)
def test_ingredient_parser_localdata(ingredient_string, expected_result, ingreedy_service):
    print()
    print(""execute test for: [%s]"" % ingredient_string)
    print()
    # result = parse_ingredient(ingredient_string)



</code></pre>

<p>Output:</p>

<pre><code>launch Docker container with Ingreedy service
[]

execute test for: [1/2 of an apple]

.destroy Docker container
launch Docker container with Ingreedy service
[]

execute test for: [12 oz frozen spinach]

.destroy Docker container
launch Docker container with Ingreedy service
[]

execute test for: [24 oz frozen strawberries]

.destroy Docker container
</code></pre>
",https://stackoverflow.com/questions/61699674/how-to-tear-down-a-docker-container-using-pytest-fixture,"['python', 'docker', 'automated-tests', 'pytest']",747,False,0,0
Can I set some attribute to a Mockito.mock(Class.class)?,"<p>I'm currently working on unit-testing services with mockito and Junit 5. <br/>
Here is the problematic part of my ServiceTest.java :</p>

<pre><code>...

archiveMeasure=Mockito.mock(ArchiveMeasure.class);
previsionHMeasure=Mockito.mock(PrevisionHMeasure.class);
ruleOccupationRate=Mockito.mock(Rule.class);
calculateIndicatorService=Mockito.mock(CalculateIndicatorService.class);

@Test
    public void DefiniteSectionThatBecomesDark_returnTrue() {
        //Arrange
        ruleOccupationRate.setThreshold(25);
        archiveMeasure.setOccupationRate(30);
        previsionHMeasure.setOccupationRate(30);
        boolean expected = true; 
        //Act

        boolean found = definiteSectionStateCongestionService.DefiniteSectionThatBecomesDark(archiveMeasure,previsionHMeasure,ruleOccupationRate);
        //Assert
        assertEquals(found,expected);
    }
</code></pre>

<p>And the service method to test is : </p>

<pre><code>public boolean DefiniteSectionThatBecomesBright (       ArchiveMeasure archiveMeasure,
                                                        PrevisionHMeasure previsionHMeasure,
                                                        Rule ruleOccupationRate) {
        if ( calculateIndicatorsService.calculateActualCongestion(ruleOccupationRate.getThreshold(), archiveMeasure.getOccupationRate())==true || 
            previsionHMeasure.getOccupationRate() &lt; ruleOccupationRate.getThreshold()) {
                return true;
            }
        else {
                return false;
            }
</code></pre>

<p>My problem is that I get a NullPointerException when I run the test, at ruleOccupationRate.getThreshold() I guess. I think that I can overcome this difficulty using lots of when().theReturn() for each getter involved in the Service. <br/><br/>
So my question is : Why the setters I used on the //Arrange part of my test aren't working ?<br/> Is it possible to set properties to a mock object, to avoid the mocking of every call of the getters ? <br/>If so, how may i proceed ? </p>
",https://stackoverflow.com/questions/60193671/can-i-set-some-attribute-to-a-mockito-mockclass-class,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",751,False,0,0
Unit Testing a Method that Interacts with the Excel Interop Library,"<p>I'm trying to become better at writing cleaner code and developing automated tests for methods in applications so as to test the application quicker and write more flexible and extensible code. While I think I understand the basics of Unit Testing, I'm having trouble developing a test for a specific method. I've recently taken an online course on Unit Testing and I learned that in order to write Unit Tests for methods that touch external resources, you should create a class that implements the code that interacts with that external resource and extract an interface for that class so the a Mock instance can be created from the extracted interface. I think using the Excel Interop library qualifies as touching an external resource and the method I'm working on right now is meant to save an Excel file to the user's computer. The code for this method can be seen below.</p>

<pre><code>    public void Save()
    {
        if (DoesFileExistInDirectory())
        {
            semesterGradeInformationWorkbook.Save();
        }
        else
        {
            semesterGradeInformationWorkbook.SaveAs(LocationAsURL);
        }
    }

    private bool DoesFileExistInDirectory()
    {
        return File.Exists(LocationAsURL);
    }
</code></pre>

<p>in this case, if the file exists already the save function can just be called on the workbook. However, if the file doesn't exist the SaveAs operation is called on the workbook to save the file to that location. The code for the whole class can be seen here.</p>

<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace GradeCalculator
{
    public class ExcelWorksheet
    {
        private Excel.Application excelApplication;
        private Excel.Workbook semesterGradeInformationWorkbook;
        private Excel.Worksheet classInformationWorksheet;

        public string Name { get; private set; }
        public string LocationAsURL { get; private set; }
        public int UsedRows
        {
            get { return this.classInformationWorksheet.UsedRange.Rows.Count; }
        }

        public int UsedColumns
        {
            get { return this.classInformationWorksheet.UsedRange.Columns.Count; }
        }

        public ExcelWorksheet(string name)
        {
            InitializeExcel();

            Name = name;

            LocationAsURL = Path.Combine(Properties.Settings.Default.DefaultDirectory, Name + "".xlsx"");

        }

        private void InitializeExcel()
        {
            excelApplication = new Excel.Application();

            semesterGradeInformationWorkbook = excelApplication.Workbooks.Add();

            classInformationWorksheet = semesterGradeInformationWorkbook.ActiveSheet;

            excelApplication.Visible = true;
        }

        public void Save()
        {
            if (DoesFileExistInDirectory())
            {
                semesterGradeInformationWorkbook.Save();
            }
            else
            {
                semesterGradeInformationWorkbook.SaveAs(LocationAsURL);
            }
        }

        private bool DoesFileExistInDirectory()
        {
            return File.Exists(LocationAsURL);
        }
    }
}
</code></pre>

<p>Any tips on how to refactor the code so that it is more extensible and I can write a unit test for it? Any other tips on how to improve the class and methods to better implement a better object oriented design would be much appreciated as well.</p>
",https://stackoverflow.com/questions/60953843/unit-testing-a-method-that-interacts-with-the-excel-interop-library,"['c#', 'unit-testing', 'object-oriented-analysis']",704,False,1,0
Unit Testing NodaTime Aliased DateTimeZone,"<p>I am working on a unit test for my extension method.</p>

<pre><code>public static DateTimeZone GetDateTimeZone(this IDateTimeZoneProvider dateTimeZoneProvider, String timezoneId)
{
    DateTimeZone dateTimeZone;
    if ((dateTimeZone = dateTimeZoneProvider.GetZoneOrNull(timezoneId)) != null)
        return dateTimeZone;    

    // Continues to try and map from TimeZoneInfo if dateTimeZone == null
}
</code></pre>

<p>When unit testing this method, the test is failing as the alias is being returned for the DateTimeZone Id.</p>

<pre><code>[TestMethod]
public void GetDateTimeZone_DateTimeZoneProviderHasTimezoneIdAsAlias_ReturnsDateTimeZone()
{
    var expectedTimezoneId = ""America/New_York"";
    var timezoneId = ""US/Eastern"";
    var dateTimeZone = _dateTimeZoneProvider.GetDateTimeZone(timezoneId); 

    Assert.AreEqual(expectedTimezoneId, dateTimeZone.Id);
}
</code></pre>

<p>As you can see, I am expecting what is in the Zone Id column (<a href=""https://nodatime.org/TimeZones"" rel=""nofollow noreferrer"">https://nodatime.org/TimeZones</a>), but instead the alias ""US/Eastern"" is being returned.
This is especially surprising since the documentation on GetZoneOrNull (<a href=""https://nodatime.org/2.4.x/api/NodaTime.IDateTimeZoneProvider.html#NodaTime_IDateTimeZoneProvider_GetZoneOrNull_System_String_"" rel=""nofollow noreferrer"">https://nodatime.org/2.4.x/api/NodaTime.IDateTimeZoneProvider.html#NodaTime_IDateTimeZoneProvider_GetZoneOrNull_System_String_</a>)
says ""Note that this may return a DateTimeZone that has a different ID to that requested, if the ID provided is an alias.""</p>

<p>After reading, ""Note also that this method is not required to return the same DateTimeZone instance for successive requests for the same ID; however, all instances returned for a given ID must compare as equal."",
I thought, maybe the aliased DateTimeZone would equate to the unaliased.</p>

<pre><code>[TestMethod]
public void GetDateTimeZone_DateTimeZoneProviderHasTimezoneIdAsAlias_ReturnsDateTimeZone()
{
    var expectedDateTimeZone = _dateTimeZoneProvider.GetZoneOrNull(""America/New_York"");
    var timezoneId = ""US/Eastern"";
    var dateTimeZone = _dateTimeZoneProvider.GetDateTimeZone(timezoneId);

    Assert.AreEqual(expectedDateTimeZone, dateTimeZone);
}
</code></pre>

<p>But, it does not.  The code that calls the extension method doesn't really care about the Id as it is using the DateTimeZone to convert from LocalTime to Utc.</p>

<pre><code>IDateTimeZoneProvider dateTimeZoneProvider = DateTimeZoneProviders.Tzdb;
var dateTimeZone = dateTimeZoneProvider.GetDateTimeZone(timezoneId);

var zonedDateTime = dateTimeZone.AtLeniently(localDateTime);
return zonedDateTime.ToDateTimeUtc(); 
</code></pre>

<p>So, it will take whatever the current offset is at the time of localDateTime.  But, for unit testing purposes, I can't just check the offset as in the example of ""America/New_York"", because it is sometimes -5 and other times -4.  Asserting that it is either -5 or -4 in a unit test doesn't feel kosher.  How should I go about testing an aliased DateTimeZone?</p>

<h2>UPDATE</h2>

<p>Here's the updated unit test using a specific date and time in which the offset is known.</p>

<pre><code>[TestMethod]
public void GetDateTimeZone_DateTimeZoneProviderHasTimezoneIdAsAlias_ReturnsDateTimeZone()
{
    var expectedOffset = Offset.FromHours(-5);
    var specificDateTimeWithKnownUtcOffset = new DateTime(2020, 1, 15, 8, 29, 15, DateTimeKind.Utc);
    var instant = Instant.FromDateTimeUtc(specificDateTimeWithKnownUtcOffset);
    var timezoneId = ""US/Eastern"";
    var dateTimeZone = _dateTimeZoneProvider.GetDateTimeZone(timezoneId);

    Assert.AreEqual(expectedOffset, dateTimeZone.GetUtcOffset(instant));
}
</code></pre>
",https://stackoverflow.com/questions/59737549/unit-testing-nodatime-aliased-datetimezone,"['c#', 'unit-testing', 'nodatime']",529,True,1,1
Unit Testing JDBC methods with MySQL specific queries,"<p>I have a bunch of methods which run mysql specific SQLs using JDBC calls. I need to write unit or integration test for these methods that should run as part of the CI build.</p>
<p>Currently I'm using an in-memory hsql DB to do unit testing on the database, which obviously isn't compatible with these MySQL specific queries. I end up running my tests against a local mysql instance.</p>
<p>As expected this is leading to drop in code coverage and  code being dropped to production without automated testing.</p>
<p>What are my options here apart from using a central MySQL instance to run these tests?</p>
<p>Sample method for reference -</p>
<pre><code>public void bulkLoad(Connection connection) {
      String bulkLoadQuery = &quot;LOAD DATA CONCURRENT LOCAL INFILE ? REPLACE INTO TABLE my_table (id, name)&quot;
      try (PreparedStatement statement = connection.prepareStatement( bulkLoadQuery ) {
          statement.setString( 1, fileToUpload );
          statement.execute();
       }
}
</code></pre>
",https://stackoverflow.com/questions/64078422/unit-testing-jdbc-methods-with-mysql-specific-queries,"['mysql', 'unit-testing', 'continuous-integration']",46,False,0,1
Class initialization on C# Unit Test fails,"<p>New to unit testing. I need to have an app called SolidWorks start up and load a file. My initialization will not run. I get the error:</p>

<blockquote>
  <p>Class Initialization method UnitTestProject1.SolidWorksPartTests.MyClassInitialize threw exception. System.IO.FileNotFoundException: System.IO.FileNotFoundException: Could not load file or assembly 'SolidWorks.Interop.sldworks, Version=27.1.0.72, Culture=neutral, PublicKeyToken=7c4797c3e4eeac03' or one of its dependencies. The system cannot find the file specified..</p>
</blockquote>

<p>I know for certain that the reference in there. I think this has something to do with static references. My code looks like this:</p>

<pre><code>    private TestContext testContextInstance;
    private static IModelDoc2 model;
    private static SolidWorksPart solidWorksPart;
    private static ISldWorks app;

    [ClassInitialize()]
    public static void MyClassInitialize(TestContext testContext) 
    {
        string testFolderLocation = @""C:\Users\erics\source\repos\XXXXXXXXXXXX\UnitTestProject1\TestFileFolder\"";
        var progId = ""SldWorks.Application"";
        var progType = System.Type.GetTypeFromProgID(progId);
        app = System.Activator.CreateInstance(progType) as ISldWorks;
        app.Visible = false;

        string testFilePath = testFolderLocation + ""FF99999 Circle.SLDPRT"";
        int errors = 0;
        object importData = new object();
        app.LoadFile4(testFilePath, """", importData, ref errors);
        model = (IModelDoc2)app.ActiveDoc;
        solidWorksPart = new SolidWorksPart(model);

    }
</code></pre>

<p>What is wrong with my class initialization?</p>

<p><strong>EDIT</strong>
Neither the constructor or the Class initializer runs. The tests I created previously do run though.</p>
",https://stackoverflow.com/questions/60404875/class-initialization-on-c-unit-test-fails,"['c#', 'unit-testing']",867,False,0,1
Assign method (function of an object) to a variable or how to pass a parameter to unit tests,"<pre><code>extension Array where Element == Int {
    
    mutating func bubbleSort() {
        let n = count
        guard n &gt; 1 else { return }
        for i in 0 ..&lt; n {
            var isSorted = true
            for j in 1 ..&lt; n - i {
                if self[j - 1] &gt; self[j] {
                    swapAt(j - 1, j)
                    isSorted = false
                }
            }
            if isSorted { break }
        }
    }
}

import XCTest //MARK: UnitTests

class SortingTest: XCTestCase {
    
    func testSorting1() {
        var a = [9, 2, 5, 3, 8, 1, 4, 7, 6]
        a.bubbleSort()
        XCTAssertEqual(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    }
    
    func testSorting2() {
        var a = [4, 3, 2, 1]
        a.bubbleSort()
        XCTAssertEqual(a, [1, 2, 3, 4])
    }
    
    func testSorting3() {
        var a = [2, 1]
        a.bubbleSort()
        XCTAssertEqual(a, [1, 2])
    }
    
    //And many many more tests here
}

SortingTest.defaultTestSuite.run()
</code></pre>
<p>That's playground code of bubbleSort algorithm and it works totally fine.<br />
But what if I implement one more sort algorithm:</p>
<pre><code>extension Array where Element == Int {
    
    mutating func oneMoreSortAlg() {
        // Some algorithm code here
    }
    
    mutating func andEvenMoreSortAlg() {
        // Some more code here
    }
}
</code></pre>
<p>Obviously the test code will be almost the same for each algorithm. So I have to somehow pass which one I want to test now.<br />
I'm new to Unit Testing so I don't know what is the canonical way to do this. I'll appreciate any hints.</p>
<p>And it raises one more question. Let's suppose I will decide to do it in this way (probably not canonical):</p>
<pre><code>class SortingTest: XCTestCase {
    let customSort = Array.object.oneMoreSortAlg //it's defenetly a wrong syntax
    
    func testSorting1() {
        var a = [9, 2, 5, 3, 8, 1, 4, 7, 6]
        a.customSort() // or maybe customSort(a), I really don't know
        XCTAssertEqual(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    }
    
    func testSorting2() {
        var a = [4, 3, 2, 1]
        a.customSort() // or maybe customSort(a), I really don't know
        XCTAssertEqual(a, [1, 2, 3, 4])
    }
    
    func testSorting3() {
        var a = [2, 1]
        a.customSort() // or maybe customSort(a), I really don't know
        XCTAssertEqual(a, [1, 2])
    }
    
    //And many many more tests here
}
</code></pre>
<p>I'm not new to swift but I've realised that I don't know how to correctly manage an assignment of method to a variable either.</p>
",https://stackoverflow.com/questions/63015683/assign-method-function-of-an-object-to-a-variable-or-how-to-pass-a-parameter-t,"['swift', 'unit-testing']",285,True,0,3
how to check std::is_base_of&lt;&gt; on (*this),"<p>For certain task, I didn't manage to get away without macro. Now I'd like to add at least some protection from misuse. </p>

<p>I'd like to <code>static_assert</code> that MYMACRO() is used  </p>

<ol>
<li>in a subclass of Base class,...</li>
<li>...namely, in <code>run()</code> method</li>
</ol>

<p>A naive approach fails:  </p>

<pre><code>static_assert(std::is_base_of&lt;Base, typeid(*this)&gt;::value, ""Use MYMACRO() only in subclass of Base."");
//                                  =============
//       SubOne would work, but not typeid(*this)
//
static_assert(__func__ == ""run"", ""Use MYMACRO() only in run() method."");
//            ========
//       not a constexpr?
//
</code></pre>

<p>To reproduce:  </p>

<pre><code>#ifndef __GNUG__
#error ""Needs GCC C++""
#endif

#define MYMACRO() \
{\
    do { \
    /*&gt; &gt; &gt; want static_assert'ions here &lt; &lt; &lt;*/\
    /*here comes stuff I coudn't put into an [inline] function,*/ \
    /*because it contains GCC Labels-as-Values and */ \
    /*conditional return;*/ \
    } while(false);\
}

class Base {
public:
    virtual int run() = 0;
};

class SubOne : Base {
public:
    int run() override {
        // ...
        MYMACRO();
        // ...
    };
};

class SubTwo : Base {
public:
    int run() override {
        // ...
        MYMACRO();
        // ...
    };
};

int main(void) 
{
    SubOne sub1;
    SubTwo sub2;
    //a little embedded app
    while (true) {
        sub1.run();
        sub2.run();
    }
}
</code></pre>

<p>Anticipating possible questions:<br>
What is it for? - <a href=""http://dunkels.com/adam/dunkels06protothreads.pdf"" rel=""nofollow noreferrer"">http://dunkels.com/adam/dunkels06protothreads.pdf</a><br>
Labels as values: - <a href=""https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html"" rel=""nofollow noreferrer"">https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html</a><br>
Why not ""proper"" <a href=""https://freertos.org/"" rel=""nofollow noreferrer"">RTOS</a> with context switching? - I expect the above solution to simplify unit testing under native architecture, side-stepping the need for <a href=""https://docs.zephyrproject.org/1.12.0/boards/posix/native_posix/doc/board.html"" rel=""nofollow noreferrer"">native (POSIX) port</a> or <a href=""https://docs.platformio.org/en/latest/plus/debug-tools/qemu.html"" rel=""nofollow noreferrer"">QEMU</a>/<a href=""https://docs.platformio.org/en/latest/plus/debug-tools/renode.html"" rel=""nofollow noreferrer"">renode</a> or <a href=""https://docs.platformio.org/en/latest/tutorials/ststm32/stm32cube_debugging_unit_testing.html#tutorial-stm32cube-debugging-unit-testing"" rel=""nofollow noreferrer"">target board</a>. (Not for all, but for many tests)</p>
",https://stackoverflow.com/questions/61012629/how-to-check-stdis-base-of-on-this,"['c++', 'gcc', 'typetraits', 'static-assert', 'protothread']",188,True,0,2
"Writing to file a.txt, whilst terminal is redirected to file b.txt","<p>I have a program running as such:</p>

<pre><code>./program &amp;&gt; b.txt
</code></pre>

<p>And the ""program"" executable writes to another file, ""a.txt"" as shown:</p>

<pre><code>std::ofstream file;
file.open (""a.txt"", std::ios::out);
file &lt;&lt; ""content: "" &lt;&lt; some_param &lt;&lt; ""\n"";
file.close();
</code></pre>

<p>and of course, the ""program"" executable outputs some other text as such:</p>

<pre><code>std::cout &lt;&lt; ""..."";
std::cerr &lt;&lt; ""..."";
</code></pre>

<p>The problem is this; ""a.txt"" has some content, that should normally be on ""b.txt"", and also, the function that writes to ""a.txt"" looks like it runs only once, while normally, that function should have ran 12-13 times.</p>

<p>It may be helpful to mention that the function that writes to ""a.txt"" is called from GoogleTest Unit Testing framework, however, the std::cout or cerr functions could be called from anywhere.</p>

<p>What could be the problem?</p>
",https://stackoverflow.com/questions/62467128/writing-to-file-a-txt-whilst-terminal-is-redirected-to-file-b-txt,"['c++', 'linux', 'googletest']",37,False,0,1
How to unit test Nest Interceptor,"<p>I'm looking for some insight on unit testing an interceptor in <code>Nestjs</code>, please bare with my limited understanding of unit tests as I'm still fairly new to them, so feel free to explain concepts that seem rather trivial, as I would appreciate it nonetheless!</p>
<p>Just for the sake of this question, I'll borrow the code from the <code>Nestjs</code> documentation, specifically, the <code>LoggingInterceptor</code>, since that's the one I implemented in my project.</p>
<h2>Here is the logging interceptor from the official docs.</h2>
<pre><code>import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    console.log('Before...');

    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() =&gt; console.log(`After... ${Date.now() - now}ms`)),
      );
  }
}
</code></pre>
<p>I've tried and failed a few times at setting up a simple unit test that just shows the <code>console.log</code> was called twice, once before the <code>next</code> call is made, and once after.</p>
",https://stackoverflow.com/questions/60197250/how-to-unit-test-nest-interceptor,"['typescript', 'nestjs']",1147,True,0,1
Unit Testing a Class With A Private Constructor,"<p>I am trying to test a class that only has a private constructor.  This is for a course registration system.  The courses do not get create via our application, therefore we intentionally have no public constructor.  Instead we use EF to get the courses that are already in the database, and register students to them.</p>
<p>I am trying to test the register method of the Course class, however I have no way of creating an instance. I could use
<code>course = (Course)Activator.CreateInstance(typeof(Course), true);</code>, but then I don't have a way to setup the necessary properties since those are private.</p>
<p>What is the recommended approach for unit testing without a constructor?</p>
<p>This is a slimmed down version of the code.</p>
<pre><code>public class Course
{
    private Course()
    {
    }

    public int Id { get; private set; }
    public string Name { get; private set; }
    public bool Open { get; private set; }
    public virtual ICollection&lt;Student&gt; Students { get; private set; }

    public void Register(string studentName)
    {
        if (Open)
        {
            var student = new Student(studentName);
            Students.Add(student);
        }
    }
}
</code></pre>
<p>// Usage //</p>
<pre><code>using (var db = new SchoolContext())
        {
            var course = db.Courses.Include(x =&gt; x.Students).Where(x =&gt; x.Name == courseName).First();

            course.Register(studentName);
            db.SaveChanges();
        }
</code></pre>
<p>// Unit Test //</p>
<pre><code>[Fact]
public void CanRegisterStudentForOpenClass(){
    // HERE I HAVE NO WAY TO CHANGE THE OPEN VARIABLE
    var course = (Course)Activator.CreateInstance(typeof(Course), true);
    course.Register(&quot;Bob&quot;);
}



    
</code></pre>
",https://stackoverflow.com/questions/63400165/unit-testing-a-class-with-a-private-constructor,"['c#', '.net', 'unit-testing', 'xunit']",2002,True,5,5
How to simulate &quot;Space&quot; or &quot;Enter&quot; key on a focused button?,"<p>On a focused button, when user hits ""Space"" or ""Enter"" key, browser will synthesise a click event on top of those keyboard events.</p>

<p>I tried to simulate keydown, keyup of a ""Space"" key on a focused button, but could not find the way to let browser synthesise a click event.</p>

<pre class=""lang-js prettyprint-override""><code>document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{which: 32, keyCode: 32, key: ' ', code: 'Space'}));
document.activeElement.dispatchEvent(new KeyboardEvent('keyup',{which: 32, keyCode: 32, key: ' ', code: 'Space'}));
</code></pre>

<p>Here is what I got so far <a href=""https://jsfiddle.net/s21f9pg7/"" rel=""nofollow noreferrer"">https://jsfiddle.net/s21f9pg7/</a></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const btn = document.querySelector('#btn');

btn.onclick = function(e) {
  console.log('click', e.type);
}
btn.onkeydown = function(e) {
  console.log('keydown', e.type);
}
btn.onkeypress = function(e) {
  console.log('keypress', e.type);
}
btn.onkeyup = function(e) {
  console.log('keyup', e.type);
}

setTimeout(() =&gt; {
  btn.focus();
  document.activeElement.dispatchEvent(new KeyboardEvent('keydown', {
    which: 32,
    keyCode: 32,
    key: ' ',
    code: 'Space'
  }));
  /* document.activeElement.dispatchEvent(new KeyboardEvent('keypress',{which: 32, keyCode: 32, key: ' ', code: 'Space'})); */
  setTimeout(() =&gt; {
    document.activeElement.dispatchEvent(new KeyboardEvent('keyup', {
      which: 32,
      keyCode: 32,
      key: ' ',
      code: 'Space'
    }));
  }, 200);
}, 200)</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;button id=""btn""&gt;click&lt;/button&gt;</code></pre>
</div>
</div>
</p>

<p>This snippet issue a keydown and a keyup on a focused button, no click event was fired.
<strong>However, if you manually hit space key, there will be a click event along with keyboard events.</strong></p>

<p>I am trying to find a way to do unit testing on focused button. Thanks for help!</p>
",https://stackoverflow.com/questions/61376771/how-to-simulate-space-or-enter-key-on-a-focused-button,"['javascript', 'html']",791,False,0,0
Preprocessor doesn&#39;t work for removing code from top level,"<p>I need to have a file input that can be executed as both - main for output, and a module for unit testing(because apparently you can't run tests again main.swift).</p>
<p>Let's say I have a file like this:</p>
<pre><code>class Hello {}
#if RELEASE
  print(&quot;hello&quot;)
#endif
</code></pre>
<p>Now, the idea here is that I can put this input into either a main.swift or something.swift and use a flag to remove the print(&quot;hello&quot;) when not in main.swift.</p>
<p>But it seems that no matter what I still get the error:</p>
<blockquote>
<p>error: expressions are not allowed at the top level print(&quot;hello&quot;)</p>
</blockquote>
<p>Is it possible to achieve what I want with the flags, or there's something weird going?</p>
",https://stackoverflow.com/questions/62913796/preprocessor-doesnt-work-for-removing-code-from-top-level,"['swift', 'linux']",31,False,0,0
How can I get nameof() functionality for the parameter name of a method called,"<p>The simplest way for me to describe this is in the Unit Testing context.</p>

<p>I have a method that accepts a parameter and asserts that parameter isn't null.</p>

<pre class=""lang-cs prettyprint-override""><code>public void DoStuff(string requirementName)
{ 
    if (requirementName == null) throw new ArgumentNullException(nameof(requirementName)); 
}
</code></pre>

<p>Then I have a test that asserts this exception is thrown.</p>

<pre class=""lang-cs prettyprint-override""><code>[Test]
public void NullRequirementName_ThrowsArgNullException()
{
    var sub = new DoStuffClass();
    Action doStuff = () =&gt; sub.DoStuff(null);
    doStuff.Should().Throw&lt;ArgumentNullException&gt;(); 
}
</code></pre>

<p>What I want is to assert that the message of the exception contains the name of the parameter, and yet allow the parameter name in the signature of <code>DoStuff</code> to change and give compile time indication that the name is changed.</p>

<pre class=""lang-cs prettyprint-override""><code>[Test]
public void NullRequirementName_ThrowsArgNullException()
{
    var sub = new DoStuffClass();
    Action doStuff = () =&gt; sub.DoStuff(null);
    doStuff.Should().Throw&lt;ArgumentNullException&gt;().Where(ex =&gt; ex.Message.Contains(""requirementName""); 
}
</code></pre>

<p>The above assertion works fine, but doesn't allow the param name to change without breaking the test at run-time. I'm looking for a simple looking syntax that effectively gives me <code>nameof(DoStuffClass.DoStuff.requirementName)</code></p>
",https://stackoverflow.com/questions/59884728/how-can-i-get-nameof-functionality-for-the-parameter-name-of-a-method-called,"['c#', '.net', '.net-core']",50,False,0,0
Unit testing the creation of an entry in the database,"<p>I'm wanted to write a simple unit test for a service.
This is the method in my service which I want to unitest.</p>

<pre><code>@Log4j
@Service
public class Service {

     @Autowired
     private Repository repository;

    public JpaRecord create(JpaRecord jpaRecord) {
        return repository.save(jpaRecord);
    }
}
</code></pre>

<p>This method just creates a new entry in the Database.</p>

<p>This is the JpaRecord: </p>

<pre><code>@Data
@Entity
@Table(name = ""TEST"", schema = ""TEST"")
public class JpaRecord implements Serializable {
    private static final long serialVersionUID = 1L;

    JpaRecord() {
        // default constructor
    }

    public JpaRecord(
            String name,
            Date createdAt,
            Blob file
    ) {
        this.name = name;
        this.createdAt = createdAt;
        this.file = file;
    }

    @Id
    @Column(name = ""ID"", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = ""TEST_SEQx"")
    @SequenceGenerator(
            sequenceName = ""TEST_SEQ"", allocationSize = 1,
            name = ""TEST_SEQx"")
    private Long id;

    @Column(name = ""NAME"")
    private String name;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = ""CREATED_AT"")
    private Date createdAt;

    @Lob
    @Column(name = ""FILE"")
    private Blob file;
}
</code></pre>

<p>The <strong>id</strong> should not be null, all the other entries can be null.
I wrote this test to check if the DB entry is not null, which means it is created.</p>

<pre><code>public class ServiceTest {

    @Autowired
    private Service Service;

    @Autowired
    private JpaRecord JpaRecord;

    @Before
    public void setUp(){

    }

    @Test
    public void testCreateWhenNull(){
        // prepare data
        JpaRecord = new JpaRecord(""testProject"", new Date(),null);
        // run

        // test with assert
        Assert.assertNotNull(Service.create(JpaRecord));
    }

}
</code></pre>

<p>I then get a java.lang.NullPointerException!
I would really appreciate any suggestion on how I should approach a problem to unit test it. 
It is my first time unit testing and I wanted to start with a simple null check.</p>
",https://stackoverflow.com/questions/60192135/unit-testing-the-creation-of-an-entry-in-the-database,"['java', 'spring-boot', 'unit-testing']",194,True,0,1
Select month from a date field in laravel,"<p>I'm trying to perform a query in Laravel 7 that gets the month part of a date field. I tried the following queries</p>
<pre><code>$test = MyModal::selectRaw('month(&quot;date_col&quot;) as temp')-&gt;get();
$test = MyModal::select(DB::Raw('month(&quot;date_col&quot;) as temp'))-&gt;get();
$test = DB::table('my_table')-&gt;select('month(&quot;date_col&quot;) as temp')-&gt;get();
</code></pre>
<p>All variation of the same query. If I dump the query log, the query is correct for all 3</p>
<pre><code>select month(&quot;date_col&quot;) as temp from &quot;my_table&quot;
</code></pre>
<p>If I run this on my DB I get the result as well. But I keep getting this error in laravel:</p>
<p>Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such function: month (SQL: select month(&quot;date_col&quot;) as temp from &quot;my_table&quot;)</p>
<p>Am I doing something wrong? And is there a way to do this query in laravel?</p>
<p>Edit: Sorry forgot to mention this is with Laravel's unit testing</p>
",https://stackoverflow.com/questions/63998106/select-month-from-a-date-field-in-laravel,"['php', 'laravel', 'eloquent']",1064,True,0,3
JUnit Testing FaceContext and Session Code,"<p>I am attempting to Junit test (IDE: Intellij) Method inside a class called ""ManagementDashboardBean"" called: (Method name): init()
The method contains FaceContext and Session. I tried the following: <a href=""https://codenotfound.com/mockito-unit-testing-facescontext-powermock-junit.html"" rel=""nofollow noreferrer"">https://codenotfound.com/mockito-unit-testing-facescontext-powermock-junit.html</a>
but am still running into issues. I am using Mockito and PowerMockito to help but cannot figure out my init() is saying Null Pointer Exception (NPE). Any guidance would be greatly appreciated. Thanks</p>

<p>P.S the end goal is to show proper test code coverage of this method. </p>

<pre><code>   public void init() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession)context.getExternalContext().getSession(false);
        userInfo = (UserSessionInfo)session.getAttribute(ConstantsUtil.USER_INFO);

        startDt = FDUtil.toDate(FDUtil.toStartOfMonth(userInfo.getCurrentDateMillis()));
        endDt = FDUtil.toDate(FDUtil.toEndOfMonth(userInfo.getCurrentDateMillis()));

        autoCompleteDate = false;
    }
</code></pre>

<p>Current JUnit Test</p>

<pre><code>package view.managed.core;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.sun.jdi.connect.Connector;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
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({FacesContext.class})

public class ManagementDashboardBeanTest {

    private ManagementDashboardBean someBean;

    @Mock
    private FacesContext facesContext;
    @Mock
    private ExternalContext externalContext;

    @Before
    public void setUp() throws Exception {
        someBean = new ManagementDashboardBean();

        //mock all static methods of FaceContext using PowerMockito
        PowerMockito.mockStatic(FacesContext.class);

        when(FacesContext.getCurrentInstance()).thenReturn(facesContext);
        when(facesContext.getExternalContext()).thenReturn(externalContext);
    }

    @Test
    public void testInitContext() {
        //create Captor instances for the userInfo
//        ArgumentCaptor&lt;String&gt; clientIdCapture = ArgumentCaptor.forClass(String.class);
//        ArgumentCaptor&lt;HttpSession&gt; session = ArgumentCaptor.forClass(HttpSession.class);
        // Run the method being tested
//        someBean.init();

//        verify(facesContext).addMessage(clientIdCapture.capture(), (FacesMessage) session.capture());

    }

}
</code></pre>

<p>The actual .java source file starts with:</p>

<pre><code>public class ManagementDashboardBean extends EntityManagerService implements Serializable {

    private static final Logger LOG = LoggerFactory.getLogger(ManagementDashboardBean.class);
</code></pre>

<p>The right after is this, which confuses the hell out of me:</p>

<pre><code>public ManagementDashboardBean() {
        init();
    }
</code></pre>

<p>What I have added so far:</p>

<pre><code>
import static org.junit.Assert.*;
import javax.faces.context.FacesContext;
import mil.af.fd.view.managed.services.EntityManagerService;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;
import java.io.Serializable;

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({FacesContext.class})

public class ManagementDashboardBeanTest {

    private ManagementDashboardBean dashboard;
    private Serializable serializableMock;
    private EntityManagerService entityManagerServiceMock;

    @BeforeClass
    public static void before() {
        System.out.println(""Before Class"");
    }

    @Before
    public void setUp() throws Exception {
        entityManagerServiceMock = Mockito.mock(EntityManagerService.class);
        serializableMock = Mockito.mock(Serializable.class);
        dashboard = new ManagementDashboardBean(serializableMock);
    }

    @Test
    public void testInitContext() {
//          dashboard.init();
        System.out.println(""Test 1"");
    }

}
</code></pre>
",https://stackoverflow.com/questions/60104684/junit-testing-facecontext-and-session-code,"['java', 'intellij-idea', 'mockito', 'junit4', 'powermockito']",206,False,0,0
Mock Non-existent Interface in PHP,"<p>I am new to PHP unit testing and I need some clarity on how can we mock non-existent Interface. Basically, In my project, I want to test one protected method which is expecting two arguments one is Interface and another is a string.</p>
<p>I want to understand how can I pass Interface as an argument in a method. I tried to Mock the Interface but it's not working for me.</p>
<p>This is my main class</p>
<pre><code>
namespace App\Models;

class VerifyNs {
    protected function NsCheck(SomeInterface $url, string $domain) {
        $answer= dns_get_record($domain, DNS_NS);
        if (!empty($answer[0]['target']), ('example.com' == substr($answer[0]['target'], -11)) {
            $result = 'NS verification for @url passed., ['@url ' =&gt; $url -&gt;getName()]';
            return $result
        }

        return 'failed;
    }

    
}
</code></pre>
<p>Here is the test case</p>
<pre><code>
class VerifyNsTest extends \PHPUnit\Framework\TestCase
{
    /**
     * To call protected method
     * @param $object
     * @param string $method
     * @param array $parameters
     * @return mixed
     * @throws \Exception
     */
    private function callMethod($object, string $method , array $parameters = [])
    {
        try {
            $className = get_class($object);
            $reflection = new \ReflectionClass($className);
        } catch (\ReflectionException $e) {
           throw new \Exception($e-&gt;getMessage());
        }

        $method = $reflection-&gt;getMethod($method);
        $method-&gt;setAccessible(true);

        return $method-&gt;invokeArgs($object, $parameters);
    }

    /**
    * Tests for verifying NS of the domain.
    *
    * @dataProvider providerTestNsCheck
    */
    public function testCheckNs($site, $url, $expected_result) {
        $site_name = $this-&gt;getMockBuilder(SomeInterface::class)
                          -&gt;setMethods(['getName'])
                          -&gt;getMock();
        
        $site_name-&gt;method('getName')-&gt;willReturn($site);

        $verifyNs = new \App\Models\VerifyNs();
        $this-&gt;assertEquals($expected_result, $this-&gt;callMethod($verifyNs, 'NsCheck', [ $site_name, $url]));
    }

    /**
     * Data provider for testCheckNs().
     *
     */
    public function providerTestNsCheck() {
        return [
        [
            'mysite',
            'example.com',
            'NS verification for mysite passed.',
       
        ],       [   
            'google',
            'google.com',
            'failed.'
            ]
        ],
        ];
    }

}
</code></pre>
<p>After running this, it's giving me an error</p>
<p><code>TypeError: Argument 1 passed to App\Models\VerifyNs::NsCheck() must be an instance of App\Models\SomeInterface, instance of Mock_SomeInterface_1ee04960 given</code></p>
<p>Can someone please help here? Is it possible to mock non_existent Interface and pass it as an argument to the method?</p>
",https://stackoverflow.com/questions/63459272/mock-non-existent-interface-in-php,"['php', 'drupal', 'mocking', 'phpunit']",46,True,0,1
Unit Testing an ngx-formly Custom Template,"<p>I am working with <a href=""https://formly.dev/"" rel=""nofollow noreferrer"">Formly</a> and created a couple Custom Templates. The only code included in the component is a call to a general error handling service, so there is really almost nothing to test other than that the component can be created. I am using only Jest for unit testing, but cannot figure out what I need to include to have the component compile successfully.</p>
<p>The error I am getting is: TypeError: Cannot read property 'formControl' of undefined. I am not sure what I am missing in my test.</p>
<p>For the simplest component (mainly styling and a directive - removed for now), I have the following:</p>
<p>Component:</p>
<pre><code>@Component({
  selector: 'my-formly-field-input',
  templateUrl: './formly-field-input.component.html',
  styleUrls: ['./formly-field-input.component.scss']
})
export class FormlyFieldInputComponent extends FieldType {

  constructor(private formErrorService: FormErrorHandlerService) {
    super();
  }

  getError(formItem: FormControl | FormGroup | FormArray): string {
    return this.formErrorService.getFormError(formItem);
  }

}
</code></pre>
<p>View:</p>
<pre><code>&lt;mat-form-field [floatLabel]=&quot;'always'&quot; 
                class=&quot;w-100&quot; 
                [appearance]=&quot;'fill'&quot;&gt;
    &lt;mat-label&gt;{{field.templateOptions.label}}&lt;/mat-label&gt;
    &lt;input matInput 
           [formControl]=&quot;formControl&quot;
           [type]=&quot;field.templateOptions.type || 'text'&quot;
           [step]=&quot;field.templateOptions.step || 1&quot;
           [max]=&quot;field.templateOptions.max || undefined&quot;/&gt;
    &lt;mat-error *ngIf=&quot;formControl.errors&quot;&gt;
        {{getError(formControl)}}
    &lt;/mat-error&gt;
&lt;/mat-form-field&gt;
</code></pre>
<p>Unit Test:</p>
<pre><code> describe('FormlyFieldInputComponent', () =&gt; {
  let component: FormlyFieldInputComponent;
  let fixture: ComponentFixture&lt;FormlyFieldInputComponent&gt;;

  const formHelperServiceStub: Partial&lt;FormErrorHandlerService&gt; = {
    getFormError: (formItem) =&gt; 'Error Happened'
  };

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        FormlyFieldInputComponent
      ],
      imports: [
        MyHelpersModule,
        BrowserAnimationsModule,
        FormlyModule.forRoot(),
        FormlyMaterialModule,
        MatFormFieldModule,
        MatInputModule,
        ReactiveFormsModule,
      ],
      providers: [
        { provide: FormErrorHandlerService, useValue: formHelperServiceStub }
      ],
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p>Thanks in advance!!</p>
",https://stackoverflow.com/questions/64380872/unit-testing-an-ngx-formly-custom-template,"['angular', 'angular-material', 'jestjs', 'ngx-formly']",2532,True,4,1
"Best practice for Unit Testing class which is mostly responsible to call methods of dependencies, but contains logic as well","<p>Let's assume I have <code>StartCommandHandler</code> which has responsibility to create some file with required files. But for doing this I have to give him a set of sub-responsibilities, like:</p>

<ul>
<li>Checks whether file exists in the FTP</li>
<li>If Not downloads files from multiple sources to the temp folder</li>
<li>Then executes some script in the folder</li>
<li>Then read generated file after script execution</li>
<li>Then create zip from that folder</li>
<li>Then remove that folder</li>
<li>Then updates database</li>
</ul>

<p>As a result of that Command Handler, we are creating folder with all required files. And now that folder is ready for another operations.</p>

<p>I have just read <code>""Art of the Unit testing""</code>. And started to add unit tests. I have followed <code>SOLID</code> principles as well. Especially, <code>SRP</code> and <code>DIP</code>, which are in my opinion prerequisites for Unit Testing.
So, most of that things which I stated above are done with specific interfaces. So, 90% job of that Command Handler is to call methods of dependencies. And 10% is the logic like this:</p>

<pre><code>if(!_dependency1.IsAnySomething())
{
     _dependency2.Download();

      var isScriptNeeded = _dependency2.IsScriptNeeded();

      if(isScriptNeeded)
      {
          var res = _dependency3.ExecuteScript();
         _dependency4.SetScriptResult(res.Info, res.Date, res.State);
      }

     _dependency3.Archive();

     _dependency5.DeleteTemp();
}
</code></pre>

<p>I already tested all dependencies of that command handler. But, hat command handler also includes some small logics like, is download file needed, or temp files are deleted or not and so on...</p>

<p><strong><em>I have so many question in my mind like:</em></strong></p>

<ol>
<li>May be Unit Testing doesn't make sense for such units? Integration Test to the rescue? Because, it seems wrong to test whether to check all calls, like whether <code>DeleteTemp</code> is called after download, or script is executed or not, or <strong><em>script result is passed in a right way</em></strong> to <code>SetScriptResult</code> method. Is it GOOD Unit Test?</li>
<li>Is there any way to refactor that class for making it testable?</li>
</ol>
",https://stackoverflow.com/questions/61848902/best-practice-for-unit-testing-class-which-is-mostly-responsible-to-call-methods,"['java', 'c#', 'unit-testing', 'testing', 'integration-testing']",1082,True,5,5
java.time.temporal.ValueRange bug when constructing,"<p>I am working with some time stuff in a project, and as I was implementing unit testing, I am not sure if I have found a bug, or if I have have just misunderstood the documentation.  The javadocs for <strong><a href=""https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/time/temporal/ValueRange.html#of(long,long,long)"" rel=""nofollow noreferrer""><code>ValueRange.of(long min, long maxSmallest, long maxLargest)</code></a></strong> state:</p>

<pre><code> * @return the ValueRange for min, smallest max, largest max, not null
 * @throws IllegalArgumentException if
 *     the minimum is greater than the smallest maximum,
 *  or the smallest maximum is greater than the largest maximum
</code></pre>

<p>The way I read that is if the value passed for min is larger than the value for maxSmallest, it should throw an exception.  However, the following code works:</p>

<p><code>ValueRange vr = ValueRange.of(5, 2, 10);</code></p>

<p>I think this should fail.  The value for min is larger than the value for smallest maximum, but no exception is thrown.  In addition, when printing the resulting ValueRange, it looks very strange:  <em>5 - 2/10</em></p>

<p>Is this a bug?  Or am I just not understanding the javadocs?</p>
",https://stackoverflow.com/questions/60301507/java-time-temporal-valuerange-bug-when-constructing,['java'],104,True,4,1
Visual Studio - C# Console App - How to write a unit test and testable code,"<p>I'm new to unit testing and would like to unit test part of my code.</p>
<p>The code attempts to connect to a database N times to get a list of tasks, if it exhausts the attempts it throws an exception to the caller.</p>
<p>I've done by best to write it in a testable way trying to keep AttemptRecursive referentially transparent.</p>
<p>I'd like to write tests that for example fail on the 1st/2nd attempt to check my code behaves correctly but I'm struggling to write the code in a way that will allow that as I can't stop in the middle of the recursive call in my Attempter class.</p>
<p>There seems to be a lot of differing opinions around the how &amp; whys of unit tests so I'm not sure if I've just completely missed the point!</p>
<p>Essentially my thought is the database could go down and I'd like to test that when it happens my code behaves correctly.</p>
<p>I've read articles on unit testing - a lot of them are on what to test for and whether it's useful but not on how to write code that's open to testing. The examples are of functions like factorials where the tests are just if the returned list contains the expected values.</p>
<p>Any help or just pointing in the right direction would be greatly appreciated!</p>
<p>Thanks</p>
<p><strong>Attempter.cs</strong> - <em>Handles attempting an action N times then throwing exception to bubble up to the caller</em></p>
<pre><code>public class Attempter&lt;T&gt;
    {
        private int _defaultMaximumAttempts;
        private int _defaultStartingMillisecondsTillNextTry;

        public Attempter(int defaultMaximumAttempts, int defaultStartingMillisecondsTillNextTry)
        {
            _defaultMaximumAttempts = defaultMaximumAttempts;
            _defaultStartingMillisecondsTillNextTry = defaultStartingMillisecondsTillNextTry;
        }


        public void Attempt(T sender, Action action)
        {
            AttemptRecursive(
                sender: sender,
                action: action,
                attemptNumber: 1,
                maximumAttempts: _defaultMaximumAttempts,
                millisecondsTillNextTry: _defaultStartingMillisecondsTillNextTry);
        }


        public void AttemptRecursive(T sender, Action action, int attemptNumber, 
               int maximumAttempts, int millisecondsTillNextTry)
        {
            try
            {
                action.Invoke();
                return;
            }
            catch (Exception ex)
            {
                if(attemptNumber &gt;= maximumAttempts)
                {
                    throw;
                }
                else
                {
                    Thread.Sleep(millisecondsTillNextTry);
                    AttemptRecursive(sender, action, attemptNumber + 1, 
                         maximumAttempts, millisecondsTillNextTry * 2);
                }
            }
        }
</code></pre>
<p><strong>DatabaseService.cs</strong> - <em>Uses the Attempter to attempt to connect to the database and run queries</em></p>
<pre><code>public class DatabaseService
    {
        private Attempter&lt;DatabaseService&gt; _attempter;

        public SqlConnectionStringBuilder ConnectionStringBuilder { get; set; }

        public DatabaseService(SqlConnectionStringBuilder connectionStringBuilder)
        {
            ConnectionStringBuilder = connectionStringBuilder;
            _attempter = new Attempter&lt;DatabaseService&gt;(
                maximumAttempts: 1,
                startingMillisecondsTillNextTry: 1000);
        }

        public DatabaseService(SqlConnectionStringBuilder connectionStringBuilder, 
             Attempter&lt;DatabaseService&gt; attempter)
        {
            ConnectionStringBuilder = connectionStringBuilder;
            _attempter = attempter;
        }

        public void AttemptExecuteNonQuery(string cmdText)
        {
            _attempter.Attempt(
                    sender: this,
                    action: () =&gt; ExecuteNonQuery(cmdText));
        }

        private void ExecuteNonQuery(string cmdText)
        {
            using (var con = new SqlConnection(ConnectionStringBuilder.ConnectionString))
            {
                con.Open();          
                //con.State == System.Data.ConnectionState.Open
                using (var cmd = new SqlCommand(cmdText, con))
                {
                    cmd.ExecuteNonQuery();                    
                }
            }
        }

        public List&lt;T&gt; AttemptExecuteReader&lt;T&gt;(string cmdText, 
             Func&lt;SqlDataReader, T&gt; constructorFunction)
        {
            var returnList = new List&lt;T&gt;();
            _attempter.Attempt(
                    sender: this,
                    action: () =&gt; returnList = ExecuteReader&lt;T&gt;(cmdText, constructorFunction));
            return returnList;
        }

        private List&lt;T&gt; ExecuteReader&lt;T&gt;(string cmdText, Func&lt;SqlDataReader,T&gt; constructorFunction)
        {
            var returnList = new List&lt;T&gt;();
            using (var con = new SqlConnection(ConnectionStringBuilder.ConnectionString))
            {
                con.Open();
                using (var cmd = new SqlCommand(cmdText, con))
                {
                    var reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        returnList.Add(constructorFunction(reader));
                    }
                }
            }
            return returnList;
        }
    }
</code></pre>
",https://stackoverflow.com/questions/62756134/visual-studio-c-console-app-how-to-write-a-unit-test-and-testable-code,"['c#', 'unit-testing']",208,False,0,0
Should SpringRunner be used in Spring Boot with Junit 5,"<p>I am confused about the class SpringRunner.
From Stackoverflow and google did understand that <code>SpringRunner</code> and <code>SpringJunit4ClassRunner</code> are one and the same.</p>

<pre><code>@RunWith(SpringRunner.class)
</code></pre>

<p>My understanding of this class is :</p>

<ul>
<li>that as its name implies - it is a 'runner' ( it will run the Junit tests ) </li>
<li>This class is used while performing unit testing with the annotation <code>@RunWith</code></li>
<li>This annotation helps in loading a spring application context and helps ‘autowire’ dependencies.</li>
<li>This class should only be used if we need spring context bean dependencies.</li>
<li>So this class should be used with caution otherwise we will unnecessarily load spring context during testing.</li>
<li>This class helps Junit and Spring collaborate together.</li>
</ul>

<p>With Junit5 and spring boot is this class no longer required ?</p>

<p>If yes what should we be using in a spring boot and Junit5 environment then ?</p>
",https://stackoverflow.com/questions/60369022/should-springrunner-be-used-in-spring-boot-with-junit-5,"['java', 'spring', 'spring-boot']",8008,True,13,3
Is it possible to add a delay to a dotnet watch command?,"<p>I am using dotnet watch command to get automatic reloading for my application and it works quite fine. The problem I encountered is that if I do run some other tool that does something similar there is some locking of resources that happens and one of the processes fails.</p>
<p>My example is that I run live unit testing in Rider.</p>
<p>What I thought might be an easy fix is to add some delay to dotnet watch, so that live testing has some seconds heads up to run before dotnet watch will do a rebuild.</p>
<p>I did not find though any possibility for that unfortunately. Is it possible to achieve with some clever trick?</p>
",https://stackoverflow.com/questions/65319382/is-it-possible-to-add-a-delay-to-a-dotnet-watch-command,"['.net-core', 'dotnet-watch']",121,False,3,0
&quot;Cannot read property &#39;length&#39; of undefined&quot; when unit testing,"<p>I am unit-testing a component which renders a list of codes from server. </p>

<p>Response coming is of this format:</p>

<pre><code>{
  ContactActivityView :[
        {
           Code:""AB"",
           IsActive:false,
        },
        {
           Code:""BC"",
           IsActive:true,
        }
        ..
        ...
  ]
}
</code></pre>

<p>In my component.ts file I consume it in the following way:</p>

<pre><code>codesArray: ICodeModel[];

ngOnInit() {
  this.getCodes();
}

getCodes() {
    this.service.getCodes()
      .subscribe((response: ICodeModel[] | []) =&gt; {
        this.codesArray = response['ContactActivityView'];
      },
      error =&gt; console.log(error)
    );
}
</code></pre>

<p>It works fine and I am able to show my data using component.html file:</p>

<pre><code>  ..
  ...
    &lt;div  class=""message"" *ngIf=""codesArray.length === 0""&gt;
      No Data Found.
    &lt;/div&gt;
    &lt;div class=""tbl-row"" *ngFor=""let code of codesArray""&gt;
      &lt;div class=""item""&gt;
        {{ code.Code }}
      &lt;/div&gt;
      &lt;div class=""item""&gt;
        {{ code.IsActive }}
      &lt;/div&gt;
  ..
  ...
</code></pre>

<p>component.service file:</p>

<pre><code>..
...
getCodes(): Observable&lt;ICodeModel[]&gt; {
  return this._service.get(this.codeURL);
}
..
...
</code></pre>

<p>Now when I run my component.spec file it gives me an error: </p>

<pre><code>TypeError: Cannot read property 'length' of undefined
</code></pre>

<p>I realized that in .html my <code>codesArray</code> is <code>undefined</code> due to which length is <code>undefined</code>.</p>

<p>I <code>console</code> my <code>codesArray</code>. It is showing data in comp.ts file but comes <code>undefined</code> in comp.spec file</p>

<p>Not sure what am I doing wrong as I am able to render the data properly, but somehow my test is failing.
Here's my component.spec file</p>

<pre><code>..
...
class MockCodesService {
  getCodes(): Observable&lt;ICodeModel[]&gt; {
    return of([]);
  }

  addCode(param: ICodeModel){
    return of({});
  }

  updateCode(param: ICodeModel) {
    return of({});
  }
}

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        CodesComponent
      ],
      providers: [
        { provide: CommonCrudService, useClass: CommonCrudMockService },
        { provide: MessageService, useClass: MessageMockService },
        { provide: AppService, useClass: AppMockService },
        { provide: CodesService, useClass: MockCodesService }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>Thanks.</p>
",https://stackoverflow.com/questions/61315827/cannot-read-property-length-of-undefined-when-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-test']",7941,False,3,1
How to unit test a Web API controller using XUnit,"<p>I am trying to unit test a method within my controller in my Web API using XUnit. The role of the method is to get a single title, by ISBN, from the database. The issue I came across during unit testing is that I am unsure how to insert the dummy data that I must perform the test on, as well as how the Assert function works.</p>

<p><strong>TitleController.cs</strong></p>

<pre><code>[ApiController]
[Route(""titlecontroller"")]
public class TitleController : Controller
{
    private IGtlTitleRepository _gtlTitleRepository;

    public TitleController(IGtlTitleRepository gtlTitleRepository)
    {
        _gtlTitleRepository = gtlTitleRepository;
    }

    [Route(""getTitle/{ISBN}"")]
    [HttpGet()]
    public GtlTitle GetTitle(string ISBN)    
    {
        return _gtlTitleRepository.GetTitle(ISBN);
    }
}
</code></pre>

<p><strong>IGtlTitleRepository.cs</strong></p>

<pre><code>    public interface IGtlTitleRepository
{
    GtlTitle GetTitle(string ISBN);
}
</code></pre>

<p><strong>MockGtlTitleRepository.cs</strong></p>

<pre><code>    public class MockGtlTitleRepository : IGtlTitleRepository
{
    private readonly string _connection;
    public MockGtlTitleRepository(IOptions&lt;ConnectionStringList&gt; connectionStrings)
    {
        _connection = connectionStrings.Value.GTLDatabase;
    }


    private List&lt;GtlTitle&gt; _titleList;

    public GtlTitle GetTitle(string ISBN)
    {
        using (var connection = new SqlConnection(_connection))
        {
            connection.Open();
            return connection.QuerySingle&lt;GtlTitle&gt;(""GetTitleByISBN"", new { ISBN }, commandType: CommandType.StoredProcedure);
        }
    }

}
</code></pre>

<p>Right, as for my test code, I was able to write the following code, but as I said above, I can't figure out a proper way to test the method.</p>

<pre><code> public class UnitTest1
{
    [Fact]
    public void Test1()
    {

        var repositoryMock = new Mock&lt;IGtlTitleRepository&gt;();
        var title = new GtlTitle();
        repositoryMock.Setup(r =&gt; r.GetTitle(""978-0-10074-5"")).Returns(title);
        var controller = new TitleController(repositoryMock.Object);

        var result = controller.GetTitle(""978-0-10074-5"");
       // assert??
        repositoryMock.VerifyAll();
    }
}
</code></pre>

<p>What should be done within this unit test in order to properly test the method?</p>

<p><strong>EDIT:</strong></p>

<p><strong>GtlTitle.cs</strong></p>

<pre><code>public class GtlTitle
{
    public string ISBN { get; set; }
    public string VolumeName { get; set; }
    public string TitleDescription { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PublisherName { get; set; }

}
</code></pre>
",https://stackoverflow.com/questions/61999456/how-to-unit-test-a-web-api-controller-using-xunit,"['c#', 'unit-testing', 'xunit', 'webapi']",8140,True,3,1
Mocking indirect dependencies with Jest,"<p>I am new to Jest and unit testing and I am not sure how to handle mocking in case of relatively deep invocation structures. Let's say we have the following app structure:</p>

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

<p>Given the grey classes (<code>axios</code> and <code>cache</code>) are external, 3rd party modules, I need to write unit tests for <code>Domain.createUser</code> and <code>Backend.postUsers</code> methods.</p>

<p>I have clear that within the <code>Backend.postUser</code> tests I need to mock <code>axios</code>. </p>

<p>In case of <code>Domain.createUser</code>, I would certainly mock <code>cache</code>, but I am not sure what to do with its second dependency.</p>

<p>Should I just mock <code>Backend.postUser</code> (as a direct dependency) or somehow indirectly mock just <code>axios</code> (as external dependency)?</p>

<p>Or both approaches work in different setups?</p>

<p>If so, what criteria should I use to make decision what is the best strategy?</p>
",https://stackoverflow.com/questions/61855366/mocking-indirect-dependencies-with-jest,"['node.js', 'unit-testing', 'mocking', 'jestjs']",1030,True,2,1
Why should we use Jasmine Spy Object in Angular Unit Testing?,"<p>I have a query regarding Angular unit testing using Jasmin/Karma.</p>
<p>I have 3 services as below: EmployeeService, SalaryService and TaxationService.</p>
<p>EmployeeService depends on SalaryService which is injected in it's constructor.</p>
<p>SalaryService depends on Taxation service which is again injected in it's constructor.</p>
<p>In my employee.component.spec.ts, I have the below code:</p>
<pre><code>let employeeService: EmployeeService;
let salaryServiceSpy: jasmine.SpyObj&lt;SalaryService&gt;;

TestBed.configureTestingModule({
 providers: [EmployeeService],
 declarations: [ EmployeeComponent ]
})
.compileComponents();
  employeeService = TestBed.inject(EmployeeService);
  salaryServiceSpy = TestBed.inject(SalaryService) as jasmine.SpyObj&lt;SalaryService&gt;;
}));

it('should return Name and Salary', () =&gt; {
  expect(employeeService.getEmployeeNameAndSalary(1)).toBe(&quot;John Smith receives: $12345 and tax value of 15%&quot;);
});
</code></pre>
<p>The code works fine, my question is why do we need to use Jasmine Spy - the code works fine without the spy service as well?</p>
<pre><code> salaryServiceSpy = TestBed.inject(SalaryService) as jasmine.SpyObj&lt;SalaryService&gt;;
</code></pre>
<p>I have used the below as reference: <a href=""https://angular.io/guide/testing-services"" rel=""nofollow noreferrer"">https://angular.io/guide/testing-services</a>.</p>
<p>If below example is more clear, what is the need to create the ValueServiceSpy? Does the TestBed.inject not already inject all dependencies and the 'dependencies of the other dependencies'?</p>
<p><a href=""https://i.stack.imgur.com/bGeWP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/bGeWP.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63578246/why-should-we-use-jasmine-spy-object-in-angular-unit-testing,"['angular', 'typescript', 'unit-testing', 'dependency-injection', 'karma-jasmine']",2769,True,2,1
How to create a unit test for a function that uses Python&#39;s http.client library using pytest and mocks?,"<p>How do I write a mock test for the following function using pytest?</p>
<pre><code>import http.client

def get_response(req_type, host, sub_domain, payload=None, headers=None,
                 body=None):

    conn = http.client.HTTPSConnection(host)
    conn.request(req_type, sub_domain, headers=headers, body=payload)
    response = conn.getresponse()

    if response.status != 200:
        raise Exception('invalid http status ' + str(response.status)
                        + ',detail body:' + response.read().decode(&quot;utf-8&quot;))

    data = response.read().decode(&quot;utf-8&quot;)
    conn.close()

    return data
</code></pre>
<p>By using the pytest_mock library and referring to the code <a href=""https://changhsinlee.com/pytest-mock"" rel=""nofollow noreferrer"">here</a>, I was able to unit tests for the other functions which use <code>get_response()</code> to perform some actions. So it's fine if we need to use even pytest_mock library to perform the unittest for <code>get_response</code>.</p>
<p>Having said that, solutions that I have seen so far are geared towards <code>requests</code> and <code>unittest</code> libraries.</p>
<p>I would like to avoid creating a http server or a Flask server for this mock-based unit-testing.</p>
<p>The <a href=""https://docs.pytest.org/en/stable/monkeypatch.html#monkeypatching-returned-objects-building-mock-classes"" rel=""nofollow noreferrer"">pytest documentation</a> seems to sugguest that I need a patch for <code>http.client.HTTPSConnection</code>, <code>conn.request()</code> &amp; <code>conn.getresponse()</code> to unit test <code>get_response()</code>.</p>
<p>Is that the case?</p>
<p>A minimal working example would be helpful.</p>
",https://stackoverflow.com/questions/63386822/how-to-create-a-unit-test-for-a-function-that-uses-pythons-http-client-library,"['python', 'unit-testing', 'mocking', 'pytest', 'pytest-mock']",880,True,2,1
Map property to property of a collection automapper,"<p>I have two entities </p>

<pre><code>public class A{
    public string Example { get; set; }
    public ICollection&lt;B&gt; BCollection { get;set; } = new HashSet&lt;B&gt;();
}

public class B {
    public string MyProperty { get; set; }
}
</code></pre>

<p>And a simple ViewModel </p>

<pre><code>public class AFirstLoadViewModel {
    public string Example { get; set; }
    public string MyProperty { get; set; }
}
</code></pre>

<p>The thing, is, this viewmodel will be use only in the first data entry, when <code>A</code> will only have one <code>B</code> object inside.</p>

<p>So, i'm trying to map a object like this: </p>

<pre><code>var source = new AFirstLoadViewModel
{
    Example = ""example"",
    MyProperty = ""myproperty""
}
</code></pre>

<p>to this </p>

<pre><code>var destination = new A {
    Example = ""example""
    BCollection = new List&lt;B&gt; {
        new B { MyProperty = ""myproperty"" }
    }
}
</code></pre>

<p>I try to do the trick using <code>ForPath</code> and <code>BeforeMap</code> without luck</p>

<pre><code>CreateMap&lt;AFirstLoadViewModel, A&gt;()
    .ForMember(x =&gt; x.Example, c =&gt; c.MapFrom(x =&gt; x.Example))
    .ForPath(x =&gt; x.BCollection.First().MyProperty, c =&gt; c.MapFrom(x =&gt; x.MyProperty))
    .BeforeMap((viewModel, entity) =&gt; {
        if(!entity.BCollection.Any())
            BCollection.Add(new B());
    });
</code></pre>

<p>But i get </p>

<blockquote>
  <p>System.ArgumentOutOfRangeException: Only member accesses are allowed.</p>
</blockquote>

<p>How can i deal with it?</p>

<p><em>I clarify: both, view model and model have many more properties, the question classes are by way of example</em></p>

<p>Edit: </p>

<hr>

<p>I try the solution proposed by Johnatan, and it works, the problem here, is that i cant Unit Testing anymore.</p>

<p>I'm testing with </p>

<pre><code>var config = new MapperConfiguration(cfg =&gt; cfg.CreateMap&lt;AFirstLoadViewModel, A&gt;(MemberList.Source));
</code></pre>

<p>And when i call <code>config.AssertConfigurationIsValid()</code> fails because the <code>MyProperty</code> property is not mapped</p>
",https://stackoverflow.com/questions/59933388/map-property-to-property-of-a-collection-automapper,"['c#', 'automapper']",2231,True,2,2
Angular testing with interval(),"<p>In my <code>ngOnInit</code> I check a route, do some stuff, and then setup an <code>interval</code></p>

<pre class=""lang-js prettyprint-override""><code>ngOnInit(): void {
    this.routeSubscription = this.route.paramMap.subscribe(x =&gt; {
         ...
         // Reload the data every 60 seconds
         interval(60_000)
             .pipe(takeUntil(this.cancelInterval$))
             .subscribe(() =&gt; this.rows$ = this.orderService.active())
    })
}
</code></pre>

<p>When I try to do my unit testing, jasmine aborts because the async method didn't return fast enough.  I'm doing this (as a sub-describe of the main one, which does all the normal <code>TestBed</code> setups):</p>

<pre class=""lang-js prettyprint-override""><code>describe('when showing active orders', () =&gt; {
    beforeEach(() =&gt; {
        activatedRoute.setParamMap({})
        fixture.detectChanges()
    })

    it('...', async () =&gt; {
        await fixture.whenStable()
        ...
    })
</code></pre>

<p>It seems to be stuck because of the interval.  I thought I could just put a call to <code>discardPeriodicTasks()</code> at the end of the <code>beforeEach</code> method, but that doesn't work.</p>

<p>So I'm looking for either the right way to handle this in testing, or a way in the production code to only make the interval call if it's not being run via testing.</p>

<p>Angular CLI: 9.0.7<br>
Node: 14.4.0<br>
Angular: 9.1.6</p>
",https://stackoverflow.com/questions/62423256/angular-testing-with-interval,"['angular', 'angular9', 'angular-test']",1229,True,2,2
Setting up QUnit tests for AJAX calls,"<p>I am attempting to use Q-Unit Testing for my code. I would like to run some tests against my AJAX queries to ensure they are running ok and returning what they should.</p>

<p>Is there anyway I could get guidance on the two ajax calls below. </p>

<p>The first AJAX <code>savePgID()</code> essentially takes in 2 numbers and then goes to the <code>pagaAJAX.php</code> page where a simple MySQL <code>INSERT</code> query runs to insert those 2 numbers into the DB.</p>

<p>The second AJAX <code>getModuleData()</code> call again goes to a PHP script where a <code>SELECT</code> query runs, which <code>GETS</code> data from the database and the AJAX just pushes the content to certain divs.</p>

<p>My 2 AJAX calls inside of
<strong>script.js:</strong></p>

<pre><code>function savePgID(moduleID, pageID){
    $.ajax({  
        url: ""pageAJAX.php"",  
        method: ""POST"",   
        data: {moduleID:moduleID, pageID:pageID},
        dataType: 'json', //ajax to expect JSON data type
      });
  }

function getModuleData(moduleID, pageID){
  console.log
  console.log(moduleID);
  console.log(pageID);
  $.ajax({  
      url: ""moduleAJAX.php"",  
      method: ""POST"",   
      data: { moduleID:moduleID, pageID:pageID },
      dataType: 'json', //ajax to expect JSON data type
      success: function(data){  
        //console.log(data);
            $('#result').html(data.result);    
            $('#modContent').html(data.modContent);  
            $('#modTitle').html(data.modTitle); 
            $('#modID').html(data.modID);
            $('#pgID').html(data.pgID);
            $('#modProgress').html(""Page "" + data.pgID); // For footer of modal overlay
      }  
  });
}
</code></pre>

<p><strong>my test.html page:</strong></p>

<pre><code>&lt;!doctype html&gt;
&lt;html lang=""en""&gt;
&lt;head&gt;
    &lt;meta charset=""UTF-8""&gt;
    &lt;title&gt;Q-Unit Tests&lt;/title&gt;
    &lt;link rel=""stylesheet"" href=""https://code.jquery.com/qunit/qunit-2.10.0.css""&gt;


&lt;/head&gt;
&lt;body&gt;

    &lt;div id=""qunit""&gt;&lt;/div&gt;
    &lt;div id=""qunit-fixture""&gt;&lt;/div&gt;
    &lt;script src=""https://code.jquery.com/qunit/qunit-2.10.0.js"" integrity=""sha256-X1fQXHSYGxa4V2bqkEAQW0DQGSxJrKveasahr959o28="" crossorigin=""anonymous""&gt;&lt;/script&gt;

    &lt;script src=""script.js""&gt;&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>
",https://stackoverflow.com/questions/61682131/setting-up-qunit-tests-for-ajax-calls,"['ajax', 'testing', 'qunit']",34,False,1,0
How to Jest mock/spyOn a property of a class,"<p>I'm new to Jest so I apologise if my questioning doesn't read correctly, I'm unit testing a method on a vanilla JS class that has a reference to the class property 'this.original_params'. From reading the docs and many other Stackoverflow posts, I'm still confused as to what parts I have to mock and the syntax for doing so. I'm currently trying to test for the input value being empty and the destination value coming from this.original_params.</p>
<pre><code>// autocomplete.js
export default class Autocomplete {
constructor(site_config, page_name) {
    this.site_config = site_config;
    this.page_name = page_name;
    this.lat = null;
    this.lng = null;
    this.original_params = '';
}

init() {
    this.original_params = new URLSearchParams(document.querySelector('meta[name=&quot;originalParams&quot;]').content);
}

getDestination(inputSelector) {
    if (document.querySelector(inputSelector).getAttribute('value') !== '') {
        return document.querySelector(inputSelector).value;
    }
    console.log(this.original_params.has('destination'));
    if (this.original_params.has('destination')) {
        return this.original_params.get('destination');
    }
  }
}
</code></pre>
<p>I have tried multiple ways of writing the test but I fail to understand where to start. Here is the current iteration of the test:</p>
<pre><code>// autocomplete.test.js
it('Sets destination if it exists in Original Params', () =&gt; {
    document.body.innerHTML = `&lt;meta name=&quot;original_params&quot; content=&quot;siteid=62309&amp;amp;currency=USD&amp;amp;cid=ROCK&amp;amp;useMiles=&amp;amp;checkin=11/12/21&amp;amp;pageSize=15&amp;amp;mapSize=13&amp;amp;groupid=43285&amp;amp;radius=5&amp;amp;nights=3&amp;amp;latitude=26.10879170000000&amp;amp;map=&amp;amp;longitude=-80.10643370000000&amp;amp;destination=Austin, TX, USA&quot;&gt;&lt;input type=&quot;search&quot; id=&quot;address-input&quot; placeholder=&quot;Destination&quot; value=&quot;&quot; required=&quot;true&quot;&gt;`;

    const original_params = new URLSearchParams(
        '&lt;meta name=&quot;original_params&quot; content=&quot;siteid=62309&amp;amp;currency=USD&amp;amp;cid=ROCK&amp;amp;useMiles=&amp;amp;checkin=11/12/21&amp;amp;pageSize=15&amp;amp;mapSize=13&amp;amp;groupid=43285&amp;amp;radius=5&amp;amp;nights=3&amp;amp;latitude=26.10879170000000&amp;amp;map=&amp;amp;longitude=-80.10643370000000&amp;amp;destination=Austin, TX, USA&quot;&gt;&lt;/meta&gt;'
    );

    expect(autocomplete.getDestination('input#address-input')).toEqual('Austin, TX, USA');
});
</code></pre>
<p>The error I am getting:</p>
<pre><code>● getDestination › Sets destination if it exists in Original Params

TypeError: this.original_params.has is not a function

  80 |             return document.querySelector(inputSelector).value;
  81 |         }
&gt; 82 |         console.log(this.original_params.has('destination'));
     |                                          ^
  83 |         if (this.original_params.has('destination')) {
  84 |             return this.original_params.get('destination');
  85 |         }
</code></pre>
<p>Any help is very much appreciated.</p>
",https://stackoverflow.com/questions/65187169/how-to-jest-mock-spyon-a-property-of-a-class,"['javascript', 'jestjs', 'mocking', 'spyon']",1657,True,1,1
How to mock data for testing Firestore with emulator,"<p>I am testing my Firestore security rules and have the following setup:</p>
<pre><code>// firestore.spec.js
/**
 * Creates a new client FirebaseApp with authentication and returns the Firestore instance.
 * Also optionally seeds the project with mock data
 */
setupFirestoreDb = async (auth, data) =&gt; {
  // initialize test app
  const PROJECT_ID = &quot;my-test-project-xyz&quot;;
  const app = firebase.initializeTestApp({ projectId: PROJECT_ID, auth });
  const db = app.firestore();

  // Write mock documents
  if (data) {
    for (const key in data) {
      const ref = db.doc(key);
      ref.set(data[key]);
    }
  }

  return db;
};

beforeEach(async () =&gt; {
  // Clear the database between tests
  await firebase.clearFirestoreData({ projectId: PROJECT_ID });
});

before(async () =&gt; {
  // Load the rules file before the tests begin
  const rules = fs.readFileSync(&quot;firestore.rules&quot;, &quot;utf8&quot;);
  await firebase.loadFirestoreRules({ projectId: PROJECT_ID, rules });
});

after(async () =&gt; {
  // Delete all the FirebaseApp instances created during testing
  // Note: this does not affect or clear any data
  await Promise.all(firebase.apps().map((app) =&gt; app.delete()));
});

const mockData = {
  'users/alice': {
    foo: 'bar',
    nestedData: {
      baz: 'fae'
    }
  },
  'users/bob': {
    foo: 'bar',
    nestedData: {
      baz: 'fae'
    }
  },
  // ... more data
}

// run the test suite
describe(&quot;Test Security Rules&quot;, () =&gt; {

  it(&quot;should let any signed-in user to read any public profile&quot;, async () =&gt; {
    let db = await setupFirestoreDb({uid: &quot;bob&quot;}, mockData);
    aliceRef = db.collection(&quot;users&quot;).doc(&quot;alice&quot;);
    await firebase.assertSucceeds(aliceRef.get()); // fails
  });

    // more test cases
    ...

});
</code></pre>
<p>And my security rules file:</p>
<pre><code>// firestore.rules
rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    // define common functions used across collections/documents

    function userExists() {
      return exists(/databases/$(database)/documents/users/$(request.auth.uid));
    }

    // Fetch a user from Firestore by UID
    function getUserData(uid) {
      return get(/databases/$(database)/documents/users/$(uid)).data
    }

    function isValidUser() {
      let userData = request.resource.data;
      return userData.name != null &amp;&amp; userData.phoneNumber != null;
    }

    // ... more functions

    // lock the entire database by default
    match /{document=**} {
      allow read, write: if false;
    }

    // rules for users collection
    match /users/{userId} {
      allow read: if isSignedIn() &amp;&amp; getUserData(userId) != null; // &amp;&amp; userExists(userId); // make sure user being read exists
      allow write: if isSignedIn() &amp;&amp; isUser(userId) &amp;&amp; isValidUser(); // only an authenticated user can create own account

      // ... other rules for nested data (subcollections)
    }

    // ... more rules 
  }
}
</code></pre>
<h3>The test fails with:</h3>
<p><code>FirebaseError: false for 'get' @ L*, Null value error. for 'get' @ L*</code>, which occurs because I believe the function <code>getUserData()</code> returns null (same for <code>userExists()</code>).</p>
<h3>Instead, I expected <code>getUserData()</code> to return true because the document for user 'alice' is created based on the mock data.</h3>
<p>Is it a problem with the Firestore emulator or is there something wrong with how I set up my mock data &amp; test fixture? I used the Firebase simulator on the console to test the same rules against a real database and the rules work (<code>getUserData()</code> and <code>userExists()</code> work as expected)</p>
<p>The code is largely based on this <a href=""https://fireship.io/lessons/testing-firestore-security-rules-with-the-emulator/"" rel=""nofollow noreferrer"">fireship tutorial</a> and the official firebase <a href=""https://github.com/firebase/quickstart-testing/blob/master/unit-test-security-rules/README.md"" rel=""nofollow noreferrer"">unit testing tutorial</a></p>
",https://stackoverflow.com/questions/62953365/how-to-mock-data-for-testing-firestore-with-emulator,"['javascript', 'firebase', 'google-cloud-firestore', 'mocking', 'firebase-security']",1906,True,1,1
getting Error: Unexpected value &#39;undefined&#39; declared by the module &#39;DynamicTestModule&#39; using jest+spectator angular 9,"<p>I am using angular 9 and replaced the default unit testing of angular to spectator and jest after deep research, its fun and I have few tests that work fine, but suddenly I have this issue when trying to test some parent component, resulting ugly error (see question title) which I can't figure out how to resolve, will be glad for some help, the code is below</p>

<p>other similar tests are working but this one gets the unfriendly msg on the title even when I remove all markup of the template and write just stupid div, and cancel the mocking on the test I still get this bummer... tried restarting servers with no help.</p>

<p>spec.ts</p>

<pre><code>
    import { Spectator, createComponentFactory } from '@ngneat/spectator/jest';
    import { PlannerScreenComponent } from './planner-screen.component';
    import { SlotsListComponent } from '../planner/components/slots-list/slots-list.component';
    import { MockComponent } from 'ng-mocks';

    describe('PlannerScreenComponent suit', () =&gt; {
      let spectator: Spectator&lt;PlannerScreenComponent&gt;;
      const createComponent: () =&gt; Spectator&lt;PlannerScreenComponent&gt; = createComponentFactory({
        component: PlannerScreenComponent,
        declarations: [MockComponent(SlotsListComponent)]
      });

      beforeEach(() =&gt; (spectator = createComponent()));

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

</code></pre>

<p>component.ts</p>

<pre><code>
    import { Component, OnInit, Input } from '@angular/core';

    @Component({
      selector: 'planner-screen',
      templateUrl: './planner-screen.component.html',
      styleUrls: ['./planner-screen.component.scss']
    })
    export class PlannerScreenComponent implements OnInit {
      @Input() isSplittedScreen = false;
      constructor() {}

      ngOnInit() {}
    }

</code></pre>

<p>component.html</p>

<pre><code>    section [class.splitted-screen]=""isSplittedScreen"" class=""planner-screen-wrapper""&gt;
          &lt;aside class=""left-ruller-container""&gt;&lt;/aside&gt;
          &lt;div class=""top-middle-title""&gt;
            &lt;div&gt;title&lt;/div&gt;
          &lt;/div&gt;
          &lt;div class=""main-panel-container""&gt;
            &lt;slots-list&gt;&lt;/slots-list&gt;
          &lt;/div&gt;
          &lt;aside class=""right-ruller-container""&gt;&lt;/aside&gt;
        &lt;/section&gt;
</code></pre>
",https://stackoverflow.com/questions/60271894/getting-error-unexpected-value-undefined-declared-by-the-module-dynamictestm,"['angular', 'jestjs', 'angular9', 'angular-unit-test', 'angular-spectator']",1378,False,1,1
Mockable spring dependency injection into mapper definition,"<p>I need to access a Spring bean from a custom mapping method. But I also need to be able to inject a mock of that Spring bean when unit-testing that mapping method.</p>
<p>Here is a minimal example of my mapper class:</p>
<pre class=""lang-java prettyprint-override""><code>@Mapper(componentModel = &quot;spring&quot;)
public abstract class MyMapper {
    private final MyBean myBean;
    
    public MyMapper(MyBean myBean) {
        this.myBean = myBean;
    }

    @BeforeMapping
    protected MyElement initElement(MyElementDto dto) {
        // custom logic using the injected MyBean to initialize MyElement
    }
    
    public abstract MyElement map(MyElementDto dto);
}

</code></pre>
<p>I would expect MapStruct to generate an implementation where it uses <code>MyMapper</code>'s parameterized constructor like so:</p>
<pre class=""lang-java prettyprint-override""><code>@Component
public class MyMapperImpl extends MyMapper {
    @Autowired
    public MyMapperImpl(MyBean myBean) {
        super(myBean);
    }

    // ... mapping function implementation ...
}
</code></pre>
<p>However, MapStruct seems to ignore parameterized constructors and only support default parameter-less constructors.</p>
<p>So the question is: <strong>How can I implement this type of logic in the cleanest way so that the generated mapper implementation is unit-testable and it is possible to mock the <code>MyBean</code> dependency properly?</strong></p>
<p>Using MapStruct 1.3.0.Final, Spring 4.3.25.Release, Mockito 1.9.5 and Junit 4.12.</p>
",https://stackoverflow.com/questions/63187829/mockable-spring-dependency-injection-into-mapper-definition,"['spring', 'dependency-injection', 'mocking', 'mapstruct']",367,True,1,1
"Writing Unit test for project in Nuxt, Vue, jest &amp; Vuetify","<p><strong>TL;DR</strong></p>

<p>Unit Test for component copied from <code>Vuetify</code> <a href=""https://vuetifyjs.com/en/getting-started/unit-testing/"" rel=""nofollow noreferrer"">link</a> are passing but my actual unit test for my component written in <code>pug</code> is not passing.</p>

<p><strong>Details:</strong></p>

<p>I am working on a project which is built using <code>Vue</code>, <code>NUXT</code>, <code>Vuetify</code> and <code>pug</code> as template language. I am configuring the project to write test cases with <code>JEST</code> test runner. The unit test is currently failing and I would need some steps to identify the problem.</p>

<p>I have read through following:</p>

<ul>
<li><a href=""https://vue-test-utils.vuejs.org/guides/#getting-started"" rel=""nofollow noreferrer"">https://vue-test-utils.vuejs.org/guides/#getting-started</a></li>
<li><a href=""https://vuetifyjs.com/en/getting-started/unit-testing/"" rel=""nofollow noreferrer"">https://vuetifyjs.com/en/getting-started/unit-testing/</a></li>
</ul>

<p>Following versions are in use:</p>

<ul>
<li><code>nuxt: ^2.0.0</code></li>
<li><code>nuxtjs/vuetify: ^1.10.2</code></li>
<li><code>pug: ^2.0.4</code></li>
<li><code>pug-plain-loader: ^1.0.0</code></li>
<li><code>jest: ^24.1.0</code></li>
<li><code>vue-jest: ^4.0.0-0</code></li>
</ul>

<p>Following is the relevant folder structure</p>

<ul>
<li><code>&lt;project root&gt;/jest.config.js</code></li>
<li><code>&lt;project root&gt;/components/common/CustomCard.vue</code> </li>
<li><code>&lt;project root&gt;/components/common/MessageDialog.vue</code></li>
<li><code>&lt;project root&gt;/tests/unit/components/common/TestMessageDialog.spec.js</code></li>
<li><code>&lt;project root&gt;/tests/unit/components/common/TestCustomCard.spec.js</code></li>
</ul>

<p>Following is are seemingly relevant parts of the configurations:</p>

<p><strong>jest.config.js</strong></p>

<pre><code>module.exports = {
  verbose: true,
  moduleNameMapper: {
    '^@/(.*)$': '&lt;rootDir&gt;/$1',
    '^~/(.*)$': '&lt;rootDir&gt;/$1',
    '^vue$': 'vue/dist/vue.common.js'
  },
  moduleFileExtensions: ['js', 'vue', 'json'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  'collectCoverage': false,
  'collectCoverageFrom': [
    '&lt;rootDir&gt;/components/**/*.vue',
    '&lt;rootDir&gt;/pages/**/*.vue'
  ],
  globals: {
    'vue-jest': {
      pug: {
        doctype: 'html'
      }
    }
  },
  preset: '@vue/cli-plugin-unit-jest/presets/no-babel'
}
</code></pre>

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

<pre><code>import {
  mount,
  createLocalVue
} from '@vue/test-utils'
import Vuetify from 'vuetify'
import MessageDialog from '@/components/common/MessageDialog.vue'

describe('MessageDialog.vue', () =&gt; {
  const sampleData = {
    titleText: 'title text with unique id : 2020.03.12.00'
  }

  let wrappedMessageDialog

  beforeEach(() =&gt; {
    const vuetify = new Vuetify()
    const localVue = createLocalVue()

    wrappedMessageDialog = mount(
      MessageDialog,
      {
        localVue,
        vuetify,
        propsData: sampleData
      }
    )
  })

  it('renders correctly when passed props', () =&gt; {
    expect(
      wrappedMessageDialog
        .find({ name: 'v-card-title' })
        .text()
    ).toMatch(sampleData.titleText)
  })
})
</code></pre>

<p><strong>MessageDialog.vue</strong></p>

<pre><code>&lt;template lang=""pug""&gt;
v-dialog(v-model=""isVisible"" width=""600"")
  v-card
    v-card-title {{ titleText }}
&lt;/template&gt;


&lt;script&gt;

export default {
  props: {
    titleText: {
      default: '',
      type: String
    }
  }
}
&lt;/script&gt;
</code></pre>

<p>I am getting following error</p>

<pre><code>FAIL tests/unit/components/common/TestMessageDialog.spec.js
[vue-test-utils]: find did not return Component, cannot call text() on empty Wrapper

      31 |       wrappedMessageDialog
      32 |         .find({ name: 'v-card-title' })
    &gt; 33 |         .text()
         |          ^
      34 |     ).toMatch(sampleData.titleText)
      35 |   })
      36 | })

      at throwError (node_modules/@vue/test-utils/dist/vue-test-utils.js:1709:9)
      at ErrorWrapper.text (node_modules/@vue/test-utils/dist/vue-test-utils.js:8767:3)
      at Object.it (tests/unit/components/common/TestMessageDialog.spec.js:33:10)

  console.error node_modules/vue/dist/vue.common.dev.js:630
    [Vue warn]: Unknown custom element: &lt;v-dialog&gt; - did you register the component correctly? For recursive components, make sure to provide the ""name"" option.

    found in

    ---&gt; &lt;Anonymous&gt;
           &lt;Root&gt;
</code></pre>

<p>Similar warnings for <code>&lt;v-dialog&gt;</code>, <code>&lt;v-card&gt;</code> &amp; <code>&lt;v-card-title&gt;</code></p>
",https://stackoverflow.com/questions/60671629/writing-unit-test-for-project-in-nuxt-vue-jest-vuetify,"['vue.js', 'jestjs', 'vuetify.js', 'nuxt.js']",2851,True,1,1
Passing Firebase Admin App in to Data Access Objects,"<p>I'm trying to create data access objects that can be unit tested using the local Firebase emulator. The objects will be used from Firebase functions and use the Admin SDK.</p>
<p>To do this I need to pass in the Firebase app object but the type for this is different between firebase-admin and rules-unit-testing packages.</p>
<p>DAO Object</p>
<pre><code>import * as admin from 'firebase-admin';

class MyDaoRepo implements IDaoRepo {
    readonly app : firebase.app.App;
    readonly store : firebase.firestore.Firestore;

    constructor(app : firebase.app.App) {
        this.app = app;
        this.store = this.app.firestore();
    }

    async getAll(ids : string[]) :Promise&lt;DocumentSnapshot&gt; {
        const refs = ids.map((id)=&gt;{
            return this.store.doc(COURSE_COLLECTION+'/'+id);
        });

        retrun this.store.getall(...refs);
    }
}
</code></pre>
<p>Unit Test</p>
<pre><code>import * as test from '@firebase/rules-unit-testing';
import { MyDaoRepo} from &quot;../../dal/my-dao-repo&quot;;

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

  it('get data from ids', 
    async () =&gt; { 

        const app = test.initializeAdminApp({projectId: 'my-test'});

        const dut = new MyDaoRepo(app);

        ...
    });
    
});
</code></pre>
<p>In Function Use</p>
<pre><code>    ...

    const app = admin.initializeApp();

    const myDao = new MyDaoRepo(app);  &lt;&lt;=== This fails saying it is not the same type and is missing properties

    ...

</code></pre>
<p>How do I get a type for App that can take both the test app and the production app types?</p>
<p>I'm new to Firebase and Typescript so guess that I'm missing a import but can't find any examples doing the same.</p>
<p>The actual error produced when assigning the test 'App' to production 'App' type is</p>
<p><code>Type 'App' is missing the following properties from type 'App': instanceId, machineLearning, projectManagement, securityRules ts(2739)</code></p>
",https://stackoverflow.com/questions/64310201/passing-firebase-admin-app-in-to-data-access-objects,"['typescript', 'firebase', 'google-cloud-firestore', 'jestjs']",113,False,1,0
Patch a dataclass attribute which is dynamically generated in its dependency in unit testing,"<p>I am new to Unit testing. I have used mocking, patching in the past but the case I have is a little bit complicated for me to create unit tests.</p>
<p>So I have a file: <code>parent.py</code> with the following data class</p>
<pre><code>import multiprocessing
from dataclasses import dataclass

@dataclass
class ParentClass:
    cpu_count: int = multiprocessing.cpu_count() 
</code></pre>
<p>I have another module <code>child.py</code> with the following data class</p>
<pre><code>from stackoverflow.parent import ParentClass
from dataclasses import dataclass

@dataclass
class ChildClass(ParentClass):
      some_attribute_1: int = 1
      some_attribute_2: int = 2
      ....
</code></pre>
<p>Finally, I have a third module <code>actual_function.py</code> that uses these data classes.</p>
<pre><code>from stack_overflow.child import ChildClass


def get_cpu_count_and_attributes(cc: ChildClass):
    return cc.cpu_count, cc.some_attribute_1 
</code></pre>
<p>Here, I want to unit test <code>print_cpu_count_and_attributes</code> function. How does patching work here? I created the following test case and it fails. The cpu_count in my system is 16 but I want to mock it with return value 8 so that it works on other machines with different number of cores</p>
<pre><code>from unittest import mock
from stack_overflow.actual_function import *
from stack_overflow.child import ChildClass


@mock.patch('stack_overflow.parent.multiprocessing.cpu_count', return_value=8)
def test_print_cpu_count_and_attributes():
    cc = ChildClass()
    assert get_cpu_count_and_attributes(cc) == (8, 1)
</code></pre>
<p>Here is the folder structure.</p>
<pre><code>stackoverflow
├── __init__.py
  ├── actual_function.py
  ├── child.py
  ├── parent.py
  └── test_function.py
</code></pre>
",https://stackoverflow.com/questions/64049192/patch-a-dataclass-attribute-which-is-dynamically-generated-in-its-dependency-in,"['python', 'unit-testing', 'testing', 'inheritance', 'python-dataclasses']",1852,True,1,1
Usage of akka ActorContext in integration tests,"<p>We're migrating our project to typed akka Actors. We have services that can create actors at will, something like:</p>
<pre><code>class Service(ac: ActorContext[_])
   def action() = { 
     ac.spawn(MyBehavior().receive)
  }
}
</code></pre>
<p>The problem arises when we're trying to test this service. It seems that we should only use <code>testKit.spawn</code> or <code>testKit.createTestProbe</code> methods. It works fine for unit-testing our classes.</p>
<p>But there is no way to get <code>ActorContext[_]</code> to pass it to services that are being tested.</p>
<p>So, it seems that that we are misusing the ActorContext in our service. But how a service can create a new actor?</p>
<p>I have an idea of passing a special <code>ActorRef[CreateActor]</code> that can create those actor. This way we can remove the dependency on <code>ActorContext[_]</code> in the <code>Service</code>, but I wanted to see if there is a better option.</p>
",https://stackoverflow.com/questions/63727897/usage-of-akka-actorcontext-in-integration-tests,"['scala', 'integration-testing', 'akka-typed']",343,True,1,1
How to make stubs and spies on methods which import from a package?,"<p>I am a JavaScript and Python developer. Here is a unit testing code snippet using <a href=""https://jestjs.io/"" rel=""nofollow noreferrer"">jestjs</a> testing framework:</p>

<p><code>index.ts</code>:</p>

<pre class=""lang-js prettyprint-override""><code>import dotenv from 'dotenv';

export class OsEnvFetcher {
  constructor() {
    const output = dotenv.config();
    if (output.error) {
      console.log('Error loading .env file');
      process.exit(1);
    }
  }
}
</code></pre>

<p><code>index.test.ts</code>:</p>

<pre class=""lang-js prettyprint-override""><code>import { OsEnvFetcher } from './';
import dotenv from 'dotenv';

describe('OsEnvFetcher', () =&gt; {
  afterEach(() =&gt; {
    jest.restoreAllMocks();
  });
  it('should pass', () =&gt; {
    const mOutput = { error: new Error('parsed failure') };
    jest.spyOn(dotenv, 'config').mockReturnValueOnce(mOutput);
    const errorLogSpy = jest.spyOn(console, 'log');
    const exitStub = jest.spyOn(process, 'exit').mockImplementation();
    new OsEnvFetcher();
    expect(dotenv.config).toBeCalledTimes(1);
    expect(errorLogSpy).toBeCalledWith('Error loading .env file');
    expect(exitStub).toBeCalledWith(1);
  });
});
</code></pre>

<p>The outcome for the unit testing:</p>

<pre><code> PASS  stackoverflow/todo/index.test.ts (11.08s)
  OsEnvFetcher
    ✓ should pass (32ms)

  console.log
    Error loading .env file

      at CustomConsole.&lt;anonymous&gt; (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |       50 |     100 |     100 |                   
 index.ts |     100 |       50 |     100 |     100 | 6                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.467s
</code></pre>

<p>The test method in the example is very common in a js project using <a href=""https://github.com/testdouble/contributing-tests/wiki/Arrange-Act-Assert"" rel=""nofollow noreferrer"">Arrange, Act, Assert</a> pattern. Due to the <code>dotenv.config()</code> method will do some file system I/O operations, it has a side-effect. So we will make a stub or mock for it. In this way, our unit tests have no side effects and are tested in an isolated environment.</p>

<p>The same applies to python. We can use <a href=""https://docs.python.org/3/library/unittest.mock.html"" rel=""nofollow noreferrer"">unittest.mock</a> mock object library to do the same thing. I'm very comfortable with these unit testing approaches.</p>

<p>Now, I switch to go, try to do the same thing. Code here:</p>

<p><code>osEnvFetcher.go</code></p>

<pre class=""lang-golang prettyprint-override""><code>package util

import (
    ""log""
    ""os""
    ""github.com/joho/godotenv""
)

var godotenvLoad = godotenv.Load

type EnvFetcher interface {
    Getenv(key string) string
}

type osEnvFetcher struct {}

func NewOsEnvFetcher() *osEnvFetcher {
    err := godotenvLoad()
    if err != nil {
        log.Fatal(""Error loading .env file"")
    }
    return &amp;osEnvFetcher{}
}

func (f *osEnvFetcher) Getenv(key string) string {
    return os.Getenv(key)
}
</code></pre>

<p><code>osEnvFetcher_test.go</code>:</p>

<pre class=""lang-golang prettyprint-override""><code>package util

import (
    ""testing""
    ""fmt""
)

func TestOsEnvFetcher(t *testing.T) {
    old := godotenvLoad
    defer func() { godotenvLoad = old }()
    godotenvLoad = func() error {
        return 
    }
    osEnvFetcher := NewOsEnvFetcher()
    port := osEnvFetcher.Getenv(""PORT"")
    fmt.Println(port)
}
</code></pre>

<p>The test case is not finished. I'm not sure how should I mock, stub, or spy <code>godotenv.Load</code> method(Equivalent to <code>dotenv.config()</code>) and <code>log.Fatal</code> method? I found this mock package - <a href=""https://github.com/golang/mock"" rel=""nofollow noreferrer"">mock</a>. But <a href=""https://github.com/joho/godotenv"" rel=""nofollow noreferrer"">godotenv</a> package has no interface, it's composed by functions. </p>

<p>I'm looking for some ways like <a href=""https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options"" rel=""nofollow noreferrer"">jest.mock(moduleName, factory, options)</a> and <a href=""https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname"" rel=""nofollow noreferrer"">jest.spyOn(object, methodName)</a>.Or, like <a href=""https://sinonjs.org/releases/latest/stubs/"" rel=""nofollow noreferrer"">stubs</a> and <a href=""https://sinonjs.org/releases/v9.0.2/spies/"" rel=""nofollow noreferrer"">spies</a> of <a href=""https://sinonjs.org/"" rel=""nofollow noreferrer"">sinonjs</a>. Or, like <a href=""https://jasmine.github.io/api/edge/global.html#spyOn"" rel=""nofollow noreferrer"">spyOn</a> of <a href=""https://jasmine.github.io/index.html"" rel=""nofollow noreferrer"">jasmine</a>. These methods can cover almost any test scenario.  No matter use DI or import modules directly.</p>

<p>I saw some ways, but they all have their own problems.</p>

<p>E.g. <a href=""https://stackoverflow.com/a/41661462/6463558"">https://stackoverflow.com/a/41661462/6463558</a>.</p>

<p>What about I need to stub ten methods which have side-effect? I need to assign these methods of a package ​​to 10 variables and replace them with the mocked version in test cases ten times before running the test. It's non-scalable. Maybe I can create a <code>__mocks__</code> directory and put all the mocked version object in it. So that I can use them in all test files. </p>

<p>Use Dependency Injection is better. In this way we can pass the mocked objects to the function/method. But some scenarios are directly importing the packages and use the methods of packages(3rd or built-in standard library). This is also the scenario in my question. I think this scenario is inevitable and will definitely appear on a certain layer of the code.</p>

<p>I can handle this scenario easily using <code>jestjs</code>, E.g.</p>

<p><code>util.js</code>, </p>

<pre><code>exports.resolveAddress = function(addr) {
  // ...
  const data = exports.parseJSON(json);
  return data;
}
exports.parseJSON = function(json) {}
</code></pre>

<p><code>main.js</code>:</p>

<pre class=""lang-js prettyprint-override""><code>// import util module directly rather than using Dependency Injection
import util from './util';
function main() {
  return util.resolveAddress();
}
</code></pre>

<p><code>main.test.js</code>:</p>

<pre class=""lang-js prettyprint-override""><code>import util from './util';
const mJson = 'mocked json data';
jest.spyOn(util, 'parseJSON').mockReturnValueOnce(mJson)
const actual = main()
expect(actual).toBe('mocked json data');
</code></pre>

<p>I directly imports <code>util</code> module and mock <code>util.parseJSON</code> method and its returned value. I am not sure if Go's package can do this. For now, these issues are <strong>Arrange</strong> issues.</p>

<p>Besides, I also need to check the methods are indeed called to make sure the code logics and branches are correct. (E.g. the <code>.toBeCalledWith()</code> method using <code>jestjs</code>). This is <strong>Assert</strong> issue.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/61952251/how-to-make-stubs-and-spies-on-methods-which-import-from-a-package,"['unit-testing', 'go', 'mocking', 'jestjs', 'stub']",348,True,-3,1
How to create fake object from a data type in Typescript for testing,"<p>I'm looking for a way to simplify making fake data for unit testing in Angular solution.
I am using interfaces like:</p>
<pre><code>export interface ReferenceDataItemCommon {
  codeDescription?: string;
  code: string;
  deleted?: boolean;
}
</code></pre>
<p>As data types in application. Currently using Factory.ts + Faker to create fake objects for purpose of tests:</p>
<pre><code>  export const fakeReferenceDataItemCommon = Factory.Sync.makeFactory&lt;ReferenceDataItemCommon&gt;({
    code: Factory.each(() =&gt; Faker.lorem.word()),
    codeDescription: Factory.each(() =&gt; Faker.lorem.sentence(4)),
  });
</code></pre>
<p>But I'm curious if there is a way to simplify it even more for when you just want a object for your test and speed up creating it even more.
Is it possible in Typescript to have a generic method that would return a object of that datatype?</p>
<pre><code>  const fake = createFake&lt;ReferenceDataItemCommon&gt;();
</code></pre>
<p>What my initial idea was is to do something like:</p>
<pre><code>Object.keys(object).forEach(key =&gt; {
  switch(typeof object[key]) {
    case 'string':
       object[key] = Faker.lorem.word();
       break;
  }
}
return object;
</code></pre>
<p>And for complex object call this method recursively. Is that possible, and if what would be a better approach to do this as I feel a bit out of my depth?</p>
",https://stackoverflow.com/questions/63425868/how-to-create-fake-object-from-a-data-type-in-typescript-for-testing,"['angular', 'typescript', 'unit-testing', 'jasmine']",6083,True,5,2
Getting &quot;Process finished with exit code 1 Class not found&quot; Error while running Robolectric unit test,"<p>I am trying to implement Robolectric framework in my Android app for Unit Testing purpose. I am first time working on the Robolectric, I followed below post and tutorial to understand the concept and implementation steps--</p>

<p>1] <a href=""http://robolectric.org/getting-started/"" rel=""nofollow noreferrer"">http://robolectric.org/getting-started/</a></p>

<p>2] <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>But when I am trying to run the first unit test, I am getting below error--</p>

<pre><code>Process finished with exit code 1
Class not found: ""com.xyz.my_package.activity.WelcomeActivityTest""
</code></pre>

<p>Below is my module level build.gradle file--</p>

<pre><code>  apply plugin: 'com.android.application'

    android {
        compileSdkVersion 29
        buildToolsVersion '29.0.2'
        defaultConfig {
            applicationId ""com.xyz.my_package""
            minSdkVersion 19
            targetSdkVersion 29
            versionCode 86
            versionName ""86.0""
            multiDexEnabled true
            testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
        }

        dexOptions {
            preDexLibraries = false
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }

        lintOptions {
            disable 'MissingTranslation'
        }

        sourceSets {
            main {
                assets.srcDirs = ['src/main/assets', 'src/main/assets/']
                res.srcDirs = ['src/main/res', 'src/main/res/drawable']
            }
        }


        testOptions {
            unitTests {
                includeAndroidResources = true
            }
        }
    }

    dependencies {

        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        implementation 'com.google.android.gms:play-services-maps:11.0.2'

        implementation 'com.google.android.gms:play-services-analytics:17.0.0'
        implementation 'com.google.android.gms:play-services-wallet:18.0.0'

        implementation 'com.facebook.fresco:fresco:1.9.0'

        testImplementation('androidx.test.espresso:espresso-core:3.1.0', {
            exclude group: 'com.android.support', module: 'support-annotations'
            exclude module: 'support-v4' exclude module: 'support-v13' exclude module: 'recyclerview-v7'
        })
        implementation 'androidx.appcompat:appcompat:1.0.0'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.0'
        testImplementation 'org.robolectric:robolectric:4.3'
        testImplementation 'androidx.test:core:1.0.0'

        implementation 'com.amplitude:android-sdk:2.16.0'
        implementation 'com.google.zxing:core:3.2.1'
        implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
        implementation 'com.google.android.material:material:1.0.0'
        implementation project("":liblknscratcherview"")
        implementation 'org.springframework.android:spring-android-core:1.0.1.RELEASE'
        implementation 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
        implementation 'commons-io:commons-io:2.4'
        implementation 'com.google.code.gson:gson:+'
        implementation 'org.apache.httpcomponents:httpcore:4.4.6'
        implementation 'com.google.android.gms:play-services-location:17.0.0'
        implementation 'com.squareup.picasso:picasso:2.5.2'
        implementation 'com.squareup.retrofit:retrofit:1.9.0'
        implementation 'com.daimajia.swipelayout:library:1.2.0@aar'
        implementation 'com.kontaktio:sdk:3.3.3'
        implementation 'io.gresse.hugo.vumeterlibrary:vumeterlibrary:1.0.15'
        implementation 'androidx.recyclerview:recyclerview:1.0.0'
        implementation 'com.mindorks:placeholderview:0.2.7'
        implementation 'androidx.cardview:cardview:1.0.0'
        implementation 'com.facebook.shimmer:shimmer:0.1.0@aar'
        implementation 'com.sothree.slidinguppanel:library:3.3.1'

        implementation 'androidx.multidex:multidex:2.0.0'
        implementation 'com.facebook.android:facebook-login:[4,5)'
        implementation 'com.facebook.android:facebook-share:[4,5)'

        implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
        implementation 'bz.tsung.android:objectify:2.0'
        implementation 'com.xiaofeng.android:flowlayoutmanager:1.2.3.2'
        implementation 'de.hdodenhof:circleimageview:3.0.0'

        implementation(name: 'core-sdk_4_4_1', ext: 'aar')
        implementation(name: 'audio-sdk_4_4_1', ext: 'aar')
        implementation(name: 'beacon-sdk_4_4_1', ext: 'aar')
        implementation(name: 'geofence-sdk_4_4_1', ext: 'aar')

        implementation project("":library"")
    }
</code></pre>

<p>Below is my Unit Test class ""WelcomeActivityTest.java"" for which I am getting above exception--</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
public class WelcomeActivityTest
{
    private Activity activity;

    @Before
    public void setup()
    {
        activity = Robolectric.buildActivity(WelcomeActivity.class).create().get();
    }

    @Test
    public void emailSignUpBtnClick()
    {
        Button signUpEmail = (Button) activity.findViewById(R.id.signUpEmail);

        signUpEmail.performClick();
        ShadowActivity shadowActivity = shadowOf(activity);
        Intent startedIntent = shadowActivity.getNextStartedActivity();
        ShadowIntent shadowIntent = shadowOf(startedIntent);
        assertThat(shadowIntent.getIntentClass().getName(), 
        equalTo(SignUpEmailActivity.class.getName()));
    }
}
</code></pre>

<p>-- I am correctly writing unit test classes in ""app/src/test/"" directory.</p>

<p>-- I am correctly maintaining same package hierarchy for my actual classes and test classes e.g.</p>

<pre><code>""com.xyz.my_package.activity.WelcomeActivity"" is my actual class written in ""app/src/main/java/"" directory

And 

""com.xyz.my_package.activity.WelcomeActivityTest"" is my test class written in ""app/src/test/java/"" directory
</code></pre>

<p>Below is the ""Rub/Debug Confuguration"" screen-shot--</p>

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

<p><strong>Below is what I tried so-far--</strong></p>

<p>1] Created separate demo app and tried running the same test case there and the strange thing is, it is working fine in Demo app but getting ""Class not found"" exception for the Test class in my actual app.</p>

<p>2] Compared the gradle dependencies and ""Rub/Debug Confuguration"" setting with the Demo app's gradle and ""Rub/Debug Confuguration"" setting and they are same.</p>

<p>3] Tries all the solution available on the <a href=""https://stackoverflow.com/questions/38056901/class-not-found-empty-test-suite-when-running-unit-tests-in-android-studio/41474392"">this post</a> but unfortunately none of them worked for me.</p>

<p><strong>Noticeable things:</strong> </p>

<p>1] My project is created 2 years back in Android Studio 3.0.0 version and currently I am using 3.6.3 version.</p>

<p>2] My Demo app which is working fine is created in Android Studio 3.6.3 version.</p>

<p>I hope given details are enough to trace the problem, still if you want some more details, please let me know. Thank you!</p>
",https://stackoverflow.com/questions/61750168/getting-process-finished-with-exit-code-1-class-not-found-error-while-running,"['android', 'unit-testing', 'robolectric']",772,False,1,0
bad request returned using postman but not in unit testing spring boot,"<p>I have a category entity with a unique field &quot;name&quot;.</p>
<p>I'm using a custom unique annotation to validate the data and it works perfectly.</p>
<p>I'm trying to test my controller on my spring boot application and i want to check if the the request returns a 400 status if the data is duplicated ( unique name ).</p>
<p>in postman it works as expected and returns the 400 status with the errors list.</p>
<p>with unit testing, it returns a 201 status with an empty body ( but in reality, returning a 201 means that the body contains the new created entity! )</p>
<p>this is my test:</p>
<pre class=""lang-java prettyprint-override""><code>    @Test
    public void testIfAdminCanCreateCategory_expect400BecauseCategoryAlreadyExist() throws Exception {
        // json
        String data = &quot;{\&quot;name\&quot; : \&quot;CATEGORY\&quot;}&quot;;
        mockMvc().with(keycloakAuthenticationToken().authorities(&quot;ROLE_admin&quot;)).perform(post(&quot;/categories&quot;).content(data).contentType(&quot;application/json&quot;))
                .andDo(print())
                .andDo(r -&gt; mockMvc().with(keycloakAuthenticationToken().authorities(&quot;ROLE_admin&quot;))
                        .perform(post(&quot;/categories&quot;).content(data).contentType(&quot;application/json&quot;))
                        .andExpect(status().isBadRequest()));
    }
</code></pre>
<p>my controller:</p>
<pre class=""lang-java prettyprint-override""><code>    @PostMapping
    @PreAuthorize(&quot;hasRole('ROLE_admin')&quot;)
    public HttpEntity&lt;MainCategory&gt; create(@Valid @RequestBody CreateMainCategory createMainCategory)
    {
        return ResponseEntity.status(HttpStatus.CREATED).body(mainCategoryService.create(createMainCategory));
    }
</code></pre>
<p>my service:</p>
<pre class=""lang-java prettyprint-override""><code>    @Override
    public MainCategory create(CreateMainCategory createMainCategory) {
        MainCategory mainCategory = new MainCategory();
        mainCategory.setName(createMainCategory.getName().toUpperCase());
        return mainCategoryRepository.save(mainCategory);
    }
</code></pre>
<p>my entity:</p>
<pre class=""lang-java prettyprint-override""><code>@Entity
@EntityListeners( AuditingEntityListener.class  )
@Data
public class MainCategory {

    @Id @GeneratedValue private Long id;

    private String name;

    @CreatedBy
    private String createdBy;

    @OneToMany(cascade = CascadeType.REMOVE, mappedBy = &quot;mainCategory&quot;)
    List&lt;Category&gt; categories;
}
</code></pre>
<p>the request from logs:</p>
<pre class=""lang-java prettyprint-override""><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /categories
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Content-Length:&quot;21&quot;]
             Body = {&quot;name&quot; : &quot;CATEGORY&quot;}
    Session Attrs = {SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@6989924: Authentication: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@6989924: Principal: user; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@40fd518f; Granted Authorities: ROLE_admin}
</code></pre>
<p>the response from logs:</p>
<pre class=""lang-java prettyprint-override""><code>MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = [Vary:&quot;Origin&quot;, &quot;Access-Control-Request-Method&quot;, &quot;Access-Control-Request-Headers&quot;, X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :400
Actual   :201
</code></pre>
",https://stackoverflow.com/questions/63428216/bad-request-returned-using-postman-but-not-in-unit-testing-spring-boot,"['spring-boot', 'unit-testing', 'spring-security', 'keycloak', 'spring-test']",654,True,-1,2
Azure.Core.ResponseHeaders in unit testing,"<p>I'm trying to implement the new Azure.Storage v12 SDK and running into an issue with unit testing. Methods that call the Azure REST API return a <code>Azure.Response&lt;T&gt;</code> which contains the method <code>GetRawResponse()</code> to return an <code>Azure.Response</code>.</p>
<p>The implementation relies on using the headers found in <code>Azure.Response.Headers</code>, which is a struct of the type <a href=""https://learn.microsoft.com/en-us/dotnet/api/azure.core.responseheaders?view=azure-dotnet"" rel=""nofollow noreferrer"">Azure.Core.ResponseHeaders</a>. I can create an instance of it, but when iterating over it it throws a null reference exception.</p>
<pre class=""lang-cs prettyprint-override""><code>using Azure.Core;

var headers = new ResponseHeaders();
var headers.GetEnumerator(); //throws null reference error
</code></pre>
<p>As far as I can tell the object has no other constructors and when obtaining its members with reflection I also see no properties or fields it could iterate over.</p>
<p>Is it possible to create an instance that's capable iterating over or mocking it using Moq?</p>
",https://stackoverflow.com/questions/63017179/azure-core-responseheaders-in-unit-testing,"['c#', 'azure', 'azure-storage', 'moq']",308,True,0,1
Interfaces - method returning object of type of the concrete class implementing it,"<p>Consider a class:</p>

<pre><code>// partial code for this class
abstract class DataNode : System.IComparable&lt;DataNode&gt;, System.IEquatable&lt;DataNode&gt;, System.Collections.IEnumerable, IDataNode
{
    protected DataNode parent;
    protected int order = System.Int32.MaxValue;

    // ctor
    protected DataNode(DataNode parent, string name)
    {
       modified = new System.Collections.Generic.Dictionary&lt;string, string&gt;();
       original = new System.Collections.Generic.Dictionary&lt;string, string&gt;();
       _parent = parent;
       if (name == null)
       {
           throw new System.ArgumentNullException(""name"");
       }
       original.Add(""name"", name);
       _status = Modification_Status.ADDED;
    }

    // methods returning objects of the same type as the class, need to be defined in interface
    public DataNode getParent()
    {
        // return the parent
    }

    public abstract DataNode deepCopy(DataNode parent);
}
</code></pre>

<p>A problem arises when dealing with methods in the class implementing this interface that return objects of the same type as the class, as in the two examples above.</p>

<p>The code is in the process of being refactored for unit testing purposes. Part of this is to create interfaces for base classes, such as this one. An interface is being created as follows:</p>

<pre><code>// partial interface code
public interface IDataNode
{
    // all public methods

    IData_Node deepCopy(IDataNode parent);
    IData_Node getParent();
}
</code></pre>

<p>The methods cannot be declared with <code>DataNode</code> in the interface, as the return type is less accessible. How to deal with this problem?</p>

<p>Edit: Actually, declaring the <code>deep_copy</code> method with return type and parameter both <code>IDataNode</code> instead of <code>DataNode</code> works, but it seems all references to this in the code need to be changed. </p>
",https://stackoverflow.com/questions/60406112/interfaces-method-returning-object-of-type-of-the-concrete-class-implementing,"['c#', '.net', 'oop', 'interface']",175,True,0,1
How to implement a custom matcher to check for object equality in Catch2,"<p>I'm new to unit testing in C++ with <a href=""https://github.com/catchorg/Catch2"" rel=""nofollow noreferrer"">Catch2</a>. Lastly, I was trying to implement a <a href=""https://github.com/catchorg/Catch2/blob/master/docs/matchers.md#custom-matchers"" rel=""nofollow noreferrer"">custom Matcher</a> to test if the fields of a given object match the ones I provide. The object in question good be like:</p>

<pre><code>class Book {
private:
    int chapters;
    int pages;

public:
    int GetChapters();
    int GetPages();
};
</code></pre>

<p>My matcher would be used like this in a test case:</p>

<pre><code>TEST_CASE(""Books info is correct"")
{
    Book myBook;
    CHECK_THAT(myBook, IsCorrect(5, 150));
    CHECK_THAT(myBook, IsCorrect(10, 325));
}
</code></pre>

<p>Following the example in the documentation, my intent has been:</p>

<pre><code>// The matcher class
class BookCheck : public Catch::MatcherBase&lt;Book&gt; {
    Book book;
    int chapters = -1;
    int pages = -1;

public:
    BookCheck(int chapters, int pages) : chapters(chapters), pages(pages) {}

    // Performs the test for this matcher
    bool match( Book&amp; b ) const override {
        return b.GetChapters() == chapters &amp;&amp; b.GetPages() == pages;
    }

    virtual std::string describe() const override {
        ostringstream ss;
        //ss &lt;&lt; ""is between "" &lt;&lt; m_begin &lt;&lt; "" and "" &lt;&lt; m_end; // TODO
        return ss.str();
    }
};

// The builder function
inline BookCheck IsCorrect(int chapters, int pages) {
    return BookCheck(chapters, pages);
}
</code></pre>

<p>When I compile this code, I get this errors:</p>

<p><em>error: ‘bool BookCheck::match(Book&amp;) const’ marked ‘override’, but does not override</em></p>

<p><em>error: invalid abstract return type ‘BookCheck’</em></p>

<p><em>error: invalid abstract return type for function ‘BookCheck
   IsCorrect(int, int)’</em></p>

<p><em>error: invalid cast to abstract class type
   ‘BookCheck’</em></p>

<p>Could you point me what am I doing wrong here?</p>
",https://stackoverflow.com/questions/60098024/how-to-implement-a-custom-matcher-to-check-for-object-equality-in-catch2,"['c++', 'unit-testing', 'abstract-class', 'catch2']",993,True,0,1
How to write Unit test cases for Web hooks in c#?,"<p>I have a web page which receives web hook request and i want to write Unit test cases (NUnit framework) for this web hook. I want to mock the web hook request (Post request) in unit test cases and pass the <strong>request headers</strong> and body as the <strong>Json data</strong> to the web page which receives request.</p>

<p><strong><em>Web page name</em></strong></p>

<pre><code>/webhook/receiveWebHook.aspx
</code></pre>

<p><strong><em>Request Headers</em></strong></p>

<pre><code>Content-Type: application/json
messageType: TestInsertNotification
</code></pre>

<p><strong><em>Request Body (Json data)</em></strong></p>

<pre><code>{ 
   ""Alias"":""Test"",
   ""TransactionID"":""123""
}
</code></pre>

<p><strong><em>Code in web page:</em></strong></p>

<pre><code>protected void Page_Load(object sender, EventArgs e)
{
      if (HttpContext.Current.Request.HttpMethod.ToUpper() == ""POST"")
      {
           object notification = null;
           string message = string.Empty;

           Int32 pID = InsertHTTPRequest(HttpContext.Current.Request); //Generate id in DB

           if (pID &gt; 0 &amp;&amp; this.Request.ContentType == ""application/json"")
           {
                StreamReader sr = new StreamReader(this.Request.InputStream, this.Request.ContentEncoding);
                message = sr.ReadToEnd();
                TextReader content = new StreamReader(new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(message)));
                JToken json = JToken.Load(new JsonTextReader(content));
                notification = new JsonSerializer().Deserialize(new JTokenReader(json), this.GetTypeOfMessage(HttpContext.Current.Request.Headers(""MessageType"")));   
           }
            if (notification != null)
            {
                 if (notification is InsertNotification)
                 {
                      InsertNotification insertNotification = notification as InsertNotification;
                      DbInsertMethod(pID, message, insertNotification);
                 }
            }
      }
}
</code></pre>

<p>Can someone please help how to achieve unit testing for webhooks in c#? 
Also, please suggest how to pass HTTP Post request from Unit test method with Header and body (containing Json data)?</p>

<p><strong>P.S.:</strong> Currently i'm using Postman to test the functionality of this webhook.</p>
",https://stackoverflow.com/questions/59746365/how-to-write-unit-test-cases-for-web-hooks-in-c,"['asp.net', 'unit-testing', 'nunit', 'httprequest', 'webhooks']",946,False,0,1
"Python 3.75, importing package that is installed in edit mode","<h2>Problem:</h2>
<p>I'm setting up unit testing with <code>pytest</code> and need to import the objects I want to test. I installed the package that I am testing in edit mode. However, <code>from my_pkg.file import File</code> causes <code>ImportError</code>.</p>
<p>I can see the module installed with a reference to my remote repository, prepended with an <code>-e</code> semaphore when I run <code>pip freeze</code>.</p>
<p>I also see the egg object sitting in the package directory in /src.</p>
<h2>Error Message in console:</h2>
<blockquote>
<p>ImportError while importing test module
'C:\Users\zzz\source\repos\proj\application\tests\test_file.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
return _bootstrap._gcd_import(name[level:], package, level)
from my_pkg.file import File E   ModuleNotFoundError: No module named 'my_pkg'</p>
</blockquote>
<h2>Package Directory:</h2>
<p><a href=""https://i.stack.imgur.com/dXRdk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/dXRdk.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/64899141/python-3-75-importing-package-that-is-installed-in-edit-mode,['python'],73,False,0,0
React useState hook inside useEffect hook does not set state when running unit tests,"<p>I am learning React and am now trying out unit testing. I have login functional component with this following code fragment:</p>
<pre><code>const [users, setUsers] = useState&lt;User[]&gt;([]);

useEffect(() =&gt; {
  usersService.getUsers().then((allUsers: User[]) =&gt; {
    setUsers(allUsers);
  });
}, []); // eslint-disable-line react-hooks/exhaustive-deps
</code></pre>
<p>It all works just fine when I run the app. However, when I try to run the test for this, it does not set the users to state. Here is a mock and a test that I wrote:</p>
<pre><code>const usersServiceMock: UsersService = {
  getUsers: (): Promise&lt;User[]&gt; =&gt; {
    return new Promise((resolve) =&gt; {
      process.nextTick(() =&gt;
        resolve([{ username: 'test', password: 'test', imageUrl: '', id: 0 } as User])
      );
    });
  },
} as UsersService;

it('logs user in', async () =&gt; {
  const loginSpy = jest.spyOn(loginServiceMock, 'logUserIn');
  const usersSpy = jest.spyOn(usersServiceMock, 'getUsers');

  const component = render(
    &lt;Login loginService={loginServiceMock} usersService={usersServiceMock} /&gt;
  );

  expect(usersSpy).toHaveBeenCalledTimes(1);
  //up until here, test is fine, but users are not set inside component  
});
</code></pre>
<p>Mock service is provided properly and mocked user data is properly resolved but setUsers(allUsers) does not actually set it with tests. Inside the effect, usersService.getUsers() does get mocked data but it never sets it.</p>
<pre><code>const [users, setUsers] = useState&lt;User[]&gt;([]);

useEffect(() =&gt; {
  usersService.getUsers().then((allUsers: User[]) =&gt; {
    // allUsers value is [{ username: 'test', password: 'test', imageUrl: '', id: 0}]        
    setUsers(allUsers);
    // users value is []
  });
}, []); // eslint-disable-line react-hooks/exhaustive-deps
</code></pre>
<p>Here is function that uses the state. It works when running the app, but when running tests, users is still empty array.</p>
<pre><code>const login = (): void =&gt; {
const userFromDb = users.find((u) =&gt; u.username === user.username);
if (!userFromDb || userFromDb.password !== user.password) {
  setUser({
    username: '',
    password: '',
    imageUrl: '',
  });
  setIsDialogOpen(true);
 } else {
  loginService.logUserIn(userFromDb);
  history.push('/home');
 }
};
</code></pre>
<p>Any ides?</p>
",https://stackoverflow.com/questions/63015111/react-usestate-hook-inside-useeffect-hook-does-not-set-state-when-running-unit-t,"['reactjs', 'unit-testing']",714,False,0,1
"Connected component reads from Redux store, but action creators don&#39;t update it","<p>I've got a connected component that gets information from the Redux store and displays it onscreen. But whenever I try and dispatch an action to update the state, it doesn't end up doing anything:</p>
<p><code>AppSettings.js</code></p>
<pre class=""lang-js prettyprint-override""><code>import {
  MINUTE_MS,
  MINUTE_S,
} from '../constants'
import {
  decrementSession,
  incrementSession,
} from './timerSlice'

import React from 'react'
import { connect } from 'react-redux'
import equal from 'fast-deep-equal'

/* eslint-disable no-useless-constructor */

export class AppSettings extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      sessionLength: this.props.sessionLength,
    }
  }

  componentDidUpdate(prevProps) {
    if (!equal(this.props, prevProps)) {
      this.setState((_, props) =&gt; {
        return {
          sessionLength: props.sessionLength,
        };
      })
    }
  }

  render() {
    let sessionLength = Math.floor(this.props.sessionLength / MINUTE_MS) % MINUTE_S
    sessionLength = ('0' + sessionLength).slice(-2)
    
    return (
      &lt;div&gt;
        &lt;div&gt;
          &lt;h3&gt;
            session
          &lt;/h3&gt;
          &lt;button 
            id='sessionUp'
            onClick={this.props.incrementSession}
            &gt;
            up
          &lt;/button&gt;
          &lt;h4&gt;
            {sessionLength}
          &lt;/h4&gt;
          &lt;button 
            id='sessionDown'
            onClick={this.props.decrementSession}
            &gt;
            down
          &lt;/button&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }
}

function mapStateToProps(state) {
  return {
    sessionLength: state['sessionLength'],
  };
}

function mapDispatchToProps() {
  return {
    decrementSession,
    incrementSession,
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(AppSettings)
</code></pre>
<p><code>timerSlice.js</code></p>
<pre class=""lang-js prettyprint-override""><code>import {
  DEFAULT_SESSION,
  MINUTE_MS,
} from '../constants'

import { createSlice } from '@reduxjs/toolkit'

export const timerSlice = createSlice({
  name: 'timer',
  initialState: {
    sessionLength: DEFAULT_SESSION,
  },
  reducers: {
    decrementSession(state) {
      state['sessionLength'] -= MINUTE_MS
    },
    incrementSession(state) {
      state['sessionLength'] += MINUTE_MS
    },
  }
})

export const {
  decrementSession,
  incrementSession,
} = timerSlice.actions

export default timerSlice.reducer
</code></pre>
<p><code>store.js</code></p>
<pre class=""lang-js prettyprint-override""><code>import { configureStore } from '@reduxjs/toolkit'
import reducer from '../features/timerSlice'

const store = configureStore({
  reducer: reducer
})

export default store
</code></pre>
<p>Upon initial render, the component reads from the store just fine, and displays the appropriate value. Unit testing showed that the component updates the value rendered onscreen when it's passed new props. My unit test also shows that the appropriate functions are called whenever buttons are pressed. I ran my app in the browser, and it showed that the Redux store wasn't being updated at all.</p>
<p>How come my store isn't responding whenever I try and dispatch actions from my component?</p>
",https://stackoverflow.com/questions/64615804/connected-component-reads-from-redux-store-but-action-creators-dont-update-it,"['javascript', 'reactjs', 'redux', 'react-redux', 'redux-toolkit']",136,True,0,1
How to create a getter method for an abstract method that is inside an enum in Java?,"<p>I have an enum that contains an non-public abstract method and I can not change the visibility of this abstract method. The abstract method is implemented for every single unit inside the enum.</p>
<p>I am trying to access this method from another package for the purposes of unit testing, but I can not because it is not visible in the other package. Is there a way where I can create a getter method for an abstract method?</p>
<p>Is there a different way to do the unit test in a way that does not involve using a getter method or changing the visibility of the abstract method?</p>
<p>Here is an example of the code I am working with:</p>
<pre><code>public enum random {
    A{
    someFunction() {
        System.out.println(&quot;A&quot;);
    }
    }
    B{
    someFunction() {
    System.out.println(&quot;B&quot;);
    }
    }
    C{
    someFunction() {
    System.out.println(&quot;C&quot;);
    }
    }

    abstract void someFunction();
};
</code></pre>
",https://stackoverflow.com/questions/64899371/how-to-create-a-getter-method-for-an-abstract-method-that-is-inside-an-enum-in-j,['java'],79,True,0,1
TypeScript compiler doesn&#39;t recognize definition files,"<p>I've been unit-testing some code that depends on interfaces and classes I am unable to import, but can add to intellisense through d.ts files. Despite having the &quot;include&quot; property in my tsconfig mention those files, I get errors about how TypeScript couldn't compile because it couldn't find any of those interfaces I am using.</p>
<p>My tsconfig:</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;es6&quot;,
    &quot;module&quot;: &quot;CommonJS&quot;,
    &quot;esModuleInterop&quot;: true,

    &quot;sourceMap&quot;: false,
    &quot;downlevelIteration&quot;: true,

  },
  &quot;include&quot;: 
  [
    &quot;_MainSource/**/*&quot;, 
    &quot;Tests/**/*&quot;, 
    &quot;@typeDefs/**/*&quot;
  ],


}
</code></pre>
<p>The error I get:</p>
<pre><code>error TS2503: Cannot find namespace 'RPG'.
</code></pre>
<p>My current test command:</p>
<pre><code>mocha -r ts-node/register Tests/**/*.ts
</code></pre>
<p>I have tried adding a 'ts-node --files' to the test command, getting me what you see here:</p>
<pre><code>mocha -r ts-node/register 'ts-node --files' Tests/**/*.ts
</code></pre>
<p>But then I get errors about how TS can't find ts-node (even though ts-node is installed, and the original command works fine on code that doesn't rely on the RPG namespace).</p>
",https://stackoverflow.com/questions/63336555/typescript-compiler-doesnt-recognize-definition-files,"['typescript', 'unit-testing', 'mocha.js', 'ts-node']",171,False,0,1
Jasmine strange reference behavior based on commenting out functions,"<p>I am doing some unit testing with Jasmine and I am having this strange reference behavior. I am using ASP.NET core with Chutzpah to view my client testing. Here is my test file:</p>
<pre class=""lang-js prettyprint-override""><code>/// &lt;reference path=&quot;..\..\Project.Web\wwwroot\lib\jquery\dist\jquery.js&quot;/&gt;
/// &lt;reference path=&quot;../../Project.Web/wwwroot/js/alerts.js&quot;/&gt;

describe(&quot;clearAlerts&quot;, function () {

    beforeEach(function () {

        this.mockContainer = {
            children: function () {
                return this.mockChildrenObj
            },
            mockChildrenObj: {
                addClass: function (text) { this.filledData = [text] },
                filledData: [&quot;NO_DATA&quot;]
            }
        }
    });

    it(&quot;should add the class is-hidden to the container&quot;, function () {

        // Act
        clearAlerts(this.mockContainer);

        // Assert
        expect(this.mockContainer.mockChildrenObj.filledData).toEqual([&quot;is-hidden&quot;]);
    });
});
</code></pre>
<p>And my src:</p>
<pre class=""lang-js prettyprint-override""><code>function clearAlerts($alertsContainer) {
    $alertsContainer.children().addClass(&quot;is-hidden&quot;);
}

function sendErrorAlert(message, $notificationElem, $inputElemToHighlight = null) {

    // Shows the notification
    $notificationElem.removeClass(&quot;is-hidden&quot;);
    $notificationElem.children('#errorNotificationMsg').first().text(message);

    // Test to see if we need to highlight an input element
    if ($inputElemToHighlight != null) {
        $inputElemToHighlight.addClass(&quot;is-danger&quot;);
    }

    var height = $notificationElem.innerHeight();
    var left = $(document).innerWidth() / 2 - $notificationElem.innerWidth() / 2;
    $notificationElem.css({ top: (-1 * height), left: left }).animate({ top: `+=${height}px` }, &quot;slow&quot;, &quot;swing&quot;);
}
</code></pre>
<p>Just running the test just like this, I have the following error in my test explorer:</p>
<pre><code>ReferenceError: Can't find variable: clearAlerts in (PATH HERE)/Project/Project.test/client/alerts.test.js (line 21)
</code></pre>
<p>HOWEVER, if I comment out the entirety of <em>sendErrorAlert</em>, the test passes! I have no configuration folders, as visual studio seems to be able to handle the packages. I just can't get my test to reference the function when there are other functions. This has been the case for other files as well. Any help will be greatly appreciated for a stack overflow newbie.</p>
",https://stackoverflow.com/questions/64866930/jasmine-strange-reference-behavior-based-on-commenting-out-functions,"['javascript', 'asp.net-core', 'jasmine']",46,False,0,1
Validate json in spring boot application,"<p>Working on a Spring Boot application, one of the functionality will include software update. It will be described in a <code>JSON</code> like this:</p>

<pre><code>{
 ""DeviceProfile"": {
    ""firmware"": {
        ""name"": ""firmware_a"",
        ""version"": ""2.0.24.3"",
        ""url"": "" "",
        ""isPatch"": true,
        ""patchdependency"":  ""1.0.0""
    },
    ""software"": [
        {
            ""name"": ""mySoftware1"",
             ""version"": ""1.0.0"",
               ""url"": ""http://www.example.com"",
             ""action"": ""install""
        },
        {
            ""name"": ""mySoftware2"",
            ""version"": ""1.1.0"",
            ""url"": ""http://www.example.com"",
            ""action"": ""install""
        },
        {
            ""name"": ""mySoftware3"",
            ""version"": ""2.0.0"",
            ""url"": ""http://www.example.com"",
            ""action"": ""install""
        }
    ],
    ""configuration"": [
        {
            ""url"": ""https://www.examples.com"",
            ""type"": ""myConfigType_1"",
            ""name"": ""myConfig_1”
        },
        {
            ""url"": ""https://www.examples.com"",
            ""type"": "" myConfigType_2"",
        ""name"": ""myConfig_2”
        }
    ]
 }
}
</code></pre>

<p>There are several conditions, that have to be fulfilled - the ""configuration"" list to contain exactly one element and its name to be a defined string. The name of each element in the <code>software</code> part should start with a defined prefix. There can be other additional conditions also. So I was wondering which is the best way to do this. I can create a <code>DeviceProfile</code> class to extract the data, using <code>ObjectMapper</code>, and then implement check for every single condition, but I was wondering whether there is better way to do this. Please advise also for unit testing of the approach.</p>
",https://stackoverflow.com/questions/61464291/validate-json-in-spring-boot-application,"['java', 'json', 'spring', 'spring-boot', 'validation']",199,False,0,1
Android Unit test : java.lang.UnsatisfiedLinkError: no &lt;library-name&gt; in java.library.path,"<p>I write this message because I am facing an issue with my android unit testing and I need your help please.</p>
<p>Actually in my Android app I am using a module (object) that I import from a jar file :</p>
<ul>
<li>I have a toto.jar in my /project/libs (for example /project/libs/toto.jar)</li>
<li>In my build.gradle I have those two lines in order to import the jar file :</li>
</ul>
<blockquote>
<p>api fileTree(dir: &quot;libs&quot;, include: [&quot;*.jar&quot;])</p>
</blockquote>
<blockquote>
<p>implementation fileTree(include: ['*.so'], dir: 'jniLibs')</p>
</blockquote>
<ul>
<li>in my MainActivityHelper I import the class of the library toto :</li>
</ul>
<blockquote>
<pre><code>import com.toto.library.myClass
</code></pre>
</blockquote>
<p>Then I use it like this in a method</p>
<blockquote>
<pre><code> var myClass: MyClass = MyClass()
 myClass.doSomething()
</code></pre>
</blockquote>
<p>in my unit test file I am trying to mock it :</p>
<blockquote>
<pre><code>@Mock
private var mockMyClass: myClass? = null
</code></pre>
</blockquote>
<p>While trying to run my test , I always got this error :</p>
<pre><code>java.lang.UnsatisfiedLinkError: no &lt;library-name&gt; in java.library.path
</code></pre>
<p>I can see that there is a file inside the library that is trying to load a library , and maybe it produced this error message</p>
<pre><code>static {
    try {
        System.loadLibrary(&quot;toto&quot;);
    } catch (NoClassDefFoundError var1) {
    }

}
</code></pre>
<p>But even after searching on many other thread, and tried other solution I don't understand how to make my jar file available for my unit test.</p>
<p>Actually my unit test files are in  :
/home/username/AndroidStudioProject/project-name/src/test/java/com/my/package</p>
<p>My jar files are in :
/home/username/AndroidStudioProject/project-name/libs</p>
<p>Some other &quot;.so&quot; (for example tata.so file), linked to jar files (toto.jar), are in :
/home/username/AndroidStudioProject/project-name/src/main/jniLibs</p>
<p>And my app project files are in :
/home/username/AndroidStudioProject/project-name/src/main/java</p>
<p>Please is there any way to make it know while unit testing compile , that jar libraries files are in libs folder ? Do I have anything to modify in build.gradle ? (like testOptions ?)</p>
<p>Thank you in advance for your Help !</p>
",https://stackoverflow.com/questions/64805925/android-unit-test-java-lang-unsatisfiedlinkerror-no-library-name-in-java-li,"['android', 'unit-testing', 'kotlin', 'jar', 'mockito']",2274,True,1,1
Angular in-memory-web-api method always returns 404 NotFound in the brower&#39;s console even if the tests passed,"<p>I'm new to unit testing in Angular (using Jasmine and Karma)</p>

<p>I'm trying to create some tests for my httpService, apparently the tests are OK.</p>

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

<p>But sometimes when I either run <code>ng test</code>, or refresh the browser, I found that one of the test in one of the 3 test suites has failed with this message : <code>Uncaught [object Object] thrown</code>.</p>

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

<p>Another annoying thing is that no matter whether all of the tests pass or any of them fail, if you check the browser's console, you'll ALWAYS find this message : </p>

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

<p><a href=""https://drive.google.com/file/d/1w_VDP5CbY7p5o9LlpogfpcAl6gvnBh8D/view?usp=sharing"" rel=""nofollow noreferrer"">I'm attaching the code in a zip file (uploaded to Drive)</a>. You only need to run <code>npm install</code> and <code>npm start</code>.</p>

<p>I really hope you can help me understand why this testing behaves like a Russian roulette. </p>
",https://stackoverflow.com/questions/60593259/angular-in-memory-web-api-method-always-returns-404-notfound-in-the-browers-con,"['jasmine', 'karma-runner', 'angular-test']",168,False,0,1
Unit Testing HTTP Post request with database access,"<p>Hi I'm currently trying to learn and implement some unit testing for my HTTP Requests. currently I have a SQlite db setup, and a simple post request. This is the test I have written so far:</p>

<pre><code>""use strict"";
process.env.NODE_ENV = 'test';

const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;

const app = require('../../../app');

chai.request('http://localhost:8080')
    .put('/tempValue')
    .send({sensorid: '1', sensorValue: '25.00', timeRecorded: '2020-04-12 12:30'})
    .then(function (res) {
        expect(res).to.have.status(200);
    })
    .catch(function (err) {
        throw err;
    });


</code></pre>

<p>I seem to be getting a error that it is unable to open the database file. Currently I am just connecting to the database in the app.js file, using <code>const dbPath = ""./database/database.db"";</code> and  <code>const dbConnection = sqlite.open(dbPath, { Promise });</code></p>

<p>I also seem to get errors about incorrect use of .catch? This is the error log:</p>

<pre><code>(node:13952) UnhandledPromiseRejectionWarning: Error: SQLITE_CANTOPEN: unable to open database file
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13952) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13952) UnhandledPromiseRejectionWarning: AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
    at D:\Uni Work\3rd Year\302CEM - Agile Development\Penguin Project\test\api\temperature\get.js:15:29
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
</code></pre>

<p>Thanks for any help!</p>

<p>EDIT:</p>

<p>This is the particular post request I'm testing, it uses MQTT to check if the message being sent is to that topic structure, then inserts into the database.</p>

<pre><code>app.ws.use(route.all('/tempValue', function (ctx){
    client.on('message', async function(topic,message){
        console.log(topic, message.toString());
        if (topic === '302CEM/Penguin/Room1/Temperature'){
            const SQL = ""INSERT INTO sensorData (sensorid, sensorValue, timeRecorded) VALUES (?,?,?)"";
            try {
                const temptostring = message.toString();
                const db = await dbConnection;
                await db.run(SQL, [""1"",temptostring, moment().format('YYYY-MM-DD HH:mm')]);
                ctx.websocket.send(temptostring);
            } catch (err) {
                console.log(err);
            }
        }
    })
}));
</code></pre>
",https://stackoverflow.com/questions/61367704/unit-testing-http-post-request-with-database-access,"['node.js', 'sqlite', 'unit-testing', 'chai', 'chai-http']",163,False,0,0
Laravel Cashier - Unit Tests with creating subscriptions with payment methods,"<p>Looking deeper into this, I'm not sure it's even possible, which is a shame because I'm trying to learn TDD.</p>

<p>I would like to test my model with <code>Billable</code> being created and subscribed to a plan.</p>

<pre><code>/** @test */
public function an_account_can_subscribe_to_a_plan() {
    $account = factory(""App\Account"")-&gt;create();

    Stripe::setApiKey('key');
    $paymentMethod = PaymentMethod::create([
        'type' =&gt; 'card',
        'card' =&gt; [
            'number' =&gt; '4242424242424242',
            'exp_month' =&gt; '2',
            'exp_year' =&gt; '2021',
            'cvc' =&gt; '314'
        ]
    ]);

    $subscription = $account-&gt;newSubscription('default', 'starter')-&gt;create($paymentMethod);
    $this-&gt;assertTrue( $subscription-&gt;valid() );  
}
</code></pre>

<p>The Laravel Cashier docs show how to send a token via Stripe.js, but that doesn't work for Unit Testing.</p>

<p>I've tried to include the Stripe library directly and create a <code>PaymentMethod</code> object, but this also requires me set an API key manually. Now the error I'm getting is that I have to verify my phone number to send raw credit card numbers to the stripe API.</p>

<p>I'm hoping there's a better way. How can I use Laravel Cashier in a TDD way and mock up fake subscriptions with fake payment methods?</p>
",https://stackoverflow.com/questions/60398112/laravel-cashier-unit-tests-with-creating-subscriptions-with-payment-methods,"['laravel', 'stripe-payments', 'laravel-cashier']",2271,True,4,2
Can an official CRAN R package depend on Intel MKL and CMake? (and Check ?),"<p>In my R package I have C code that uses <a href=""https://software.intel.com/en-us/mkl"" rel=""nofollow noreferrer"">Intel MKL</a> (and an open source library for <a href=""https://libcheck.github.io/check/"" rel=""nofollow noreferrer"">C unit testing</a>). I use <a href=""https://cmake.org/"" rel=""nofollow noreferrer"">CMake</a> to build the C code. I also have <a href=""http://www.rcpp.org/"" rel=""nofollow noreferrer"">Rcpp</a> interface code that I use to call the C code from R. </p>

<p>I wanted to know if <a href=""https://cran.r-project.org/"" rel=""nofollow noreferrer"">CRAN</a> would accept this package given that you'd have to have Intel MKL and CMake already installed on your system for it to work? </p>

<p>I'm not too worried about the unit testing, I can always get rid of that, but I definitely need Intel MKL because I'm using linear algebra routines that are specific to MKL e.g. Sparse-Matrix-Dense-Matrix multiply etc. </p>

<p>The reason I need CMake is because currently, that's what I'm using to build a static library from the C code and manipulate the <code>Makevars</code> file in the package's <code>src</code> folder, so that I can link the Rcpp interface code against the C library.</p>

<p>My <code>Makevars</code> looks as follows:</p>

<pre><code>PKG_CPPFLAGS=-I/usr/local/lib/R/site-library/Rcpp/include -I/opt/intel/compilers_and_libraries_2019.4.243/linux/mkl/include -I./C
PKG_LIBS=-L./C/cmake-build-release -lbcd -llog -Wl,--start-group /opt/intel/compilers_and_libraries_2019.4.243/linux/mkl/lib/intel64/libmkl_intel_ilp64.a /opt/intel/compilers_and_libraries_2019.4.243/linux/mkl/lib/intel64/libmkl_sequential.a /opt/intel/compilers_and_libraries_2019.4.243/linux/mkl/lib/intel64/libmkl_core.a -Wl,--end-group -lpthread -lm -ldl 
</code></pre>

<p>This works on Ubuntu, but I'm worried about OS X and especially Windows. For example, <a href=""https://stackoverflow.com/questions/10723165/using-visual-c-with-r/44381109#44381109"">here</a> someone claims that Intel MKL is not compatible with <code>minGW</code>.</p>

<p>I know that there are many CRAN packages that use either MKL or CMake. But for the ones that I've investiaged, MKL is used as an optional BLAS library and CMake is used to build what's under the <code>inst</code> folder, which did not depend on external libraries. I've looked at <a href=""https://cran.r-project.org/doc/manuals/r-release/R-exts.html"" rel=""nofollow noreferrer"">writing R extensions</a> and also the <a href=""https://cran.r-project.org/"" rel=""nofollow noreferrer"">CRAN submission page</a> but wasn't able to find find an answer. I thought that since there are more and more people interested in using CMake and MKL with R it would be good to have a SO post. </p>
",https://stackoverflow.com/questions/61333914/can-an-official-cran-r-package-depend-on-intel-mkl-and-cmake-and-check,"['r', 'cmake', 'intel-mkl', 'cran']",492,True,0,1
Automapper ProjectTo not working with EFCore in memory database (unit tests),"<p>We are using Automappers ProjectTo method to build a DTO object that is a subset of a larger database view. It is working as expected when running the actual application but we have had a problem where it doesn't give expected results when unit testing with an EF Core In-Memory database. It seems to just be giving back 0 results no matter what the query. Here is the test I am trying to run.</p>

<pre><code>[Fact]
public async Task GetTemplateAdHocReportList_ReturnsOnlyTemplateReports()
{
    await TestHelper.SeedFull(ReportContext); // Calls SeedAdHocReports below along with other seed methods

    var results = await _sut.GetTemplateAdHocReports();

    results.Where(x =&gt; !x.IsTemplate).Count().Should().Be(0);
}
</code></pre>

<p>This is the Seed Data:</p>

<pre><code>public static async Task SeedAdHocReports(ReportContext context)
{
    var reports = new AdHocReport[]
    {
        new AdHocReport()
        {
            Id = 1,
                Name = ""DevExtreme Example Report"",
                IsTemplate = true,
                AdHocDataSourceId = 1,
                Fields = ""[{\""caption\"":\""Category\"",\""dataField\"":\""ProductCategoryName\"",\""expanded\"":true,\""area\"":\""row\""},{\""caption\"":\""Subcategory\"",\""dataField\"":\""ProductSubcategoryName\"",\""area\"":\""row\""},{\""caption\"":\""Product\"",\""dataField\"":\""ProductName\"",\""area\"":\""row\""},{\""caption\"":\""Date\"",\""dataField\"":\""DateKey\"",\""dataType\"":\""date\"",\""area\"":\""column\""},{\""caption\"":\""Amount\"",\""dataField\"":\""SalesAmount\"",\""summaryType\"":\""sum\"",\""format\"":{\""type\"":\""currency\"",\""precision\"":2,\""currency\"":\""USD\""},\""area\"":\""data\""},{\""caption\"":\""Store\"",\""dataField\"":\""StoreName\""},{\""caption\"":\""Quantity\"",\""dataField\"":\""SalesQuantity\"",\""summaryType\"":\""sum\""},{\""caption\"":\""Unit Price\"",\""dataField\"":\""UnitPrice\"",\""format\"":\""currency\"",\""summaryType\"":\""sum\""},{\""dataField\"":\""Id\"",\""visible\"":false}]"",
                Status = true
        }
    };

    context.AdHocReports.AddRange(reports);
    await context.SaveChangesAsync();
}
</code></pre>

<p>Here is the GetTemplateAdHocReports method being tested</p>

<pre><code>public async Task&lt;IList&lt;AdHocReportDto&gt;&gt; GetTemplateAdHocReports()
{
    //This gives the expected 1 object in the unit tests:
    var test = await _reportContext.AdHocReports.Where(x =&gt; x.Status &amp;&amp; x.IsTemplate).OrderBy(x =&gt; x.Name).ToListAsync();

    //This always comes back with a count of 0 even though the seed data should return 1 result
    var results = await _reportContext.AdHocReports.Where(x =&gt; x.Status &amp;&amp; x.IsTemplate).OrderBy(x =&gt; x.Name).ProjectTo&lt;AdHocReportDto&gt;(_mapper.ConfigurationProvider).ToListAsync();
    return results;
}
</code></pre>

<p>Finally in case they are useful here are the constructors:</p>

<pre><code>public AdHocServiceTests()
{
    TestHelper = new TestHelper();

    var reportOptions = TestHelper.GetMockedReportDbOptions();
    ReportContext = new ReportContext(reportOptions);

    _sut = new AdHocService(ReportContext, TestHelper.Mapper, TestHelper.GetMockedNiceService().Object);
}

public TestHelper()
{
    var mappingConfig = new MapperConfiguration(cfg =&gt;
    {
        cfg.AddProfile&lt;ReportDtoMapperProfile&gt;();
    });
    Mapper = mappingConfig.CreateMapper(); // public property on TestHelper
}

public AdHocService(ReportContext reportContext, IMapper mapper, INiceService niceService)
{
    _niceService = niceService;
    _mapper = mapper;
    _reportContext = reportContext;
}
</code></pre>

<p>So the final question is why does the ""var test = "" line above work, but the following ""var results ="" line with the ProjectTo just keeps giving back 0 results?</p>
",https://stackoverflow.com/questions/60837497/automapper-projectto-not-working-with-efcore-in-memory-database-unit-tests,"['.net-core', 'automapper', 'xunit']",513,False,4,0
Mapped types: remove private interface,"<p>In TypeScript, private attributes are considered part of the shape (or interface) of a type.</p>

<pre><code>class Person {
  constructor(private name: string, public age: number) { }
}
const p: Person = { age: 42 };
// Error: Property 'name' is missing.
</code></pre>

<p>This is valid, because TypeScript needs to keep track of privates.</p>

<pre><code>class Person {
  constructor(private name: string, public age: number) { }
  equals(other: Person) {
    return this.name === other.name &amp;&amp; this.age === other.age;
    // This is valid, because TypeScript kept track of the private `name` property!
  }
}
</code></pre>

<p>However, there usually you want to ignore the private interface. For example, when you're using dependency injection and unit testing.</p>

<pre><code>class HttpClient {
   constructor(private log: Logger) {
   }
   async doGet(url: string) { 
      return (await fetch(url)).json();
   }
}

class MyService {
  constructor(private http: HttpClient) {
  }
  // Implementation
}

// Unit test for MyService:
describe('MyService', () =&gt; {
  it('should work', () =&gt; {
    const httpMock: HttpClient = { // ERROR: Property 'log' is missing
      doGet(url: string) {
         return Promise.resolve({ name: 'Han' });
      }
    };
    const sut = new MyService(httpMock);
  });
});
</code></pre>

<p>I know we could solve this by adding an interface <code>IHttpClient</code> which describes the public interface for an <code>HttpClient</code> and use that instead of the class type directly, but that is a lot of work and it need to be kept in sync manually. </p>

<p>Is there a way to remove all non-public properties from a type using a mapped type?</p>

<p>Something like:</p>

<pre><code>type PublicInterface&lt;T&gt; = {
    [P in PublicNames&lt;T&gt;]: T[P];
}
</code></pre>

<p>So it could be used in places where you do not care about privates:</p>

<pre><code>class MyService {
  constructor(private http: PublicInterface&lt;HttpClient&gt;) {
  }
  // Implementation
}
</code></pre>
",https://stackoverflow.com/questions/60389559/mapped-types-remove-private-interface,"['typescript', 'mapped-types']",1348,True,4,1
Unit Testing a custom TagHelper where HTML conditionally rendered based on the presence of a ValidationAttribute on the model Property,"<p>I have a custom TagHelper which extends the OOTB InputTagHelper. I am conditionally adding attributes to it based on the presence of a custom ValidationAttribute on the model property associated with it. The code for this in the TagHelper <code>.Process</code> method works fine:</p>
<pre><code>if (this.For.Metadata.ValidatorMetadata.OfType&lt;NumericValidationAttribute&gt;().Any())
{
   output?.Attributes.SetAttribute(new TagHelperAttribute(&quot;inputmode&quot;, &quot;numeric&quot;));
   output?.Attributes.SetAttribute(new TagHelperAttribute(&quot;pattern&quot;, &quot;[0-9]*&quot;));
}
</code></pre>
<p>My issue is in Unit Testing this. I have other Unit Tests written using the code available in the Net Core MVC Test repo: <a href=""https://github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/"" rel=""noreferrer"">https://github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/</a></p>
<p>... but there's no real steer on how to create the <code>For</code> i.e <code>ModelExpression</code> for the property I want to test which has this Validation attribute associated with it: e.g.</p>
<pre><code>    public class TestModel
    {
        [NumericValidation(ErrorMessage = &quot;Error message&quot;)]
        public string Field1 { get; set; }
    }
</code></pre>
<p>I want to be able to populate the <code>For.Metadata.ValidatorMetadata</code> list for this ModelExpression and I don't know how.</p>
<p>The full Unit Test which doesnt work is:</p>
<pre><code>[Fact]
        public void CustomInputTagHelperProcess_NumericValidationAttributeOnModelProperty_GeneratesCorrectHtml()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
            var model = new TestModel
            {
                Field1 = &quot;cc&quot;,
            };
            var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(TestModel), model);
            var modelExpression = new ModelExpression(name: &quot;Field1&quot;, modelExplorer: modelExplorer);
            var viewContext = TestableHtmlGenerator.GetViewContext(model, metadataProvider);

            var attributes = new TagHelperAttributeList
            {
                { &quot;name&quot;, PropertyName },
                { &quot;type&quot;, InputTypeName },
            };

            var tagHelperContext = new TagHelperContext(attributes, new Dictionary&lt;object, object&gt;(), nameof(CustomInputTagHelperTest));

            var output = new TagHelperOutput(
                Input,
                new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =&gt; Task.FromResult&lt;TagHelperContent&gt;(result: null))
            {
                TagMode = TagMode.SelfClosing,
            };

            var customInputTagHelper = new CustomInputTagHelper(this.htmlGenerator)
            {
                For = this.modelExpression,
                InputTypeName = InputTypeName,
                Name = PropertyName,
                ViewContext = this.viewContext,
            };

            // Act
            customInputTagHelper.Process(this.tagHelperContext, output);

            // Assert - ensure we have an inputmode attribute on the input.
            Assert.Contains(output.Attributes, x =&gt; x.Name == &quot;inputmode&quot; &amp;&amp; x.Value.ToString() == &quot;numeric&quot;);
        }
</code></pre>
<p>Any thoughts?</p>
",https://stackoverflow.com/questions/65239861/unit-testing-a-custom-taghelper-where-html-conditionally-rendered-based-on-the-p,"['unit-testing', 'asp.net-core-mvc', 'asp.net-core-tag-helpers', 'validationattribute']",342,False,8,0
Getting jest to only transform certain file types in a module,"<p>I currently have a project that uses jest for unit testing. The issue I an encountering is that one of the dependency modules is requiring a .css file:</p>

<pre><code>./node_modules/problem-module/dist/problem-module.js:

  line 0: require(""./problem-module.css"");
</code></pre>

<p>I configured jest to not ignore that specific module for transformation, fixing the issue with the CSS being required. Although, now the test blows up because jest is attempting to also transform all of the .js files in the module with babel-jest, which have all previously been ran through babel prior to the module being published. which results in an error similar to:</p>

<pre><code>TypeError: (0 , problemModuleFunction.default) is not a function
</code></pre>

<p>My jest configuration:</p>

<pre><code>  ""jest"": {
    ""testEnvironment"": ""jsdom"",
    ""testMatch"": [
      ""&lt;rootDir&gt;/src/**/*.test.js""
    ],
    ""moduleDirectories"": [
      ""&lt;rootDir&gt;/src"",
      ""&lt;rootDir&gt;/node_modules""
    ],
    ""moduleNameMapper"": {
      ""\\.(css|scss)$"": ""&lt;rootDir&gt;/__mocks__/styleMock.js"",
      ""\\.(jpg|gif|ttf|eot|svg)$"": ""&lt;rootDir&gt;/__mocks__/fileMock.js""
    },
    ""transform"": {
      ""^((?!mock).)*.(js|jsx)$"": ""babel-jest"",
      ""\\.(css|styl|less|sass|scss)$"": ""&lt;rootDir&gt;/node_modules/jest-css-modules-transform""
    },
    ""transformIgnorePatterns"": [
        ""node_modules/(?!(problem-module))""
    ],
    ""setupFilesAfterEnv"": [
      ""&lt;rootDir&gt;/setupTests.js""
    ],
    ""moduleFileExtensions"": [
      ""css"",
      ""scss"",
      ""js"",
      ""json"",
      ""jsx""
    ]
  },
</code></pre>

<p>What would be the best method to make sure that the CSS files from this module are mapped properly without transforming any of the JS files?</p>
",https://stackoverflow.com/questions/60852903/getting-jest-to-only-transform-certain-file-types-in-a-module,"['javascript', 'node.js', 'jestjs', 'babeljs', 'babel-jest']",447,False,3,0
How would I unit test this method?,"<p>I am new to unit testing (xUnit) and I am not quite sure how to approach this method when writing tests for it.</p>
<p>Basically I have a class called Label.cs and in the constructor I use DI to inject 2 interfaces.</p>
<p>I also have a Get() method where it:</p>
<ol>
<li>Constructs a XML request</li>
<li>Removes any invalid characters</li>
<li>Calls the API</li>
<li>Reads the label info from the response</li>
<li>Returns the response</li>
</ol>
<p>Is it possible to write tests for a method like this? I understand that I can mock the dependencies, pass them into the constructor and setup the methods using Moq but what if I had 4 or 5 more validations methods from ILabelValidation inside the Get() method? Would I need to setup all those methods using Moq?</p>
<pre><code>public class Label 
{
    private readonly ICarrierService _carrierService;
    private readonly ILabelValidation _validator;

    public Label(int accountId, ICarrierService carrierService, ILabelValidation validator)
    {
        _carrierService = carrierService;
        _validator = validator;
    }

    public override async Task&lt;CreateShipmentResponse&gt; Get(int accountId, Shipment shipment)
    {
        string xmlRequest = ConstructRequest(shipment);
        
        // strip out any invalid characters inside the request
        xmlRequest = _validator.InvalidCharacterValidation(xmlRequest);

        // what if I have another method that I use from the ILabelValidation?
        // _validator.ValidatePackageCount(3);

        var stringContent = new StringContent(xmlRequest, Encoding.UTF8, &quot;text/xml&quot;);

        // make the API request
        var shipmentResponse = await _carrierService.CreateShipment(dict, stringContent);

        var stream = await shipmentResponse.Content.ReadAsStreamAsync();
        Models.Label labelInfo = GetLabelInfo(stream);

        var response = new CreateShipmentResponse();
        response.labels = new List&lt;string&gt;();

        if (!string.IsNullOrEmpty(labelInfo.Base64String))
            response.labels.Add(labelInfo.Base64String);

        return response;
    }
}
</code></pre>
",https://stackoverflow.com/questions/64114532/how-would-i-unit-test-this-method,"['c#', 'unit-testing', 'moq', 'xunit']",162,True,3,2
Vue unit testing vuex store action with jest,"<p>I'm using Vue version 2.6.11, Vuex version 3.4.0. I have a function in the vuex store (timeTravel) which moves array element from given index to another given index. I have a component with a button that trigger this function. I'm new to unit testing and it's confusing for me.</p>
<p><strong>ActionList.vue component</strong></p>
<pre><code>// other codes

&lt;v-btn color=&quot;primary&quot; dark @click=&quot;timeTravel({from:action.from_index,to:action.to_index,action_list_index:index})&quot;&gt;
  &lt;v-icon left dark&gt;
   mdi-clock-outline
  &lt;/v-icon&gt;
   Submit
&lt;/v-btn&gt;

&lt;script&gt;
import { mapGetters, mapActions } from &quot;vuex&quot;;
export default {
  name: &quot;ActionsList&quot;,
  computed: mapGetters([&quot;commitedActionsList&quot;]),
  methods: {
    ...mapActions([&quot;timeTravel&quot;]),
  },
};
&lt;/script&gt;
</code></pre>
<p><strong>Vuex store</strong></p>
<pre><code>import Vue from &quot;vue&quot;;
import Vuex from &quot;vuex&quot;;
import axios from &quot;axios&quot;;

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    posts: [],
    commitedActions: [],
  },
  getters: {
    postsList: (state) =&gt; state.posts,
    commitedActionsList: (state) =&gt; state.commitedActions,
  },
  mutations: {
    setPosts: (state, posts) =&gt; (state.posts = posts),
    setCommitedActions: (state, commitedActions) =&gt;
      state.commitedActions.push(commitedActions),
  },
  actions: {
    async fetchPosts({ commit }) {
      const response = await axios.get(
        &quot;https://jsonplaceholder.typicode.com/posts/?_limit=5&quot;
      );
      commit(&quot;setPosts&quot;, response.data);
    },
    timeTravel({ commit, getters }, data) {
      var from = data[&quot;from&quot;];
      var to = data[&quot;to&quot;];
      var action_list_index = data[&quot;action_list_index&quot;];
      console.log(from,to,action_list_index);
      var posts_copy = getters.postsList;

      var f = posts_copy.splice(from, 1)[0]; // remove `from` item and store it
      posts_copy.splice(to, 0, f); // insert stored item into position `to`
      commit(&quot;setPosts&quot;, posts_copy);
      
      this.state.commitedActions.splice(action_list_index,1)

    },
  },
  modules: {},
});
</code></pre>
<p>So I want to write a unit test for this timeTravel function with jest. I found some tutorials but it's confusing for me. So far I've come up with this.</p>
<pre><code>import Vuetify from 'vuetify';
import Vuex from 'vuex'
import { createLocalVue ,shallowMount } from '@vue/test-utils'
import ActionsList from '@/components/ActionsList.vue';

let localVue = createLocalVue();

describe('App',()=&gt;{
    let store
    let actions
    let state
    let getters

    beforeEach(()=&gt;{
        localVue.use(Vuex)
        localVue.use(Vuetify)
        state = {posts:[]}

        getters = {
            postsList: (state) =&gt; state.posts,
        }

        actions = {
            timeTravel: jest.fn()
        }

        store = new Vuex.Store({
            state,
            getters,
            actions
        })
    })

    it('dispatches timeTravel', ()=&gt;{
        const wrapper = shallowMount({
            localVue,
            store
        })

        wrapper.find('v-btn').trigger('click')

        expect()
    })
})
</code></pre>
<p>I want to test if timeTravel function is moving element from given index to another given index. So it would be great if someone can point me in the right direction which helps me to write this unit test.</p>
",https://stackoverflow.com/questions/64256875/vue-unit-testing-vuex-store-action-with-jest,"['javascript', 'unit-testing', 'vue.js', 'jestjs', 'vuex']",1046,False,3,0
How to retry an expect statement if it fails in jest,"<p>I am using jest to do unit testing in my react application.</p>
<p>I have a material ui date picker in my application with next and previous buttons and I have the current selected date in the browser url. Whenever user clicks next or previous button, the url gets updated.
I used <code>history.push</code> to do that and I checked that it's working properly in the ui. But the test case I have to verify this is failing at the following expect statement <code>expect(history.push).toBeCalledWith('/path/to/url?date=${date}');</code> saying 0 calls are made to this function. I want to retry only this particular expect statement a couple more times if it fails to make sure that it's not failing due to some delay. How can I do that?</p>
<p><code>retry(expect(history.push).toBeCalledWith('/path/to/url?date=${date}'), numTimes);</code></p>
",https://stackoverflow.com/questions/63067484/how-to-retry-an-expect-statement-if-it-fails-in-jest,"['javascript', 'reactjs', 'jestjs', 'material-ui', 'react-testing-library']",1799,True,2,1
Unit testing with FakeAsync in Dart,"<p>I'm kind of new to unit testing, and I am writing a unit test which uses the <a href=""https://pub.dev/packages/quiver"" rel=""nofollow noreferrer"">quiver package</a> for faking async execution. The function I am using looks something like this:</p>

<pre class=""lang-dart prettyprint-override""><code>import 'dart:async';

import 'package:quiver/testing/async.dart';
import 'package:rxdart/rxdart.dart';
import 'package:test/test.dart' as tester;

testStream&lt;MyType&gt;(
  String message, {
  Iterable expecting,
  Future&lt;void&gt; Function(BehaviorSubject) action,
  Duration waitTime,
  int skip = 1,
}) {
  tester.test(message, () {
    final _stream = BehaviorSubject&lt;MyType&gt;();
    FakeAsync().run((async) async {
      final List&lt;MyType&gt; _results = &lt;MyType&gt;[];
      final _subscription = _stream.skip(skip).listen(_results.add);
      await action?.call(_stream);

      if (waitTime != null) async.elapse(waitTime);

      _subscription.cancel();
      if (expecting != null) {
        tester.expect(_results, expecting);
      }
    });
  });
}
</code></pre>

<p>It works well on most tests I wrote, but I am having problems with a specific example due to the lack of knowledge. In the particular case I pass the action which adds a delayed future to the stream similarly like this:  </p>

<pre class=""lang-dart prettyprint-override""><code>testStream&lt;int&gt;(
  'Just a basic message',
  expecting: [1],
  action: (stream) async =&gt;
       Future.delayed(Duration(days: 99), () =&gt; stream.add(1)),
  waitTime: Duration(seconds: 1),
);
</code></pre>

<p>If I understood it right, this test should fail, however when I run it, it passes. <strong>What am I doing wrong here</strong>?</p>

<p>Then, what should I do to make it execute the action first and then elapse the timer after the action has been called without waiting for it?</p>
",https://stackoverflow.com/questions/60549440/unit-testing-with-fakeasync-in-dart,"['unit-testing', 'asynchronous', 'dart']",730,False,2,0
I am not really sure what this code does (bit manipulation),"<p>I wrote some code I am unit testing right now and for that I made the code below with the help of the internet.</p>

<pre><code>//shows changed bit
    //0010 0101 XOR 0010 0111 = 0000 0010 
    uint8_t XOR = value ^ result;

    int count;
    //count amount of 1's in XOR
    for (count = 0; XOR; XOR &gt;&gt;= 1)
    {
        count += XOR &amp; 1;
    }
</code></pre>

<p>Value is the original value, and result is the value but with ONE bit toggled. </p>

<p>I just want to make sure I understand this correctly but please correct me if I am wrong.</p>

<p>The 2nd statement in the for loop the ""XOR;"" what I think it does is run the for loop while XOR is not 0. And the XOR >>= 1 is that it sets to its self but with the 1 shifted one place to the right.</p>

<p>And the count does a +1 whenever there is a 1 on the last position ?</p>

<p>That's what I make out of it. </p>
",https://stackoverflow.com/questions/61836198/i-am-not-really-sure-what-this-code-does-bit-manipulation,"['c', 'bit-manipulation', 'bit-shift']",39,True,2,1
The NUnit 3 driver encountered an error while executing reflected code (NUnit.Engine.NUnitEngineException),"<p>I have a simple Nunit project which contains only a single test. I want to execute my code using command, so I have installed ‘Nunit-console.exe’ on my Windows 10 machine. After installation, executed the code on command prompt using below command</p>
<pre><code>nunit3-console.exe &quot;G:\LiveProjects\NUnitTestProject2\NUnitTestProject2\bin\Debug\netcoreapp3.1\NUnitTestProject2.dll&quot;
like so
</code></pre>
<p>After executing this command, I have discovered below error message:</p>
<pre><code>NUnit.Engine.NUnitEngineException : The NUnit 3 driver encountered an error while executing reflected code.
  ----&gt; System.InvalidCastException : Unable to cast transparent proxy to type 'System.Web.UI.ICallbackEventHandler'.
--NUnitEngineException
The NUnit 3 driver encountered an error while executing reflected code.
like so
</code></pre>
<p>Please refer my below code:</p>
<pre><code>[TestFixture]   
    public class Tests
    {
        [SetUp]
        public void Setup()
        {

            Console.WriteLine(&quot;Welcome setup&quot;);

        }

        [Test]
        public void Test1()
        {
          
            Console.WriteLine(&quot;Welcome first Test &quot;);
            Assert.Pass();
        }
    }
like so
</code></pre>
<p><strong>Configuration details of my project:</strong></p>
<ol>
<li><strong>Microsoft.NET Framework</strong> version 4.7.0</li>
<li><strong>OS:</strong> window 10</li>
<li><strong>IDE:</strong> Visual studio 2019</li>
<li>Use <strong>Nunit framework</strong> for unit testing</li>
<li><strong>NUnit3TestAdapter</strong> (Version) 3.16.1</li>
<li><strong>Microsoft.NET.Test.Sdk</strong> (Version) 16.5.0</li>
<li><strong>NUnit.Console</strong> (Version) 3.11.1</li>
<li><strong>Target .NET framework</strong> (Version)  3.1</li>
</ol>
<p>Also, I have tried to disable the ‘code coverage’ option in visual studio 2019, however - I am not able to see it in. Can anyone suggest - where is ‘code coverage’ option available in visual studio 2019.</p>
",https://stackoverflow.com/questions/64611083/the-nunit-3-driver-encountered-an-error-while-executing-reflected-code-nunit-en,"['c#', '.net', 'automation', 'console', 'nunit']",5120,True,6,3
Where should the Dagger TestComponent be created in an Android project? under the main folder or under the test folder?,"<p>I wanted to use Dagger2 with Unit Testing and I have found online 2 projects that have different approaches regarding how you would create a TestComponent. The first project uses the approach in which it keeps the AppComponent in <em>main</em> folder and the TestComponent in <em>test</em> folder and the TestComponent would extend the AppComponent. The second project creates both the AppComponent and the TestComponent in the <em>main</em> folder and then the DaggerTestComponent is used in the <em>test</em> folder when writing tests.</p>
<p>With the first approach, the DaggerTestComponent is created with errors as TestComponent is not recognized for some reason, but with the second approach, the DaggerTestComponent is created successfully and with no errors. My question is if you know what does Dagger recommends because I have read this page related to unit testing: <a href=""https://dagger.dev/dev-guide/testing"" rel=""nofollow noreferrer"">https://dagger.dev/dev-guide/testing</a> and I didn't understand that the TestComponent should be created in a different location (the test folder) than the AppComponent (the main folder). Maybe I am wrong.</p>
<p>This is the first project approach and the structure:
<a href=""https://i.stack.imgur.com/bFeYg.jpg"" rel=""nofollow noreferrer"">first project structure</a>
and here is the error shown after a unit test is run and the DaggerTestComponent is generated:
<a href=""https://i.stack.imgur.com/YvFTd.png"" rel=""nofollow noreferrer"">first project DaggerTestComponent</a>.
The TestComponent code looking something like this:</p>
<pre><code>@Singleton
@Component(
    modules = [
        (ApplicationModule::class),
        (RepositoryModule::class)
    ]
)
interface TestAppComponent : ApplicationComponent {
    fun into(appRepositoryTest: AppRepositoryInjectNamedTest)
    fun into(appRepositoryTest: AppRepositoryInjectTest)
    fun into(baseTest: BaseTest)
}
</code></pre>
<p>This is the second project approach and structure: <a href=""https://i.stack.imgur.com/mcpwT.jpg"" rel=""nofollow noreferrer"">second project structure</a> and the DaggerTestComponent is generated correctly: <a href=""https://i.stack.imgur.com/MedN9.png"" rel=""nofollow noreferrer"">second project DaggerTestComponent</a> but this time is not extending the AppComponent.
The second project TestComponent code looking something like this:</p>
<pre><code>@Component(
    modules = [
        DependencyModule::class,
        FragmentFactoryModule::class
    ]
)
@AppScope
interface TestComponent {

    @Component.Factory
    interface TestFactory {
        fun create(@BindsInstance app: Application): TestComponent
    }

    fun fragmentFactory() : FragmentFactory

}
</code></pre>
<p>So to state the question again: where does Dagger2 recommend that the TestComponent class should be created? in <em>main</em> folder or in <em>test</em> folder? And in case you suggest <em>test</em> folder can you also give some examples/links? Thank you.</p>
",https://stackoverflow.com/questions/62551992/where-should-the-dagger-testcomponent-be-created-in-an-android-project-under-th,"['android', 'unit-testing', 'dagger-2']",29,False,2,0
How can I mock a Promise in a test stub without using PromiseKit,"<p>I have a need to add a library to an app, the trouble is the library is using <code>PromiseKit</code>. My application does not use promises, as such I was planning on introducing an adapter to map the promise results to completion handlers.</p>

<p>What I am unsure of is, when unit testing this, I will need to create a spy, but this means being able to, or at least stub, the behaviour of a promise returning something.</p>

<p>I had considered adding PromiseKit as a dependency to my test target only, but not sure if this is the best approach as I don't actually care about <em>real</em> promises.</p>

<p>An example would be :-</p>

<pre class=""lang-swift prettyprint-override""><code>protocol OAuthAdapterType: SessionStateProviderType { }

final class OAuthAdapter: OAuthAdapterType {

  private weak var oauthProvider: OAuthProviderType?

  init(oauthProvider: OAuthProviderType?) {
    self.oauthProvider = oauthProvider
  }
}

extension OAuthAdapter: SessionStateProviderType {

  func getStatus(then completion: @escaping (Result&lt;SessionState, Error&gt;) -&gt; Void) {
    oauthProvider?.checkSession()
      .done { completion(.success(SessionStateMapper.map($0))) }
      .catch { _ in completion(.success(.signedOut)) }
  }

}

final class SessionStateMapper {
  static func map(_ status: Bool) -&gt; SessionState {
    return status ? .signedIn : .signedOut
  }
}

</code></pre>

<p>In this case, <code>checkSession</code> is a <code>Promise&lt;Bool&gt;</code>.</p>

<p>I have created a Spy would looks something like :-</p>

<pre class=""lang-swift prettyprint-override""><code>import XCTest
import PromiseKit
import OAuthKit

class OAuthProviderSpy: OAuthProviderType {
  var invokedCheckSession = false
  var invokedCheckSessionCount = 0
  var stubbedCheckSessionResult: Promise&lt;Bool&gt; = .value(false)
  func checkSession() -&gt; Promise&lt;Bool&gt; {
    invokedCheckSession = true
    invokedCheckSessionCount += 1
    return stubbedCheckSessionResult
  }
}
</code></pre>
",https://stackoverflow.com/questions/60025277/how-can-i-mock-a-promise-in-a-test-stub-without-using-promisekit,"['swift', 'promise', 'xctest', 'promisekit']",401,False,1,0
Unit testing LiveData emissions in combination with RxJava,"<p>I have been facing an issue unit testing our business logic. The problem is when I wanted to unit test all the emissions of the livedata. Right now I only get the last emitted value but I wanted to unit test all the values that get emitted one by one.</p>

<p>Here is my rough setup.</p>

<p>Here is how my viewModel <code>onSaveEvent</code> click event looks like</p>

<pre><code>        disposable.add(finalSource
        .observeOn(schedulerProvider.ui())
            .doOnSubscribe {
                // show spinner
                _myLiveData.value = Loading(toShow = true, loadingMessage = ""Loading"")
            }
            .doAfterTerminate {
                // remove spinner
                _myLiveData.value = Loading(toShow = false)

            }
            .subscribe { resource -&gt;
                // Update either on success or error.
                _myLiveData.value = resource
        }
    )
</code></pre>

<p>My view model test looks something like this.</p>

<pre><code>@Test
fun testOnSaveEvent() {
    // Other setup code.
    Mockito.`when`(myRepo.onSave()).thenReturn(mockSingle)
    myViewModel.onSaveEvent(salesTaxCompanyInfo)

    testScheduleProvider.ui().triggerActions()

    // I see that the value is of type Loading
    val firstValue = myViewModel.myLiveData.getOrAwaitValue()

    // The next value is also Loading, although I would like to see the success event.
    val secondValue = myViewModel.myLiveData.getOrAwaitValue()
}
</code></pre>

<p>Ideally, I am looking for something on the lines <code>TestCoroutineDispatcher</code> listed here: <a href=""https://medium.com/androiddevelopers/testing-two-consecutive-livedata-emissions-in-coroutines-5680b693cbf8"" rel=""nofollow noreferrer"">https://medium.com/androiddevelopers/testing-two-consecutive-livedata-emissions-in-coroutines-5680b693cbf8</a></p>

<p>While I understand that LiveData only holds the last value it receives I wanted to know if there is any we can unit test the emissions one by one.</p>
",https://stackoverflow.com/questions/62105549/unit-testing-livedata-emissions-in-combination-with-rxjava,"['android', 'unit-testing', 'mvvm', 'rx-java', 'viewmodel']",242,False,1,0
Is it possible to compare two Func&lt;&gt; variables (not expressions) in C#?,"<p>It seems it is possible to compare two delegates in C# for equality, but I cannot figure out if one can compare two variables of type <code>Func&lt;&gt;</code></p>

<pre><code>Func&lt;Task&lt;Foo&gt;&gt; a = () =&gt; _service.GetFoo();
Func&lt;Task&lt;Foo&gt;&gt; b = () =&gt; _service.GetFoo();
</code></pre>

<p>Is it possible to do some comparison of these?</p>

<p>P.S. I need this for unit testing, I do pass a delegate like that to another method and I'd like to test that this is what is being passed (not <code>_service.GetBar()</code> that is). I have now solved this by calling the delegate and comparing the result, but I'd rather compare it directly if it is possible.</p>

<p>P.P.S. This is not duplicate even though people made it look like that. The other question is about expressions and it's a completely special thing in C# that is not an ordinary delegate.</p>
",https://stackoverflow.com/questions/61674164/is-it-possible-to-compare-two-func-variables-not-expressions-in-c,"['c#', 'unit-testing', 'delegates', 'comparison', 'func']",438,False,1,0
How to get nUnit unit tests to work with Xamarin.Forms in Azure pipelines?,"<p>I'm trying to get nUnit unit tests working with Xamarin.Forms. Everything works fine on my machine, but when I push to Azure and it goes into the build pipeline, I get the following error :</p>

<p><code>The current .NET SDK does not support targeting .NET Core 3.1.  Either target .NET Core 2.2 or lower, or use a version of the .NET SDK that supports .NET Core 3.1 [/Users/runner/runners/2.164.6/work/1/s/TestProject1/TestProject1.csproj</code>  </p>

<p>When I remove the unit test project, the build is successful. I think the problem has something to do with the fact that Xamarin.Forms uses .Net Standard, while my unit test project is using .NET Core. How do I reconcile this? Specific advice or a pointer to a tutorial that goes over unit testing with Xamarin.Forms on Azure would be greatly appreciated. I'm really new to playing around with devops, so some kind of training track would be nice.</p>

<p>Also, here is my Azure Pipeline YAML file :</p>

<pre><code>    pool:
      vmImage: 'macOS 10.13'

    steps:
      # To manually select a Xamarin SDK version on the Hosted macOS agent, enable this script with the SDK version you want to target
      # https://go.microsoft.com/fwlink/?linkid=871629
      - script: sudo $AGENT_HOMEDIRECTORY/scripts/select-xamarin-sdk.sh 5_4_1
        displayName: 'Select Xamarin SDK version'
        enabled: false

      - task: NuGetToolInstaller@0

      - task: NuGetCommand@2
        inputs:
          restoreSolution: '**/*.sln'

      - task: XamariniOS@2
        inputs:
          solutionFile: '**/*.sln'
          configuration: 'Release'
          buildForSimulator: true
          packageApp: false 

</code></pre>

<p>Thanks!</p>
",https://stackoverflow.com/questions/59975677/how-to-get-nunit-unit-tests-to-work-with-xamarin-forms-in-azure-pipelines,"['azure', 'unit-testing', 'xamarin.forms', 'azure-devops', 'devops']",476,True,1,1
akka http mock (authorization) directive,"<p>I'm trying to write unit testing to an akka-http server (route), but having trouble with the authorization directive. 
I simply want to ignore (mock) the authorization directive.</p>

<p>A minimal version of my code:</p>

<pre><code>object App {

    val logger: Logger = Logger[App]

    def main(args: Array[String]): Unit = {
        implicit val system: ActorSystem = ActorSystem(""my-system"")
        implicit val executionContext: ExecutionContextExecutor = system.dispatcher

        val service = new TestRoute()
        val bindingFuture = Http().bindAndHandle(service.route, ""0.0.0.0"", 8080)

        bindingFuture.onComplete {
            case Success(_) =&gt; println(s""listening on localhost:8080"")
            case Failure(error) =&gt; println(s""failed: ${error.getMessage}"")
        }
    }


    object TestRoute {

        def authorize: Directive1[JsObject] = extractCredentials.flatMap {
            case Some(OAuth2BearerToken(token)) =&gt; verifyToken(token) match {
                case Success(t) =&gt;
                    logger.debug(""token verified successfully"")
                    provide(t)
                case Failure(t) =&gt;
                    logger.warn(s""token is not valid: ${t.getMessage}"")
                    reject(Rejections.validationRejection(t.getMessage))
            }
            case _ =&gt;
                logger.warn(""no token present in request"")
                reject(AuthorizationFailedRejection)
        }


        def verifyToken(token: String): Try[JsObject] = {
            val source = Source.fromResource(""public_production.pem"")
            val fileData = try source.mkString finally source.close()
            JwtSprayJson.decodeJson(token, fileData, Seq(JwtAlgorithm.RS256))
        }
    }

    class TestRoute {
        val route: Route =
            TestRoute.authorize { jwtClaims =&gt;
                println(jwtClaims)
                complete(""sucess"")
            } 
    }
}
</code></pre>

<p>I want to test the Route in <code>TestRoute</code>. So <code>authorize</code> is the directive I want to mock. I simply want to control what <code>authorize</code> will return, without having to actually getting in the function.</p>

<p>My colleague suggested to wrap the Route in some kind of class that will take the <code>authorize</code> method as an argument, such that in the unit-test I can control it very easily. But I'm looking for the mock answer.</p>

<p>I saw some examples with Mockito, but none of them were compatible with my scalatest version, which is <code>3.1.0</code>.</p>
",https://stackoverflow.com/questions/60728743/akka-http-mock-authorization-directive,"['scala', 'unit-testing', 'mocking', 'akka', 'akka-http']",269,False,1,0
How to write unit test case for a method [Angular],"<p>I'm a beginner in Angular. I'm trying hard to learn Typescript and now I've been told to write unit test cases in Jasmine and Karma for every <code>component</code> and <code>service</code> I create. I've watched many tutorials to learn <em>Unit testing in Angular</em>. I'm an intern, yesterday I raised a Pull request on which my tech lead has given the following comment.</p>

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

<p>Here is the code that I've written.</p>

<p><strong>filter-bar.component.ts</strong></p>

<pre><code>import { Component, OnInit, ViewChild, OnDestroy, Input, ChangeDetectorRef } from '@angular/core';
import './filter-bar.component.scss';
import { SisenseService } from '../services/sinsense.service';
import { SisenseConfigService } from '../services/sinsense-config.service';
import { Dashboard, Widget } from 'src/app/shared/models/sisenseConfig';
...

@Component({
    selector: 'app-filter-bar',
    templateUrl: './filter-bar.component.html'
})
export class FilterBarComponent implements OnInit, OnDestroy {
  selectedMembersCount: number;
  dataUnavailable: boolean;

  constructor(
    public sisenseService: SisenseService,
    public sisenseConfigService: SisenseConfigService
  ) {}

  ngOnInit() {
    this.getDataFromWidget();
  }

  getDataFromWidget() {
    this.sisenseService.getWidgetData(
    this.sisenseConfigService.getDashboardId(Dashboard.POPULATION),
    this.sisenseConfigService.getWidgetInfo(Dashboard.POPULATION, Widget.UNIQUE_LIVES).id,
      widgetData =&gt; {
        this.selectedMembersCount = widgetData.queryResult.value.data;
        this.changeDetector.detectChanges();
      },
      () =&gt; {
        this.dataUnavailable = true;
      }
    );
  }
}
</code></pre>

<p>And this is the spec file that I've written:</p>

<p><strong>filter-bar.component.spec.ts</strong></p>

<pre><code>import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBarComponent } from './filter-bar.component';
import { SisenseFilterService } from '../services/sinsense-filter.service';
import { PopUpService } from '@wuitk6/angular/components/popup/popup.service';
import { SisenseService } from '../services/sinsense.service';
import { SisenseConfigService } from '../services/sinsense-config.service';

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

    mockSisenseConfigService.getWidgetInfo.and.returnValue({ id: 'demo_ID' });

        fixture = TestBed.createComponent(FilterBarComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
});
</code></pre>

<p>And here's the service, (i don't know who has written this code):</p>

<p><strong>sisense-config.service.ts</strong></p>

<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/do';
...
import { ErrorService } from './error.service';

// This is to avoid compile errors in typescript.
// The real variable will be added when sisense.js is loaded
declare var Sisense: any;

@Injectable({
    providedIn: 'root'
})
export class SisenseConfigService {
  constructor(private http: HttpClient, private errorService: ErrorService) {}

  getDashboardId(dashboardName: string): string {
    ...
  }

  getWidgetInfo(dashboardName: string, widgetName: string): ISisenseWidget {
   ...
   return widgetInfo;
  }
}
</code></pre>

<p>I've written the test file but She is not OK with it. Please help me what exactly my tech lead is asking for. Feel free to ask for more code details.</p>
",https://stackoverflow.com/questions/60751588/how-to-write-unit-test-case-for-a-method-angular,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'angular-test']",12373,True,1,1
Unable to generate code coverage report using ReportGenerator,"<p>I have created a build pipeline in Azure DevOps for one of my ASP.NET MVC application. There exist projects for unit testing, and I need to generate code coverage report, for which I have used coverlet.msbuild NuGet package, and ""ReportGenerator"". </p>

<p>Following is the packages.config file of one of the unit test project:</p>

<pre><code>&lt;packages&gt;
  &lt;package id=""coverlet.msbuild"" version=""2.8.0"" targetFramework=""net461"" developmentDependency=""true"" /&gt;
  &lt;package id=""NUnit"" version=""2.6.3"" targetFramework=""net45"" /&gt;
  &lt;package id=""ReportGenerator"" version=""4.4.6"" targetFramework=""net461"" /&gt;
&lt;/packages&gt;
</code></pre>

<p>Also, please find the yaml of Build solution, test assemblies, and ReportGenerator tasks in build pipeline:</p>

<p><strong>Build Solution:</strong></p>

<pre><code>steps:
- task: VSBuild@1
  displayName: 'Build solution **\SmartStoreNET.sln'
  inputs:
    solution: '**\SmartStoreNET.sln'
    msbuildArgs: '/p:CollectCoverage=true /p:CoverletOutputFormat=cobertura'
</code></pre>

<p><strong>Test Assemblies</strong></p>

<pre><code>steps:
- task: VSTest@2
  displayName: 'Test Assemblies'
  inputs:
    testAssemblyVer2: |
     **\$(BuildConfiguration)\*test*.dll
     !**\obj\**
    codeCoverageEnabled: true
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'
</code></pre>

<p><strong>ReportGenerator</strong></p>

<pre><code>steps:
- task: Palmmedia.reportgenerator.reportgenerator-build-release-task.reportgenerator@4
  displayName: ReportGenerator
  inputs:
    reports: '$(Build.SourcesDirectory)/tests/**/coverage.cobertura.xml'
    targetdir: '$(Build.SourcesDirectory)/CodeCoverage'
    reporttypes: 'HtmlInline_AzurePipelines;Cobertura;Badges'
</code></pre>

<p>While executing the pipeline I am getting following error in ReportGenerator task:</p>

<blockquote>
  <p>The report file pattern 'd:\a\1\s/tests/**/coverage.cobertura.xml' is invalid. No matching files found.</p>
</blockquote>

<p>Can anyone please suggest what is missing here, or what could be the potential issue.</p>

<p>Any help on this would be much appreciated.</p>

<p>Thanks,</p>

<p>Nirman</p>
",https://stackoverflow.com/questions/60058931/unable-to-generate-code-coverage-report-using-reportgenerator,"['nunit', 'code-coverage', 'azure-pipelines', 'cobertura', 'reportgenerator']",7439,True,1,1
unit testing firebase HttpsFunctions,"<p>I am using firebase https function and am running unit tests on them. When calling the https function to be tested, the firebase documentation suggest to simply call it within my test file like this:</p>

<p><code>toBeTestesFunction()</code></p>

<p>This is my firebase https function:</p>

<p><code>export const toBeTestedFunction = https.onRequest(async (req, resp) =&gt; {
      bla bla bla
}</code></p>

<p>Now my problem is that onRequest takes a callback which in my case is asynchronous and needs to be awaited. However onRequest return the type HttpsFunction which is of type:</p>

<p><code>TriggerAnnotated &amp; ((req: Request, resp: Response) =&gt; void);</code></p>

<p>Since it does not return a promise I cannot await it. This makes the content in the function which has a callback that is asynchronous untestable. In the firebase documentation they give an exmaple which seems flawed (<a href=""https://firebase.google.com/docs/functions/unit-testing?authuser=0#test-background"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing?authuser=0#test-background</a>).</p>

<p>Any help is much appreciated
Thanks</p>
",https://stackoverflow.com/questions/60873541/unit-testing-firebase-httpsfunctions,"['firebase', 'unit-testing', 'google-cloud-functions']",68,False,1,0
can somebody explain the sequence of start to end of data stages in databricks in MS Azure,"<p>I am learning Databricks in MS azure and have been given 4 steps to complete a task:</p>
<ol>
<li>Upload a csv file (identify the relevant dataset yourself) into dbfs</li>
<li>Perform some of the basics transformational activities on the data set</li>
<li>Finally save the output Into The Delta tables of the data bricks</li>
<li>Once the delta table is created implemented unit testing (with certain test cases like count column profiling pytest can used for any other module) in databricks</li>
</ol>
<p>I did first step but then for second step i was told to create a dataframe and do sql activity through delta table which I was not aware of. Can somebody share the sequence of what needs to be done while working on databricks</p>
",https://stackoverflow.com/questions/63052832/can-somebody-explain-the-sequence-of-start-to-end-of-data-stages-in-databricks-i,"['azure', 'cloud', 'databricks', 'azure-databricks']",258,False,1,1
Jest enzyme mock function not working with toHaveBeenCalled and mock.calls.length,"<p>I am learning react unit testing, I wrote simple test case but its not working, I googled a lot and everywhere I see same example and that's not working for me. I tried both ways toHaveBeenCalled/mock.calls.length.</p>
<p>Counter is getting increased, I know i can check/test counter value to find out if button is clicked, But what If there isn't any counter and I just want to make sure that button click triggers a function ?</p>
<p>I know if i move this function to some other file and then import it then below test will pas since I am passing that function as prop. But what if i want to test a function which is not imported and in the same file ?</p>
<p><a href=""https://codesandbox.io/s/gallant-dhawan-d6vvl"" rel=""nofollow noreferrer"">Sandbox Demo</a></p>
<pre><code>import React from &quot;react&quot;;
import &quot;./Login.css&quot;;

class Login extends React.Component {
  state = {
    counter: 0
  };

  doLogin = (event) =&gt; {
    let { counter } = this.state;
    this.setState((prevstate) =&gt; ({ counter: prevstate.counter + 1 }));
    // console.log(&quot;Handle login button click&quot;);
  };

  render() {
    const { counter } = this.state;
    return (
      &lt;table width=&quot;100%&quot; border=&quot;0&quot; cellPadding={4}&gt;
        &lt;tr&gt;
          &lt;td&gt;
            &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;Username&quot; /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;
            &lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;Password&quot; /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;
            &lt;button onClick={this.doLogin}&gt;LogIn&lt;/button&gt;
            &amp;nbsp;&amp;nbsp;{counter}
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    );
  }
}

export default Login;
</code></pre>
<p>Test case</p>
<pre><code>it(&quot;Handle login button click&quot;, () =&gt; {
  const mockOnClick = jest.fn();

  const wrapper = shallow(&lt;Login onClick={mockOnClick} /&gt;);
  wrapper.find(&quot;button&quot;).simulate(&quot;click&quot;);
  wrapper.find(&quot;button&quot;).simulate(&quot;click&quot;);
  // mockOnClick();
  console.log(wrapper.state(&quot;counter&quot;));
  // expect(mockOnClick).toHaveBeenCalled();
  expect(mockOnClick.mock.calls.length).toEqual(2);
});
</code></pre>
",https://stackoverflow.com/questions/63878328/jest-enzyme-mock-function-not-working-with-tohavebeencalled-and-mock-calls-lengt,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",1038,True,0,1
Bespoken Code Coverage for self-hosted Alexa Skill written in Python (Flask),"<p>I am working on an Alexa Skill written in Python using the ask-sdk for Python. This skill is running self-hosted on a Flask server listening to port 5000.
Now i would like to integrate Unit-Tests using the Bespoken Framework.</p>
<p>My testing.json file looks like this:</p>
<pre><code>{

    &quot;locales&quot;: &quot;de-DE&quot;,
    &quot;interactionModel&quot;: &quot;models/de-DE.json&quot;,
    &quot;trace&quot;: true,
    &quot;jest&quot;: {
        &quot;silent&quot;: true
    },
    &quot;skillURL&quot;: &quot;http://localhost:5000&quot;
}
</code></pre>
<p>i am locally running an http.server on port 9998 to get the report.html.
The tests passed successfully, but the code coverage is not working correctly. It seems like the files used in this skills are not recognized at all. Instead they are looking up the files slides.js, debugger.js, jquery.js</p>
<pre><code>-----------------------------------------|----------|----------|
File                                     |  % Stmts | % Branch | 
-----------------------------------------|----------|----------|
All files                                |        0 |        0 | 
 docutils/writers/s5_html/themes/default |        0 |        0 | 
  slides.js                              |        0 |        0 |     ...
 werkzeug/debug/shared                   |        0 |        0 | 
  debugger.js                            |        0 |        0 | 
  jquery.js                              |        0 |        0 |
-----------------------------------------|----------|----------|

Test Suites: 1 passed, 1 total
Tests:       11 passed, 11 total
Snapshots:   0 total
Time:        9.475s
</code></pre>
<p>I followed this guide <a href=""https://read.bespoken.io/cli/tutorials/tutorial-flask-ask-python/#getting-started"" rel=""nofollow noreferrer"">https://read.bespoken.io/cli/tutorials/tutorial-flask-ask-python/#getting-started</a>.</p>
<p>Therefore I looked up the FAQ and got this information from <a href=""https://read.bespoken.io/unit-testing/faq/#what-are-continuous-integration-ci-and-automated-unit-testing"" rel=""nofollow noreferrer"">https://read.bespoken.io/unit-testing/faq/#what-are-continuous-integration-ci-and-automated-unit-testing</a>:</p>
<hr />
<p><strong>Can I unit-test skills written in programming languages other than Javascript?</strong>
Yes, you can. It does require having a server running locally on your laptop that our library can call, but otherwise it will &quot;just work&quot;.</p>
<p>Before the test is run, start the server to receive payloads. It will be listening on something like: http://localhost:9000.</p>
<p>Set that URL in the skillURL configuration element in the testing.json file. This should be set instead of the handler element - the handler only works with Javascript lambdas/functions.</p>
<p>After tests are run, shut the server down - we recommend doing this as part of a regular process. It can be added to one of our filters, for example - read about filters here XXX.
Finally, if you have request signature checking or timestamp filtering being performed on the requests, you will need to disable this.</p>
<hr />
<p>This is my app.py:</p>
<pre><code>
SB = SkillBuilder()
app = Flask(__name__)

app.config.setdefault(VERIFY_SIGNATURE_APP_CONFIG, False)
id = &quot;XXXX&quot;
skill_obj = SB.create()


webservice_handler = WebserviceSkillHandler(skill=skill_obj)
webservice_handler.verify_signture = False


skill_adapter = SkillAdapter(skill=skill_obj, skill_id=id, app=app)

skill_adapter.VERIFY_SIGNATURE_APP_CONFIG = False

skill_adapter.register(app=app, route=&quot;/&quot;)



if __name__ == '__main__':

    if 'ASK_VERIFY_REQUESTS' in os.environ:
        verify = str(os.environ.get('ASK_VERIFY_REQUESTS', '')).lower()
        if verify == 'false':
            app.config['ASK_VERIFY_REQUESTS'] = False
    app.run(host='0.0.0.0', port=5000, debug=True)

</code></pre>
<p>I am thankful for any idea!</p>
",https://stackoverflow.com/questions/62773772/bespoken-code-coverage-for-self-hosted-alexa-skill-written-in-python-flask,"['python', 'unit-testing', 'flask', 'alexa', 'ask-sdk']",152,True,1,1
Could not create SSL/TLS secure channel while calling pages within the site,"<p>I am working on a web call that is supposed to do some checking on WSDL pages within the same site. I thought this would be simple. It works fine until we add in the certificate call and then the SSL breaks</p>
<pre><code>        var httpClientHandler = new HttpClientHandler
        {
            SslProtocols = SslProtocols.Tls12,
            ServerCertificateCustomValidationCallback = (message, certificate2, chain, errors) =&gt; { return true; }
        };

        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection collection = store.Certificates.Find(X509FindType.FindBySubjectName, &quot;fakename.com&quot;, false);
        httpClientHandler.ClientCertificates.AddRange(collection);

        HttpClient client = new HttpClient(httpClientHandler);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        HttpResponseMessage resp = client.GetAsync(uri, HttpCompletionOption.ResponseContentRead, token).Result;
</code></pre>
<ol>
<li>the user clicks the healthcheck link</li>
<li>I construct a full uri for the WSDL.</li>
<li>the code above runs and I read the respnse.</li>
</ol>
<p>Unit testing shows this working fine, the difference is that I am making the call outside of the site, from that I can deduce that the certificate does get added, and a call is possible.</p>
<p>Has anyone else seen this happen? Is there some rule I need to observe in order to call a page from within my own site behind SSL?</p>
",https://stackoverflow.com/questions/63586770/could-not-create-ssl-tls-secure-channel-while-calling-pages-within-the-site,"['c#', 'wcf']",84,True,0,1
Is it possible to resolve the `StatusCode` of the `ObjectResult` base of the run-time derived class T value?,"<p>Some context:</p>
<p>I'm unit testing a simple <code>MyController</code>, for each of the test I'm asserting that the http response object is a specific type of <code>Microsoft.AspNetCore.Mvc.ObjectResult</code> base class or any of its derived classes like <code>BadRequestObjectResult</code> or <code>OkObjectResult</code>.</p>
<pre><code>MyController : BaseController
{
    public void IActionResult&gt; Get(...)
    {
        try
        {
            if (...) retrun BadRequest(...)

            return Ok(...);
        }
        catch (Exception ex)
        {
            return StatusCode(500, ...);
        }
    }
</code></pre>
<p>For example, at the end of each unit test I'm asserting the actual return type is of <code>ObjectResult</code> with <code>HttpCode</code> of 500 or for the second unit test's return type is of <code>BadRequestObjectResult</code> with <code>HttpCode</code> of 400:</p>
<pre><code>[Test]
public void ControllerTest_WhenFail_ShouldRetrunInternalServerError()
{
    ...
    IActionResult actual = controller.Get(...);
    //Assert
    AssertHttpCode&lt;ObjectResult&gt;(actual, 500);
}

public void ControllerTest_WhenRequestNotValid_ShouldRetrunBadRequest()
{
    ...
    IActionResult actual = controller.Get(...);
    //Assert
    AssertHttpCode&lt;BadRequestObjectResult&gt;(actual, 400);
}
</code></pre>
<p>Here is the Assert Function for the type casting and asserting the <code>StatusCode</code>:</p>
<pre><code>private void AssertHttpCode&lt;T&gt;(IActionResult actual, int httpCode) where T : ObjectResult
{
    Assert.IsNotNull(actual);
    T objectResult = actual as T;
    Assert.AreEqual(objectResult.StatusCode, httpCode);
}
</code></pre>
<p>My Question:</p>
<p>Instead of sending the <code>httpCode</code> as a parameter from each of the unit tests, <strong>I wonder if it is possible to resolve the <code>StatusCode</code> of the <code>ObjectResult</code> base of the run-time T value?</strong> so the clients of <code>AssertHttpCode</code> function, won't need to send the <code>httpCode</code> as a parameter, like:</p>
<pre><code>public void ControllerTest_WhenRequestNotValid_ShouldRetrunBadRequest()
{
    ...
    IActionResult actual = controller.Get(...);
    //Assert
    AssertHttpCode&lt;BadRequestObjectResult&gt;(actual); //no 400 here, it is obvious!
}

private void AssertHttpCode&lt;T&gt;(IActionResult actual) where T : ObjectResult
{
    Assert.IsNotNull(actual);
    T objectResult = actual as T;
    Assert.AreEqual(objectResult.StatusCode, **resolved_http_Code_from_T**);
}
</code></pre>
",https://stackoverflow.com/questions/63605004/is-it-possible-to-resolve-the-statuscode-of-the-objectresult-base-of-the-run,"['c#', 'unit-testing', 'generics', 'asp.net-core-webapi']",2419,True,0,3
"Run unit test with Jest, Vue, Vuetify, and Pug","<p>I am currently working on a project that is using Vue, Class based components, typescript, pug, vuetify and Jest for unit testing. I have been trying to run unit tests using jest and have not been able to get them to work. At this point I am pretty lost as to what could be wrong. It seems that there are issues with unit tests when using vueifty which I think I have sorted out but am not certain. When I run the test the test fails because the wrapper is always empty.</p>
<h2>Component</h2>
<pre><code>&lt;template lang=&quot;pug&quot;&gt;
    v-row(align=&quot;center&quot; justify=&quot;center&quot;)
        v-col(cols=&quot;6&quot;)
            v-card
                v-form(ref=&quot;loginForm&quot; v-model=&quot;valid&quot; v-on:keyup.enter.native=&quot;login&quot;)
                    v-card-title#title Login
                    v-card-text
                        v-text-field(class=&quot;mt-4&quot; label=&quot;Username&quot; required outlined v-model=&quot;username&quot; :rules=&quot;[() =&gt; !!username || 'Username Required.']&quot;)
                        v-text-field(label=&quot;Password&quot; required outlined password :type=&quot;show ? 'text' : 'password'&quot; :append-icon=&quot;show ? 'visibility' : 'visibility_off'&quot; @click:append=&quot;show = !show&quot; v-model=&quot;password&quot; :rules=&quot;[() =&gt; !!password || 'Password Required.']&quot;)
                    v-alert(v-if=&quot;error&quot; v-model=&quot;error&quot; type=&quot;error&quot; dense dismissible class=&quot;mx-4&quot;)
                        | Error while logging in: {{ errorMsg }}

                    v-card-actions()
                        div(class=&quot;flex-grow-1&quot;)    
                        v-btn(class=&quot;mr-4&quot; color=&quot;teal&quot; :disabled=&quot;!valid&quot; large depressed @click=&quot;login&quot;) Login

                div Forgot password?
                    a(href=&quot;/forgot-password&quot; class=&quot;mx-2&quot;) Click here

                div(class=&quot;my-2&quot;) Don't have an account?
                    a(href=&quot;/signup&quot; class=&quot;mx-2&quot;) Signup
                    | for one
&lt;/template&gt;

&lt;script lang=&quot;ts&quot;&gt;
import { AxiosError, AxiosResponse } from 'axios';
import JwtDecode from 'jwt-decode';
import { Component, Vue } from 'vue-property-decorator';

import { TokenDto, VForm } from '@/interfaces/GlobalTypes';

@Component({
    name: 'LoginForm',
})
export default class Login extends Vue {
    private password: string = '';
    private username: string = '';
    private show: boolean = false;
    private error: boolean = false;
    private errorMsg: string = '';

    private valid: boolean = false;

    ... removed rest for brevity
</code></pre>
<h2>Test</h2>
<pre><code>import LoginForm from '@/components/auth/LoginForm.vue';
import login from '@/views/auth/LoginView.vue';
import { createLocalVue, mount } from '@vue/test-utils';
import Vue from 'vue';
import Vuetify from 'vuetify';
// jest.mock('axios')

Vue.use(Vuetify)
const localVue = createLocalVue();
console.log(localVue)


describe('LoginForm.vue', () =&gt; {
    let vuetify: any
  beforeEach(() =&gt; {
    vuetify = new Vuetify()

  });

  it('should log in successfully', () =&gt; {
      const wrapper = mount(LoginForm, {
          localVue,
          vuetify
      })
      console.log(wrapper.find('.v-btn'))
  });
});
</code></pre>
<p>The LoginForm is loaded properly but it does not seeem that that mount creates the wrapper for some reason. When I log the wrapper I get:</p>
<pre><code>    VueWrapper {
      isFunctionalComponent: undefined,
      _emitted: [Object: null prototype] {},
      _emittedByOrder: []
    }
</code></pre>
<p>Any ideas are greatly appericated</p>
",https://stackoverflow.com/questions/61282798/run-unit-test-with-jest-vue-vuetify-and-pug,"['unit-testing', 'vue.js', 'jestjs', 'vuetify.js', 'vue-test-utils']",1660,False,0,2
X509Certificate2 for unit tests,"<p>I'm currently unit testing .NET application with NUnit framework.</p>
<p>Some of the methods we use involve getting X509Certificate2 object as input and checking if one or more properties match certain crateria.</p>
<p>For example, method that check whether the thumbprint exists in a very specific list.</p>
<p>Thus, I need a way to mock or fake the X509Certificate2 object so that I can control what the thumbprint field will return or what are the extentions list will contain.</p>
<p>One way I can approach this is to create the special certificates and use them as resources in the tests project (hard coded or embedded resource).</p>
<p>I'm searching for a different solution, if it's even possible.</p>
<p>And suggestions will be greatly appreciated!
Thanks in advance :)</p>
",https://stackoverflow.com/questions/63660547/x509certificate2-for-unit-tests,"['c#', 'unit-testing', 'nunit', 'x509certificate', 'x509certificate2']",1320,True,-1,1
C++ Unit testing - using hardcoded or generated array,"<p>Let's say I'writing c++ driver for controlling some device on the serial bus. This is simplified version of the problem.
I have class <code>DeviceDriver</code> that have <code>std::vector&lt;unsigned char&gt; transmitFrames(int deviceNumber)</code> method. It returns two significant bytes followed by constant number of zero values. The pattern is:</p>

<p><code>transmitFrames(0)</code> should return <code>{0xFF, 0xFF}</code>,
<code>transmitFrames(1)</code> should return <code>{0xFF, 0xFF, 0x00, 0x00}</code>,
<code>transmitFrames(2)</code> should return <code>{0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00}</code>...</p>

<p>When testing this method should I use hardcoded expected arrays or should I generate it somewhere?
Hardcoded version it's nearly impossible to write because <code>transmitFrames(100)</code> will return the vector of many values. Generated version would be okay but what about algorithm? It will be the same as in the class. This would break DRY rule and of course testing algorithm would have still bug. I'm using googletest framework. How to deal with problems like long arrays in unit testing?</p>
",https://stackoverflow.com/questions/61596302/c-unit-testing-using-hardcoded-or-generated-array,"['c++', 'unit-testing', 'googletest', 'googlemock']",172,False,0,0
How we use TestBed for components with NativeScript?,"<p>I'm writing an app with NativeScript 6+ and Angular 8+. I'm trying to write some unit tests and get them up and running. I have read the documentation on unit testing: <a href=""https://docs.nativescript.org/tooling/testing/testing"" rel=""nofollow noreferrer"">https://docs.nativescript.org/tooling/testing/testing</a> I've got some unit tests up and running with plain components. e.g.</p>

<pre><code>import { ItemsComponent } from ""~/app/item/items.component"";
import { ItemService } from ""~/app/item/item.service"";

describe('Items Component Standard Test', () =&gt; {

    let  component: ItemsComponent;

    beforeEach(() =&gt; {
        component = new ItemsComponent(new ItemService());
    });

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

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

<p>I see that we can test Components with dependencies by instantiating them in the constructors and with mock services as well. <a href=""https://angular.io/guide/testing#service-tests"" rel=""nofollow noreferrer"">https://angular.io/guide/testing#service-tests</a></p>

<p>I tried to follow the tutorial on this web page but I keep getting an error:</p>

<p>sample code &amp; repository:</p>

<p><a href=""https://github.com/aquinn637/Fresh"" rel=""nofollow noreferrer"">https://github.com/aquinn637/Fresh</a></p>

<pre><code>import { ItemsComponent } from ""~/app/item/items.component"";
import { ItemService } from ""~/app/item/item.service"";
import { nsTestBedBeforeEach, nsTestBedAfterEach, nsTestBedRender } from ""nativescript-angular/testing"";

describe('Renderer E2E', () =&gt; {

    beforeEach(nsTestBedBeforeEach([ItemsComponent], [ItemService]));
    afterEach(nsTestBedAfterEach(false));

    it('should be defined',  () =&gt; {

        nsTestBedRender(ItemsComponent).then((fixture) =&gt; {
            expect(fixture.componentInstance).toBeTruthy();
        });

    });
</code></pre>

<p>Error:</p>

<pre><code>CONSOLE WARN file:///node_modules/@nativescript/angular/testing/src/util.js:171:0: nsTestBedRender called without nsTestBedBeforeEach/nsTestBedAfter each. You are responsible for calling 'fixture.destroy()' when your test is done in order to clean up the components that are created.

CONSOLE ERROR file:///app/vendor.js:85281:30: Unhandled Promise rejection: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out ; Zone: ProxyZone ; Task: Promise.then ; Value: Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out ZoneAwareError(file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:1298:0)

at

at expect

at

at file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:138:0

at file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:883:0

at file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:188:0

at drainMicroTaskQueue(file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:595:0)

at file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:500:0

at timer(file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:1561:0)

at invoke(file:///node_modules/@nativescript/core/timer/timer.js:54:30)

at file:///node_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:151:0

at file:///node_modules/@nativescript/core/timer/timer.js:18:0

at UIApplicationMain([native code])

at run(file:///node_modules/@nativescript/core/application/application.js:312:0)

at ../node_modules/nativescript-unit-test-runner/app/bundle-app.js(file:///node_modules/nativescript-unit-test-runner/app/bundle-app.js:3:0)

at __webpack_require__(file:///src/webpack/bootstrap:74:0)

at file:///src/main.ts:11:16

at ./main.ts&lt;…&gt;

19 03 2020 12:01:11.660:WARN [NativeScript / 13.3 (13.3; iPad)]: Disconnected (0NativeScript / 13.3 (13.3; iPad) ERROR

  DisconnectedClient disconnected from CONNECTED state (transport error)

NativeScript / 13.3 (13.3; iPad): Executed 4 of 4 SUCCESS (0.161 secs / 0.099 secs)
</code></pre>

<p>Is it possible to use TestBed for our components in NativeScript? If so, can you provide an eample of how to do that?</p>
",https://stackoverflow.com/questions/60757582/how-we-use-testbed-for-components-with-nativescript,"['angular', 'unit-testing', 'nativescript', 'karma-jasmine']",233,True,0,1
mocking process.exit in a jasmine test,"<p>My business logic has a condition where if a certain condition is true, the process exits. This is correct for business logic, but unit testing this scenario is an issue because when I mock the value of the condition, the test process itself exits, and thus I get errors printed at the end since none of the expectations were actually completed. How can I mock the functionality of process.exit in jasmine, without actually exiting the process?</p>
<p>To make the problem clearer, here is some example code:</p>
<pre><code>// Unit tests:

it('kills process when condition is false', async (done: DoneFn) =&gt; {
     let conditionSpy1 = spyOn(conditionApi, 'getConditionValue').and.returnValues(true, true, ..., false);
     let apiSpy1 = spyOn(api, 'method1').and....
     let apiSpy2 = spyOn(api2, 'method2').and...
     await myFunction();
     expect(api.method1).toHaveBeenCalled();
     expect(api2.method2).not.toHaveBeenCalled();
     done();
});
</code></pre>
<pre><code>// business logic
async function myFunction() {

     const results = api.method1();
     for (const document of results) {
         const continueProcess = conditionApi.getConditionValue();
         if (!continueProcess) {
             console.log('received quit message. exiting job...');
             process.exit(0);
         }
         doStuff(document);
     }
     api2.method2();
}
</code></pre>
<p>I want to return from the myFunction() call and go back to the unit test so that the expectations continue, but because of the process.exit(0) call, the test cuts off completely.</p>
<p>How can I get around this?</p>
",https://stackoverflow.com/questions/63714757/mocking-process-exit-in-a-jasmine-test,"['node.js', 'jasmine', 'jasmine-node']",1122,True,0,1
NativeScript - how to get unit tests to work properly?,"<p>I'm writing an app with NativeScript 6+ and Angular 8+.</p>

<p>I'm trying to write some unit tests and get them up and running. </p>

<p>I have read the documentation on unit testing:
<a href=""https://docs.nativescript.org/tooling/testing/testing"" rel=""nofollow noreferrer"">https://docs.nativescript.org/tooling/testing/testing</a></p>

<p>I followed the directions there for setting up the tests and using TestBed.
My tests are not working and throwing errors.</p>

<p>Here is my repository: <a href=""https://github.com/aubrey-fowler/NativeScriptUnitTests"" rel=""nofollow noreferrer"">https://github.com/aubrey-fowler/NativeScriptUnitTests</a></p>

<p>Questions:</p>

<ol>
<li>The documentation only shows an example of how to write a test for a
component. How do I write a test for a service? I also need to use
TestBed for this because my service has dependency injection.</li>
<li>My tests are throwing errors. Why and how can I fix them?</li>
</ol>

<p>Errors:</p>

<pre><code>no reachable hosts
</code></pre>

<p>on my Android phone</p>

<p>code snippet:</p>

<pre><code>import { ItemsComponent } from '../app/item/items.component';

import {
    nsTestBedAfterEach,
    nsTestBedBeforeEach,
    nsTestBedRender
} from 'nativescript-angular/testing';

describe('ItemsComponent Test', () =&gt; {

    beforeEach(nsTestBedBeforeEach([ItemsComponent]));
    afterEach(nsTestBedAfterEach(false));

    it('should be defined', () =&gt; {

        nsTestBedRender(ItemsComponent).then((fixture) =&gt; {
            fixture.detectChanges();
            const component = fixture.componentInstance;
            expect(component).toBeTruthy;
        });

    });

});
</code></pre>
",https://stackoverflow.com/questions/60673043/nativescript-how-to-get-unit-tests-to-work-properly,"['angular', 'unit-testing', 'nativescript']",307,True,0,1
Apache Ignite: best practice for starting Ignite server for Unit Testing,"<p>I have a maven/Java 8 project using JUnit4. The code under test creates and manipulates a Cache using the Java thin client. In order to run my unit tests from the command line (mvn test) or from an IDE like Eclipse, I'd like to be able to programatically start an Ignite server. </p>

<p>If I start the server like: </p>

<pre><code>        Runnable runnable = () -&gt; { 
            Ignite ignite = Ignition.getOrStart(cfg);
        };
        Thread t = new Thread(runnable);
        t.start();
</code></pre>

<p>in a @BeforeClass (using Runnable to avoid blocking on getOrStart()), the server dies gracefully after a few Seconds. </p>

<pre><code>[15:34:16] Ignite node started OK (id=33cb95c5)
[15:34:22] Ignite node stopped OK [uptime=00:00:05.378]
</code></pre>

<p>Sadly too soon for my unit tests to run. So is there a best practice for unit testing application code with the ad hoc start of Ignite? Seems to be not an uncommon question but I've yet to find a good answer (""use this framework"", ""extend this class"" etc).</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/61767552/apache-ignite-best-practice-for-starting-ignite-server-for-unit-testing,"['unit-testing', 'junit', 'ignite']",1634,True,0,1
Will nested function be called in mocha unit test after stubbing :AssertionError: expected &#39;some data&#39; to equal &#39;stubbed string&#39;,"<p>I am new to unit testing  using mocha and sinon , just to learn more I have stubbed a function to return some string, in my code I call this function as inner function. My test is to see if the stubbed return string is assigned to a variable. Please look at the code snippet to understand more</p>

<p><strong>file.specjs</strong></p>

<pre><code>let sinon = require(""sinon"");
let filejs = require('./file.js');
let expect = require (""chai"").expect;

it('should run only the outer function' ,function() {

// I try to stub my function here
sinon.stub(filejs,'test1').callsFake ((someArg) =&gt; {
  return ""stubbed string"";
});

// Now I will call my test outer function
   filejs.test();
  expect(filejs.param).to.equal(""stubbed string"");

})

</code></pre>

<pre><code>
    let param;
    module.exports = {
         test,
         test1
    }

    function test () {
      module.exports.param = test1();
    }

    function test1() {
       console.log(""should not be called);
       let data = ""some data"";
       return data; 
    }
</code></pre>

<p>As I have already stubbed the function test1, I don't expect this to be called, and return from test1 is assigned to param and since we have faked the function to return a different string, I expect this string to be set to param variable.</p>

<p>But when I run the test I see this error </p>

<blockquote>
  <p>AssertionError: expected 'some data' to equal 'stubbed string'</p>
</blockquote>
",https://stackoverflow.com/questions/60344754/will-nested-function-be-called-in-mocha-unit-test-after-stubbing-assertionerror,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'sinon']",390,True,0,1
How to test Flask API that uses application factory,"<p>I am writing an API in a flask and I use the application factory. This is how my <code>__init__.py</code> looks.</p>
<pre><code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api

db = SQLAlchemy()
api = Api()   

def create_app():
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object(&quot;config.Config&quot;)

    db.init_app(app)
    api.init_app(app)

    with app.app_context():
        db.create_all()
        return app
</code></pre>
<p>In wsgi.py (which in entry point to start) I have my endpoints.</p>
<pre><code># some more imports
from application import create_app 
app = create_app()

# some more endpoints
api.add_resource(Products, &quot;/products&quot;) # GET
                    
if __name__ == &quot;__main__&quot;:
    # some more code here..
    app.run(debug=True)
</code></pre>
<p>Now I want to write some unittest, but the problem is I constantly get 404 not found on the enpoinds, even thought in postman it work fine.</p>
<p>this is my test.</p>
<pre><code>from unittest import TestCase
from application import create_app
from application import db

app = create_app()


class ProductTest(TestCase):

    def setUp(self) -&gt; None:
        &quot;&quot;&quot; Prepare new database and test client. &quot;&quot;&quot;
        app.config[&quot;SQLALCHEMY_DATABASE_URI&quot;] = &quot;sqlite:///&quot;
        with app.app_context():
            db.init_app(app)
            db.create_all()
        self.app = app.test_client
        self.app_context = app.app_context

    def test_get_products(self):
        with self.app() as client:
            with self.app_context():
                res = client.get(&quot;/products&quot;)
                self.assertEqual(res.status_code, 200)  # it fails - it returns 404 everytime
</code></pre>
<p>I suppose there is some problem with the create_app thing. I don't know exactly how to use it in test. When I write the same API but without using the application factory (and thus without create_app), this test passes.</p>
<p>Can anyone explain me what I am doing wrong and how to use create_app from application factory with unit testing endpoints?</p>
",https://stackoverflow.com/questions/63614655/how-to-test-flask-api-that-uses-application-factory,"['python', 'api', 'unit-testing', 'flask']",737,False,0,0
How to begin unit testing using phpstorm,"<p>so firstly, I am very new to coding. This question pertains to unit testing using php. Should be obvious, I know, but my question is, in order to actually use the unit tests i will eventually create, will I have to also make up some code apply the tests? All of the tutorials explain how to configure the IDE i am using (phpstorm) but do not give any sample code to actually perform the tests. Is there a feature built into phpstorm which allows you to try the unit tests you create? If i do in fact require sample code, what kind of code should i use and where could i get it from? Any help is appreciated, thank you.</p>
",https://stackoverflow.com/questions/60767529/how-to-begin-unit-testing-using-phpstorm,"['php', 'unit-testing']",66,True,0,1
How to create unit tests for .cpp files in a different project,"<p>I'm currently using Microsoft Unit Testing Framework for C++ and have been following this guide:</p>

<p><a href=""https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2019"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2019</a></p>

<p>However, when trying to create a test project under the same solution as the project I am testing I can't I keep getting the linker error</p>

<pre><code>LNK2019 unresolved external symbol ""public: void __cdecl SLL&lt;int&gt;::add(int)"" (?add@?$SLL@H@@QEAAXH@Z) referenced in function ""public: void __cdecl A1272UnitTest::A1272UnitTest::TestMethod1(void)"" (?TestMethod1@A1272UnitTest@1@QEAAXXZ)  
</code></pre>

<p>The problem I am trying to use a method definition inside of the ""q1a.cpp"" file under the project I am testing.</p>

<p>I have tried following this guide 
<a href=""https://learn.microsoft.com/en-us/visualstudio/test/how-to-use-microsoft-test-framework-for-cpp?view=vs-2019#object_files"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/how-to-use-microsoft-test-framework-for-cpp?view=vs-2019#object_files</a></p>

<p>In order to link the obj files but it was of no avail.</p>

<p>This is what my
<a href=""https://i.stack.imgur.com/n9teY.png"" rel=""nofollow noreferrer"">solution directory</a> looks like</p>
",https://stackoverflow.com/questions/62352354/how-to-create-unit-tests-for-cpp-files-in-a-different-project,"['c++', 'visual-studio', 'unit-testing', 'visual-studio-2019']",326,False,0,0
Android Xamarin MenuInflater change from v 6.0 to later versions?,"<p>I'm writing an Android app using Xamarin libraries v27.0.2.1.  I also have references to Xamarin.Android.Support.V7.AppCompat and Xamarin.Android.Suport.V4</p>
<p>I'm unit testing on Android 6.0 and then testing on higher levels.  The following code causes the menu option in the actionbar to be visible and have the standard &quot;settings&quot; menu option.  It's fine on Android v6.0 but testing on v7.0 and higher, the menu icon (three dots) doesn't appear.  What am I missing?</p>
<p>Here's the toolbar xml:</p>
<pre><code>&lt;Toolbar xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:minHeight=&quot;?android:attr/actionBarSize&quot;
            android:background=&quot;?android:attr/colorPrimary&quot;
            android:titleTextColor=&quot;@android:color/white&quot;
            android:minWidth=&quot;200px&quot;
            android:id=&quot;@+id/toolbar1&quot; 
            android:title=&quot;@string/title_bar&quot;
            android:theme=&quot;@style/ThemeOverlay.AppCompat.Dark&quot;
            /&gt;
</code></pre>
<p>I'm adding it to the layout using include:</p>
<pre><code>        &lt;include 
            android:id=&quot;@+id/toolbarMain&quot;
            layout=&quot;@layout/toolbar&quot;
            android:layout_columnSpan=&quot;2&quot;
            android:layout_column=&quot;0&quot;
            android:layout_columnWeight=&quot;1&quot;/&gt;
</code></pre>
<p>Here's the code to activate it.</p>
<pre><code>        {
            MenuInflater.Inflate(Resource.Menu.menu_main, menu);
            return base.OnCreateOptionsMenu(menu);
        }
</code></pre>
<p>As I mentioned, it works on Android 6.0 but not any higher versions.  I'm surely missing something simple, but I can't find it and haven't found any articles on this.</p>
",https://stackoverflow.com/questions/62661588/android-xamarin-menuinflater-change-from-v-6-0-to-later-versions,"['android', 'xamarin']",39,True,0,1
Squirejs : requirejs is not defined,"<p>We have an amd/requirejs based web app. We came to a point to add a unit testing to our code. Googling returned that squireJs is best amd-require based mocking library. after installing, The problem is that we cant resolve the squirejs dependency. The issue seems so basic but we tried with both Mocha and Jasmine to use it, though it seems something we are forgetting to configure:</p>

<p>our js that we want to test looks basically like:</p>

<pre><code>define(function employeeAndTagsPage(require) {  
    var global = require('common/global');
    var customMessageWindow = require('../../customMessageWindow/customMessageWindow');

    var currentTab;
    var navigate = null;
    // and other BL
});
</code></pre>

<p>Package.json:</p>

<pre><code>{
  ""name"": ""jasmine.test"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""index.js"",
  ""scripts"": {
    ""test"": ""echo \""Error: no test specified\"" &amp;&amp; exit 1""
  },
  ""author"": """",
  ""license"": ""MIT"",
  ""devDependencies"": {
    ""amd-loader"": ""0.0.8"",
    ""jasmine-node"": ""^3.0.0"",
    ""requirejs"": ""^2.3.6"",
    ""squirejs"": ""^0.2.1""
  }
}
</code></pre>

<p>Jasmine_examples PlayerSpec.js:</p>

<pre><code>describe(""Player"", function () {
    require('amd-loader');
  var Player = require('../../lib/jasmine_examples/Player');
    var Song = require('../../lib/jasmine_examples/Song');
    var requirejs = require('requirejs');
    var squire = requirejs('squirejs'); // here it fails 
    var player, song,  mock;

  beforeEach(function() {
    player = new Player();
    song = new Song();
    mock = new squire();
  });
//unit tesitng 
});
</code></pre>

<p>The error we are getting:</p>

<pre><code>ReferenceError: requirejs is not defined
  Stack:
        at &lt;Jasmine&gt;
        at getContext (c:\Synel\TESTS\eHarmonyNew-Jasmine\eHarmony\App\Test\node_modules\squirejs\src\Squire.js:58:5)
        at Squire.configure (c:\Synel\TESTS\eHarmonyNew-Jasmine\eHarmony\App\Test\node_modules\squirejs\src\Squire.js:107:15)
</code></pre>

<p>The squirejs library code can be found here:</p>

<p><a href=""https://github.com/iammerrick/Squire.js/blob/master/src/Squire.js"" rel=""nofollow noreferrer"">https://github.com/iammerrick/Squire.js/blob/master/src/Squire.js</a></p>

<p>What is the reason of the library being failed ? What we are forgetting? Any assist or reccomendation is appraciated</p>
",https://stackoverflow.com/questions/60055072/squirejs-requirejs-is-not-defined,"['node.js', 'jasmine', 'requirejs', 'mocha.js', 'squirejs']",183,False,0,0
How to unit test whether a file was moved from a local directory to an ActiveMQ queue,"<p>I am new to apache camel and am currently working on unit testing of a folder watcher system. I have a simple route builder that looks at one directory and if the application is run that file is deleted from that directory and then moved to an activeMQ queue.</p>
<p>My question is how do I go about testing this? If I was to run the unit tests I want to be able to see that the folder that moves the file is actually doing as such and that the activeMQ is receiving that file.</p>
<p>I'm sorry if this is very vague, I can offer clarification where I can, this is more of a high-level question just to help me on the right path.</p>
",https://stackoverflow.com/questions/65499625/how-to-unit-test-whether-a-file-was-moved-from-a-local-directory-to-an-activemq,"['spring-boot', 'junit', 'apache-camel']",49,False,0,1
Unable to instantiate angular form.properties in jasmine unit test,"<p>I have a simple clear method in my component as below. As you can see in the comment, <code>this.form.reset();</code> is causing an error in my test. When this line is removed the test succeeds. The error is <code>// TypeError: Cannot read property 'reset' of undefined</code></p>

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

<pre><code>  onClearFilter() {
        this.form.reset(); // TypeError: Cannot read property 'reset' of undefined
        this.search = '';
        this.isAdvanced = false;

        this.filterStateService.clearFilterState(this.filterStateKey);

        // Reset Filter state
        this.filterState = new Filter(this.filterStateKey);
        this.filterStateService.filterStates[this.filterStateKey] = { ...this.filterState };
        this.doFilter();
    }
</code></pre>

<p><strong>myComponent.spec.ts</strong></p>

<pre><code>describe('onClearFilter', () =&gt; {
    it('makes expected calls', () =&gt; {
        const filterStateServiceStub: FilterStateService = fixture.debugElement.injector.get(FilterStateService);
        spyOn(filterStateServiceStub, 'clearFilterState').and.callThrough();
        component.onClearFilter();
        expect(filterStateServiceStub.clearFilterState).toHaveBeenCalled();
    });
});
</code></pre>

<p>I'm new to Unit Testing, but I guess I need to define this.form into my <code>it()</code> to allow <code>reset</code> to no longer be undefined - how do I do this in my scenario? Thanks</p>

<p><strong>UPDATE</strong></p>

<p>I tried...</p>

<pre><code>describe('onClearFilter', () =&gt; {
    it('makes expected calls', () =&gt; {
        const filterStateServiceStub: FilterStateService = fixture.debugElement.injector.get(FilterStateService);
        const form: FormGroup = fixture.debugElement.injector.get(FormGroup);
        component.form = form;
        spyOn(filterStateServiceStub, 'clearFilterState').and.callThrough();
        spyOn(component.form, 'reset').and.callThrough();
        component.onClearFilter();
        expect(component.form.reset).toHaveBeenCalled();
        expect(filterStateServiceStub.clearFilterState).toHaveBeenCalled();
    });
});
</code></pre>

<p><code>FormGroup</code> comes from <code>ReactiveFormsModule</code> import, so I tried getting form.reset from that as above but got a new error of...</p>

<pre><code>Error: StaticInjectorError(DynamicTestModule)[FormGroup]: 
  StaticInjectorError(Platform: core)[FormGroup]: 
    NullInjectorError: No provider for FormGroup!
</code></pre>

<p>Based on the above I then added <code>FormGroup</code> to my providers but this came up with its own issues and upon reading you dont do that as everything is available from the <code>ReactiveFormsModule</code> import.</p>
",https://stackoverflow.com/questions/61081277/unable-to-instantiate-angular-form-properties-in-jasmine-unit-test,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",124,False,0,0
How to convert one string to another by successive substitutions of characters?,"<p>I'm currently trying to design an algorithm that doing such thing:</p>

<p>I got two strings A and B which consist of lowercase characters 'a'-'z'
and I can modify string A using the following operations:</p>

<pre><code>1. Select two characters 'c1' and 'c2' from the character set ['a'-'z'].
2. Replace all characters 'c1' in string A with character 'c2'.
</code></pre>

<p>I need to find the minimum number of operations needed to convert string A to string B when possible.</p>

<p>I have 2 ideas that didn't work </p>

<pre><code>1. Simple range-based for cycle that changes string B and compares it with A.
2. Idea with map&lt;char, int&gt; that does the same.
</code></pre>

<p>Right now I'm stuck on unit-testing with such situation : 'ab' is transferable to 'ba' in 3 iterations and 'abc' to 'bca' in 4 iterations.
My algorithm is wrong and I need some fresh ideas or working solution. 
Can anyone help with this?</p>

<p>Here is some code that shows minimal RepEx:</p>

<pre class=""lang-cpp prettyprint-override""><code>int Transform(string&amp; A, string&amp; B)
{
    int count = 0;

    if(A.size() != B.size()){
        return -1;
    }

    for(int i = A.size() - 1; i &gt;= 0; i--){
        if(A[i]!=B[i]){
           char rep_elem = A[i];
           ++count;
           replace(A.begin(),A.end(),rep_elem,B[i]);
        }
    }

    if(A != B){
        return -1;
    }

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

<p>How can I improve this or I should find another ideas? </p>
",https://stackoverflow.com/questions/60320236/how-to-convert-one-string-to-another-by-successive-substitutions-of-characters,"['c++', 'string', 'algorithm']",809,True,0,1
Testing a function in a react component with Jest,"<p>I'm pretty new to unit testing with react components. I have a react component that copies the given id from props when clicked. And that's calling a function from a separate file to execute a copyToClipboard function and then set the state of a react component to 'copied'. I'm trying to test test these functions and possibly get the state value changed to 'copied'. Whenever i try to simulate the onclick function, it gives an error saying 'Cannot read property 'writeText' of undefined'. It's because onClick function is calling a seperate function for this process, is it possible to mock that other function and pass that to onClick() function or another solution? Or any pointers how i should move forward?</p>
<p>App.js</p>
<pre><code>import React from &quot;react&quot;;
import &quot;./styles.css&quot;;
import {copyToClipboard} from './CopyFile'
export default function App({id}) {
  const [copyStatus, setCopyStatus] = useState('')

  const copyLineItemId=(id)=&gt;{
    copyToClipboard(id)
    setCopyStatus('Copied')
    setTimeout(function () {
      setCopyStatus('')
    }, 2000)
  }

  return (
    &lt;div&gt;
      &lt;i id=&quot;copy&quot; className=&quot;fa fa-copy&quot; onClick={() =&gt;copyLineItemId({id})}&gt;&lt;/i&gt;
      &lt;p id=&quot;status&quot;&gt;{copyStatus}&lt;/p&gt;
  &lt;/div&gt;
  );
}
</code></pre>
<p>Test file</p>
<pre><code>import React from 'react'
import { mount } from 'enzyme'
import { MockedProvider } from '@apollo/react-testing'

function getComponent(props) {
  const { componentProps } = props
  return (
    &lt;MockedProvider&gt;
      &lt;CopyComponent {...componentProps} /&gt;
    &lt;/MockedProvider&gt;
  )
}


test('copy function', () =&gt; {
    const componentProps = {
      id:123
    }

    const wrapper = mount(getComponent({ componentProps }))

    wrapper.find(&quot;#copy&quot;).simulate('click')

    expect(wrapper.find(&quot;#status&quot;)).toEqual(&quot;Copied&quot;)
  })
</code></pre>
<p>copy function CopyFile.js</p>
<pre><code>const copyToClipboard = (arg) =&gt; {
  navigator.clipboard.writeText(arg)
}

export {copyToClipboard}
</code></pre>
",https://stackoverflow.com/questions/63310438/testing-a-function-in-a-react-component-with-jest,"['reactjs', 'mocking', 'jestjs', 'enzyme']",265,False,0,1
Fongo - Fake Mongo : Not able to load dataset from location for unit testing of mongrepository using fongo,"<p>I am using fongo as in memory database for testing my mongodbrepository.</p>
<p>I have taken reference from <a href=""http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html"" rel=""nofollow noreferrer"">http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html</a> for unit testing.</p>
<p>To populate sample data, I have added required json file under test/resources/json-data/user/user.json but it's not loaded into fongo.</p>
<pre><code>@Test
@UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT, locations = &quot;/json-data/user/user.json&quot;) // test/resources/..
    public void findUser_should_return_user() {
        User user = userRepository.findByXYZId(&quot;XX12345&quot;);
        assertNotNull(user);
    }
</code></pre>
<p>What's  missing ? What needs to change to load dataset from json to fongo(fake mongo)</p>
<p>[Edit-1] Need to try 2 things #1 Include missing rule &amp; #2 json format</p>
<p>looks like json format need to include collection name -
Reference-1 : <a href=""https://github.com/lordofthejars/nosql-unit#dataset-format"" rel=""nofollow noreferrer"">https://github.com/lordofthejars/nosql-unit#dataset-format</a></p>
<p>Reference 2 -https://github.com/lordofthejars/nosql-unit/tree/master/nosqlunit-demo/src/test/resources/com/lordofthejars/nosqlunit/demo/mongodb</p>
",https://stackoverflow.com/questions/63289949/fongo-fake-mongo-not-able-to-load-dataset-from-location-for-unit-testing-of,"['java', 'mongodb', 'junit', 'fongo']",250,True,0,2
How to fix this test case: Can&#39;t bind to &#39;value&#39; since it isn&#39;t a known property of &#39;dls-option&#39;,"<p>This is my day 3 in Angular unit testing with Jasmine and Karma. I'm following Pluralsight lectures. First thing first, <code>dls-option</code> is a component which I'm using form a library. I'll explain. I'm using a library of angular components provided by our company. In the below code <code>&lt;dls-dropdown&gt;</code> and <code>&lt;dls-option&gt;</code> are nothing but <code>&lt;select&gt;</code> and <code>&lt;option&gt;</code> tag of HTML. They've created color and font styling wrapper around it. Here's my code:</p>

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

<pre><code>&lt;div&gt;
  &lt;h1&gt;Choose one from the list&lt;/h1&gt;
  &lt;dls-dropdown&gt;
    &lt;dls-option *ngFor=""let mode of modes"" [value]=""mode""&gt;
      &lt;p&gt;{{ mode }}&lt;/p&gt;
    &lt;/dls-option&gt;
  &lt;/dls-dropdown&gt;
 &lt;/div&gt;
</code></pre>

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

<pre><code>import { Component, OnInit, ... } from '@angular/core';
...

@Component({
    selector: 'app-timeselector',
    templateUrl: './timeselector.component.html'
})
export class TimeselectorComponent implements OnInit {
    modes = [""Novice"", ""Intermediate"", ""Expert"", ""Beast""];
    ...
}
</code></pre>

<p>and here's my test file:
<strong>timeselector.component.spec.ts</strong></p>

<pre><code>import { TestBed, ComponentFixture } from ""@angular/core/testing""
import { TimeselectorComponent } from './timeselector.component'
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

fdescribe('TimeselectorComponent', () =&gt; {
    let fixture: ComponentFixture&lt;TimeselectorComponent&gt;;
    @Component({
        selector: 'dls-label',
        template: '&lt;div&gt;&lt;/div&gt;'
    })
    class DlsLabelComponent {}

    @Component({
        selector: 'dls-dropdown',
        template: '&lt;div&gt;&lt;/div&gt;'
    })
    class DlsDropdownComponent {}


    @Component({
        selector: 'dls-option',
        template: '&lt;div&gt;&lt;/div&gt;'
    })
    class DlsDropdownOption {}

    beforeEach(()=&gt;{
        TestBed.configureTestingModule({
            imports: [
                FormsModule
            ],
            declarations: [
                TimeselectorComponent,
                DlsLabelComponent,
                DlsDropdownComponent,
                DlsDropdownOption
            ]
        });
        fixture = TestBed.createComponent(TimeselectorComponent);
    })
    it('should create', ()=&gt; {
        //expect(fixture.componentInstance).toBeTruthy();
    })
})
</code></pre>

<p>But my test case is failing. Here's the screenshot:
<a href=""https://i.stack.imgur.com/cvQ5Z.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cvQ5Z.png"" alt=""enter image description here""></a></p>

<p>Please help me with this and also feel free to suggest other mistakes as well. This will help me in my career.</p>

<p>PS: I just want to do a shallow testing. I want to mock child components.</p>
",https://stackoverflow.com/questions/61698628/how-to-fix-this-test-case-cant-bind-to-value-since-it-isnt-a-known-property,"['angular', 'jasmine', 'karma-jasmine', 'angular-unit-test']",710,True,0,1
Why is a .tns file being imported when running &quot;ng test&quot; in this NativeScript Code-Sharing project?,"<p>I have a NativeScript Code-Sharing project. I wish to use Karma unit testing against the web version using <code>ng test</code>. This fails due to a <code>.tns</code> version of a service being wrongly imported when building the tests.</p>

<p>Following are steps to recreate the problem in a minimal NativeScript Code-Sharing project.</p>

<ul>
<li><p>Create a new NativeScript Code-Sharing project</p>

<pre><code>$ ng new -c=@nativescript/schematics ns-shared-test --shared
</code></pre></li>
<li><p>Enter the project folder</p>

<pre><code>$ cd ns-shared-test
</code></pre></li>
<li><p>Generate a new service</p>

<pre><code>$ ng generate service services/my-service
</code></pre></li>
<li><p>Generate a new component</p>

<pre><code>$ ng generate component my-component
</code></pre></li>
<li><p>Modify <code>my-component.component.ts</code> to use my-service</p>

<ul>
<li><p>Add at top of file:</p>

<pre><code>import { MyServiceService } from '@src/app/services/my-service.service';
</code></pre></li>
<li><p>And replace the constructor:</p>

<pre><code>constructor( private myService:MyServiceService ) { }
</code></pre></li>
</ul></li>
<li><p>Run unit tests</p>

<pre><code>$ ng test
</code></pre>

<ul>
<li>Observe that the test passes</li>
</ul></li>
<li><p>Split my-service</p>

<pre><code>$ cp src/app/services/my-service.service.ts src/app/services/my-service.service.tns.ts
</code></pre></li>
<li><p>Modify <code>my-service.service.tns.ts</code> to use something NativeScript specific</p>

<ul>
<li><p>Add at the top of file:</p>

<pre><code>import { Color } from 'tns-core-modules/color/color';
</code></pre></li>
<li><p>And replace the constructor:</p>

<pre><code>constructor() { new Color('white'); }
</code></pre></li>
</ul></li>
<li><p>Run unit tests</p>

<pre><code>$ ng test
</code></pre>

<ul>
<li>Observe that the test fails while loading NativeScript modules</li>
</ul></li>
</ul>
",https://stackoverflow.com/questions/59631732/why-is-a-tns-file-being-imported-when-running-ng-test-in-this-nativescript-co,"['nativescript', 'angular2-nativescript', 'nativescript-codesharing']",74,True,0,1
"SpringBootTest, Testcontainers, container start up - Mapped port can only be obtained after the container is started","<p>I am using docker/testcontainers to run a postgresql db for testing.  I have effectively done this for unit testing that is just testing the database access.  However, I have now brought springboot testing into the mix so I can test with an embedded web service and I am having problems.</p>
<p>The issue seems to be that the dataSource bean is being requested before the container starts.</p>
<pre><code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [com/myproject/integrationtests/IntegrationDataService.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Mapped port can only be obtained after the container is started
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Mapped port can only be obtained after the container is started
Caused by: java.lang.IllegalStateException: Mapped port can only be obtained after the container is started
</code></pre>
<p>Here is my SpringBootTest:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {IntegrationDataService.class,  TestApplication.class},
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringBootTestControllerTesterIT
    {
    @Autowired
    private MyController myController;
    @LocalServerPort
    private int port;
    @Autowired
    private TestRestTemplate restTemplate;


    @Test
    public void testRestControllerHello()
        {
        String url = &quot;http://localhost:&quot; + port + &quot;/mycontroller/hello&quot;;
        ResponseEntity&lt;String&gt; result =
                restTemplate.getForEntity(url, String.class);
        assertEquals(result.getStatusCode(), HttpStatus.OK);
        assertEquals(result.getBody(), &quot;hello&quot;);
        }

    }
</code></pre>
<p>Here is my spring boot application referenced from the test:</p>
<pre><code>@SpringBootApplication
public class TestApplication
    {

    public static void main(String[] args)
        {
        SpringApplication.run(TestApplication.class, args);
        }
   
    }
</code></pre>
<p>Here is the IntegrationDataService class which is intended to startup the container and provide the sessionfactory/datasource for everything else</p>
<pre><code>@Testcontainers
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@EnableTransactionManagement
@Configuration
public  class IntegrationDataService
    {
    @Container
    public static PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer(&quot;postgres:9.6&quot;)
            .withDatabaseName(&quot;test&quot;)
            .withUsername(&quot;sa&quot;)
            .withPassword(&quot;sa&quot;)
            .withInitScript(&quot;db/postgresql/schema.sql&quot;);   

    @Bean
    public Properties hibernateProperties()
        {
        Properties hibernateProp = new Properties();
        hibernateProp.put(&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.PostgreSQLDialect&quot;);
        hibernateProp.put(&quot;hibernate.format_sql&quot;, true);
        hibernateProp.put(&quot;hibernate.use_sql_comments&quot;, true);
//        hibernateProp.put(&quot;hibernate.show_sql&quot;, true);
        hibernateProp.put(&quot;hibernate.max_fetch_depth&quot;, 3);
        hibernateProp.put(&quot;hibernate.jdbc.batch_size&quot;, 10);
        hibernateProp.put(&quot;hibernate.jdbc.fetch_size&quot;, 50);
        hibernateProp.put(&quot;hibernate.id.new_generator_mappings&quot;, false);
//        hibernateProp.put(&quot;hibernate.hbm2ddl.auto&quot;, &quot;create-drop&quot;);
//        hibernateProp.put(&quot;hibernate.jdbc.lob.non_contextual_creation&quot;, true);
        return hibernateProp;
        }

    @Bean
    public SessionFactory sessionFactory() throws IOException
        {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        sessionFactoryBean.setPackagesToScan(&quot;com.myproject.model.entities&quot;);
        sessionFactoryBean.afterPropertiesSet();
        return sessionFactoryBean.getObject();
        }

    @Bean
    public PlatformTransactionManager transactionManager() throws IOException
        {
        return new HibernateTransactionManager(sessionFactory());
        }     
   
    @Bean
    public DataSource dataSource()
        {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(postgreSQLContainer.getDriverClassName());
        dataSource.setUrl(postgreSQLContainer.getJdbcUrl());
        dataSource.setUsername(postgreSQLContainer.getUsername());
        dataSource.setPassword(postgreSQLContainer.getPassword());
        return dataSource;
        }

    }
</code></pre>
<p>The error occurs on requesting the datasource bean from the sessionFactory from one of the Dao classes before the container starts up.</p>
<p>What the heck am I doing wrong?</p>
<p>Thanks!!!</p>
",https://stackoverflow.com/questions/64528638/springboottest-testcontainers-container-start-up-mapped-port-can-only-be-obt,"['spring-boot', 'junit', 'testcontainers']",8306,True,4,1
GitLab CI failing with SSH error loading key invalid format,"<p>I am starting to get into GitLab CI for my company. We have a PrestaShop, and I want automatic deployment to the web server after a Git push.</p>
<p>Unit testing will come later. At the moment I just need it to deal with putting a copy of the &quot;/app&quot; folder in the web root of the web server.</p>
<p>So this is what I have got...</p>
<pre><code>before_script:
  - apt-get update -qq
  - apt-get install -qq git
  - 'which ssh-agent || ( apt-get install -qq openssh-client )'
  - eval $(ssh-agent -s)
  - ssh-add &lt;(echo &quot;$SSH_PRIVATE_KEY&quot;)
  - mkdir -p ~/.ssh
  - '[[ -f /.dockerenv ]] &amp;&amp; echo -e &quot;Host *\n\tStrictHostKeyChecking no\n\n&quot; &gt; ~/.ssh/config'


deploy_test:
  type: deploy
  environment:
    name: test
    url: [test server domain]
  script:
    - ssh [user]@[server] -p [port] &quot;cd [repo folder] &amp;&amp; git checkout master &amp;&amp; git pull origin master &amp;&amp; exit&quot;
    - ssh [user]@[server] -p [port] &quot;rsync -rzvh [repo /app folder] [web server root path]&quot;
  only:
    - master
</code></pre>
<p>Recently, gitlab-runner has started failing with the error <code>Error loading key &quot;/dev/fd/63&quot;: invalid format</code>.</p>
<p>Can you help me to solve that error?</p>
<p>FYI, I have my personal private key set as $SSH_PRIVATE_KEY environment var in GitLab - the public on the web server of course. SSH is enabled on the web server which has WHM and cPanel. And I pre-checked out a copy of master via cPanel on the web server into the [repo folder].</p>
",https://stackoverflow.com/questions/62743906/gitlab-ci-failing-with-ssh-error-loading-key-invalid-format,"['ssh', 'gitlab', 'prestashop', 'web-deployment', 'gitlab-ci']",2371,True,4,2
How React Testing Library can assert children props and Redux store updates?,"<p>I just started exploring a unit testing framework for my react application. I locked my choice at <code>@testing-library/react</code> instead of <code>Enzyme</code> as it is recommended by React and helps writing more robust tests. I'm also planning to use <code>Jest</code> for completeness.</p>

<p>But before I could proceed with <code>React Testing Library</code>, I'm stuck at few questions. Can someone please help?</p>

<p>For instance, </p>

<ol>
<li>There is an <code>Editor</code> component which updates Redux store based on user input.</li>
<li>There is another component <code>Preview</code> which reads value directly from store.</li>
<li>There is a third component <code>Container</code> which contains both of the above components passing some props.</li>
</ol>

<p>Questions:</p>

<ol>
<li>How to test if user input in <code>Editor</code> component actually updates store?</li>
<li>How to test if <code>Preview</code> component can render value reading from store?</li>
<li>How to test if <code>Container</code> component passes props correctly to its children?</li>
</ol>

<p><br></p>

<p><strong>Container.jsx</strong></p>

<pre><code>import React from 'react';
import Editor from './Editor';
import Preview from './Preview';

const Container = ({editorType}) =&gt; {
  return (
    &lt;div&gt;
      &lt;Editor type={editorType} /&gt;
      &lt;Preview /&gt;
    &lt;/div&gt;
  );
};
export default Container;
</code></pre>

<p><strong>Editor.jsx</strong></p>

<pre><code>import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {setName} from './actions';

const Editor = ({type}) =&gt; {
  const name = useSelector(state =&gt; state.name);
  const dispatch = useDispatch();

  return (
    &lt;div&gt;
      &lt;h1&gt;Type: {type}&lt;/h1&gt;
      &lt;input value={name} onChange={evt =&gt; dispatch(setName(evt.target.value))} /&gt;
    &lt;/div&gt;
  );
};
export default Editor;
</code></pre>

<p><strong>Preview.jsx</strong></p>

<pre><code>import React from 'react';
import { useSelector } from 'react-redux';

const Editor = ({type}) =&gt; {
  const name = useSelector(state =&gt; state.name);

  return (
    &lt;div&gt;
      &lt;h1&gt;Name: {name}&lt;/h1&gt;
    &lt;/div&gt;
  );
};
export default Preview;
</code></pre>
",https://stackoverflow.com/questions/62049939/how-react-testing-library-can-assert-children-props-and-redux-store-updates,"['reactjs', 'redux', 'jestjs', 'enzyme', 'react-testing-library']",4385,True,3,1
Dynamically loading modules in Racket,"<p>For a project I am creating a class <code>driver%</code> which is supposed to be a layer of abstraction over different modules providing the same procedures. The class would be initialized with an argument that specifies the module to be used.</p>
<p>Additionally, I would like <code>driver%</code> to expose the same procedures but without side effects, to facilitate unit testing classes that use the driver.</p>
<p>Consider the following:</p>
<strong><code>module_one.rkt</code></strong>
<pre><code>#lang racket
(provide foo)
(define (foo)
  (display &quot;called from &quot;module one&quot;))
</code></pre>
<strong><code>module_two.rkt</code></strong>
<pre><code>#lang racket
(provide foo)
(define (foo)
  (display &quot;called from &quot;module two&quot;))
</code></pre>
<strong><code>driver.rkt</code></strong>
<pre><code>#lang racket
(require (prefix-in one: &quot;module_one.rkt&quot;)
         (prefix-in two: &quot;module_two.rkt&quot;))

(provide driver%)

(define driver%
  (class object%
         (super-new)
         (init driver-choice)
         (define choice driver-choice)
         (define/public (foo)
           (case choice
             [(1) (one:foo)]
             [(2) (two:foo)]
             [else void]))))       
</code></pre>
<p>This fulfills the above requirements, but is not very elegant: for each exposed procedure, another case expression will have to be added. This seems unnecessary, as the choice for an API is made when the class is instantiated, so the choice will be the same everywhere.</p>
<p>What would be a more acceptable solution to this problem? I have looked into using <code>local-require</code>, but this does not seem to work with <code>define/public</code>.</p>
<p>Many thanks!</p>
",https://stackoverflow.com/questions/64444079/dynamically-loading-modules-in-racket,['racket'],183,True,3,1
Android Robolectric unit testing not working in a dynamic feature modules why?,"<p>Robolectric unit testing fails with error message <code>java.lang.RuntimeException: android.content.pm.PackageParser$PackageParserException: Failed to parse {projectDir}/build/intermediates/apk_for_local_test/debugUnitTest/apk-for-local-test.ap_</code>, </p>

<pre><code>Caused by: java.lang.NullPointerException
</code></pre>

<p>I started writing unit tests for my application using Robolectric in multi-dynamic feature application, I also just got a fair grip of dynamic feature modules and how best to share dependencies among them. Below is how I solved it.</p>

<p><a href=""https://i.stack.imgur.com/0FZUW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0FZUW.png"" alt=""Dynamic feature architecture""></a></p>

<p>The problem is that a viewMoel factory dependency common to all which is inject by dagger resides in the library module and a viewModel unit test class resides in the DynamicFeat-1 always fails with error <code>java.lang.RuntimeException: android.content.pm.PackageParser$PackageParserException: Failed to parse {projectDir}/build/intermediates/apk_for_local_test/debugUnitTest/apk-for-local-test.ap_</code></p>

<p>And the unit test base class</p>

<pre><code>abstract class BaseTest {

    lateinit var mockServer: MockWebServer

    @Inject
    lateinit var factory: ViewModelProviderFactory


    @Before
    open fun setUp(){

        setUpMockServer()
        configureDI()

    }

    @After
    open fun tearDown(){

        if(isMockServerEnabled()){

            mockServer.shutdown()
        }
    }



    abstract fun isMockServerEnabled(): Boolean

    private fun setUpMockServer(){

        if(isMockServerEnabled()){

            mockServer = MockWebServer()
            mockServer.start()
        }
    }

    open fun mockHttpResponse(fileName: String, responseCode: Int) = mockServer.enqueue(MockResponse()
            .setResponseCode(responseCode)
            .setBody(getJson(fileName)))

    private fun getJson(path : String) : String {
        val uri = this.javaClass.classLoader!!.getResource(path)
        val file = File(uri.path)
        return String(file.readBytes())
    }

    private fun configureDI(){

        //val coreComponent = DaggerCoreComponent.builder().contextModule(ContextModule(RuntimeEnvironment.application)).build()
        DaggerTestHomeComponent.builder().build().inject(this)
    }
}
</code></pre>

<p>The unit test class extends the base and sets up the viewModel by calling <code>super.setUp()</code> but this will always fail. Can anyone help me figure out how to make this work? I will be happy to provide more details if needed, am using robolectric <code>4.3</code></p>
",https://stackoverflow.com/questions/62202196/android-robolectric-unit-testing-not-working-in-a-dynamic-feature-modules-why,"['android', 'robolectric']",615,False,3,0
Subscribe to activated route parameter in Angular9 unit test,"<p>I am hitting a problem unit testing the following Angular 9 component:</p>
<pre><code>export class BirdsDetailComponent implements OnInit {
  ...

  constructor(private route: ActivatedRoute) {
    route.params.subscribe(_ =&gt; {
      this.route.paramMap.subscribe(pmap =&gt; this.getData(+pmap.get('id')));
    });
  }

  ngOnInit() {}

  getData(id: number): void { ... }
</code></pre>
<p>Unlike in other components that I am familiar with, this component initiates the data retrieval from the constructor.</p>
<p>I am hitting a problem (I think) with setting the route parameter.  I have tried a range of ways of setting up the activated route mock/stub.  Including the one found in this setup in the <a href=""https://stackblitz.com/angular/xkagvbjambb?file=src%2Fapp%2Fhero%2Fhero-detail.component.spec.ts"" rel=""nofollow noreferrer"">Angular docs</a>.</p>
<pre><code>describe('BirdsDetailComponent', () =&gt; {

  let component: BirdsDetailComponent;
  let fixture: ComponentFixture&lt;BirdsDetailComponent&gt;;

  let activatedRoute: ActivatedRouteStub;

  beforeEach(() =&gt; {
    activatedRoute = new ActivatedRouteStub();
  });


  // the `id` value is irrelevant because ignored by service stub
  beforeEach(() =&gt; activatedRoute.setParamMap({ id: 99999 }));

  beforeEach(async(() =&gt; {
    const routerSpy = createRouterSpy();
    function createRouterSpy() {
      return jasmine.createSpyObj('Router', ['navigate']);
    }

    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes([])],
      declarations: [BirdsDetailComponent],
      providers: [
        {
          provide: ActivatedRoute, useValue: ActivatedRouteStub
        }
        // {
        //   provide: ActivatedRoute,
        //   useValue: {
        //     params: of({ id: '123' })
        //   }
        // }
      ]
    })
      .compileComponents();
  }));


  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(BirdsDetailComponent);
    component = fixture.componentInstance;

    activatedRoute.setParamMap({ id: 1 });
  });

  it('should call getData', () =&gt; {
    const conserveStatus = {
      conservationStatusId: 1, conservationList: 'string',
      conservationListColourCode: 'string', description: 'string', creationDate: 'Date | string',
      lastUpdateDate: 'Date | string', birds: []
    };

    const bird = {
      birdId: 1, class: 'string', order: 'string', family: 'string',
      genus: 'string', species: 'string', englishName: 'string', populationSize: 'string',
      btoStatusInBritain: 'string', thumbnailUrl: 'string', songUrl: 'string',
      birderStatus: 'string', birdConservationStatus: conserveStatus,
      internationalName: 'string', category: 'string', creationDate: 'Date | string',
      lastUpdateDate: 'Date | string'
    };

    fixture.detectChanges();
    // // Act or change
    // component.getBird(1);

    // // fixture.detectChanges();

    // Assert
    expect(mockBirdsService.getBird).toHaveBeenCalled();
  });

});
</code></pre>
<p>I have also tried a simple setup of the activated route parameter, which you can see in the commented out code, like this (and variation of this):</p>
<pre><code> {
   provide: ActivatedRoute,
   useValue: {
     params: of({ id: '123' })
   }
 }
</code></pre>
<p>Whatever I try I also seem to hit the 'Cannot read property 'subscribe' of undefined thrown' error.  Could the problem be related to detecting the changes?  Can anyone point me in the right direction?</p>
",https://stackoverflow.com/questions/61050735/subscribe-to-activated-route-parameter-in-angular9-unit-test,"['karma-jasmine', 'angular9']",999,True,3,1
Python 3 Pytest: How to mock request urlopen response and headers?,"<p>I have broken my code down into separate functions for unit testing. I am trying to pick up Pytest testing framework and so far only know the basics. </p>

<p>I don't actually want to send a request to the internet -- this would be a fruitless test since I'd only be testing the <code>urllib</code> library anyway. I do, however, want to test how the response is handled. </p>

<p>I have this function to make the request</p>

<pre><code>def request_url(url):
    return request.urlopen(url)
</code></pre>

<p>And then I am checking the content type:</p>

<pre><code>def get_document_type(req):
    """""" checks if document is html or plain text """"""
    doc_type = req.info().get_content_type()
    if doc_type == ""text/html"":
        return ""html""
    elif doc_type == ""text/plain"":
        return ""txt""
    else: 
        return error_message[""unsupported_document_type""]
</code></pre>

<p>Then I will need to test and I will need to mock each outcome. If this was Node.js I could use something like rewire or a sinon stub. </p>

<pre><code>def get_content(req):
    doc_type_response = get_document_type(req)
    if doc_type_response == ""html"":
        # handle html content
    elif get_type_response == ""txt"":
        # handle plain text
    else:
        return doc_type_response
</code></pre>

<p>This unit test works but I don't want to make the real call. </p>

<pre><code>def test_request_url():
    url = request_url(url_to_try).info().get_content_type() 
    assert url == ""text/plain""
</code></pre>

<p>Does anybody know the best way to do this please? </p>
",https://stackoverflow.com/questions/59643855/python-3-pytest-how-to-mock-request-urlopen-response-and-headers,"['python', 'python-3.x', 'unit-testing', 'mocking', 'pytest']",5199,True,3,1
Check if a repeated field in a protobuf message contains a value,"<p>I'm doing some unit testing using gTest and gMock, trying to test if a function is passed a protobuf message which contains a specific value in a repeated field. I'm currently building an exact copy of the expected message, and then using <code>google::protobuf::util::MessageDifferencer</code> to expect that the exact message is received. </p>

<p>The issue is that I don't really want to compare the entire message; I only want to verify that a specific value exists in a repeated field. There could be other values in there I don't care about.</p>

<p>I was thinking about writing a custom matcher, something like</p>

<pre><code>MATCHER_P(FieldFinder, expected, """")
{
  for (element : arg.repeated_field())
  {
    if (element == expected)
    {
      return true;
    }
  }
  return false;
}
</code></pre>

<p>But this matcher would be tied into this specific message structure and wouldn't let me reuse it if the repeated field is at a different location. Is there a better way to do this?</p>
",https://stackoverflow.com/questions/60566131/check-if-a-repeated-field-in-a-protobuf-message-contains-a-value,"['unit-testing', 'automated-tests', 'googletest', 'googlemock']",862,False,3,0
cloud functions test failing and context.params missing from the trigger function,"<p>I am following this tutorial on unit testing firebase functions: <a href=""https://fireship.io/lessons/testing-cloud-functions-in-firebase/"" rel=""nofollow noreferrer"">https://fireship.io/lessons/testing-cloud-functions-in-firebase/</a></p>

<p>I added a unit test for a <code>onCreate</code> realtime database trigger and while the data arrives in it, the <code>context.params</code> come in as empty for the unit test.
so I have</p>

<pre><code>    test('checks that the user gets created', async () =&gt; {
    const userId = 'aaaaaaa';
    const path = `/users/${userId}`;
    const data = {
      ""id"": userId,
      ""firstName"": ""Dan"",
      ""phoneNumber"": ""+11111111111"",
      ""carInfo"": {
        ""color"": ""blue"",
        ""make"": ""Ford"",
        ""model"": ""Focus"",
        ""plate"": ""BV-11-AAA""
      }
    };

    // Create a Database snapshot
    const snap = testEnv.database.makeDataSnapshot(data, path);

    // Execute it
    await wrapped(snap);

    const after = await admin.database().ref(path).once('value');
    const afterValue = after.val();

    expect(afterValue.phoneNumber).toBe('+11111111111')

  });
</code></pre>

<p>and my actual function (<code>index.ts</code>) being:</p>

<pre><code>export const newUserCreated = database.ref('/users/{userId}').onCreate(async (snapshot: DataSnapshot, context) =&gt; {
    console.log('context params : ', context.params);
    const user = snapshot.val();
    await createStripeCustomerHandler(user, snapshot.key);
});
</code></pre>

<p>I get the actual payload in my function's handler, BUT:</p>

<p>There's 2 issues with it:</p>

<ol>
<li>It does not actually perform the save into the database, so the test itself fails (<code>afterValue</code> is null) (might be intended behaviour actually. not sure)</li>
<li>The context params come in as empty when executing the unit test, so it prints out <code>context params :  {}</code>. do I need to send the params for the context manually? from the <code>testEnv.database.makeDataSnapshot</code> command?</li>
</ol>

<p>Am I doing something wrong or am I missing anything?
Thank you in advance.</p>
",https://stackoverflow.com/questions/61928635/cloud-functions-test-failing-and-context-params-missing-from-the-trigger-functio,"['typescript', 'firebase-realtime-database', 'jestjs', 'google-cloud-functions', 'ts-jest']",189,False,2,1
Angular UNIT Testing method with .subscribe misunderstanding,"<p>I start to learn Angular testing recently and faced with a misunderstanding of the UNIT testing concept. 
For example, 
I have a dialog with with 2 buttons: Confirm delete and Cancel. When user click Confirm Delete button the http-service method is called and dialog closes. Sounds simple. Here is the code:</p>

<pre><code>confirmDelete() {
   this.httpService.delete(item)
       .subscribe(() =&gt; this.dialogRef.close(),
                  (err) =&gt; this.message = 'Some text');
} 
</code></pre>

<p>And my test for this function is:</p>

<pre><code>it('should call service delete method and close the dialog', async( () =&gt; {
   spyOn(dialogRef, 'close'); // I have mockDialogRef;
   component.confirmDelete();
   fixture.whenStable().then(() =&gt; {
      fixture.detectChanges();
      expect(deleteSpy.calls.any().toBe(true)); // Spy on delete method
      expect(dialogRef.close).toHaveBeenCalled();
   });
}));
</code></pre>

<p>And it worked fine. Seems to be the delete method has been called and dialog has been closed. But my question is. What we should test in such methods? Should we always test the stuff inside subscribe method or only that service methods is called? And should I Test here the case if server return error? 
So, ..sorry for stupid question, but I'm really confused. Hope you guys will help me(   </p>
",https://stackoverflow.com/questions/61439518/angular-unit-testing-method-with-subscribe-misunderstanding,"['angular', 'unit-testing']",187,False,1,0
Unit testing in Asp.Net Core MVC Web Application,"<p>I am having a hard time figuring out how to do unit testing in my MVC Web App. Although it is not a really hard concept to grasp, I was not able to find out whether I need a specific framework for this or respect some certain steps, given its multi-layered architecture. I would be very glad if you could give me some tips or code snippets so I could have an idea on what I should actually do. I will give you an example from my project:</p>

<p><strong>PhaseController</strong></p>

<pre><code>    public IActionResult Create()
    {

        return View();
    }

    [HttpPost]
    public IActionResult Create(Phase phase)
    {
        int releaseId = (int)TempData[""id""];
        string connectionString = Configuration[""ConnectionStrings:DefaultConnection""];
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sql = ""CreatePhase"";

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                // adding parameters
                SqlParameter parameter = new SqlParameter
                {
                    ParameterName = ""@Name"",
                    Value = phase.Name,
                    SqlDbType = SqlDbType.VarChar,
                    Size = 50
                };
                command.Parameters.Add(parameter);

                parameter = new SqlParameter
                {
                    ParameterName = ""@ReleaseId"",
                    Value = releaseId,
                    SqlDbType = SqlDbType.Int
                };
                command.Parameters.Add(parameter);

                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
        }

        return RedirectToAction(""Index"", ""Phase"", new { id = releaseId });
    }
</code></pre>

<p><strong>Phase Model</strong></p>

<pre><code>namespace Intersection.Models
{
    public class Phase
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int ReleaseId { get; set; }
       // public IEnumerable&lt;Phase&gt; phases { get; set; }
    }
}
</code></pre>

<p>Take these two as an example - how should my test class look like in order to properly test the Create() method (The POST one as well)?</p>

<p><strong>EDIT:</strong></p>

<p>Following @Nkosi's reply, I am adding a different method from another controller:</p>

<pre><code>public IActionResult Create()
    {
        List&lt;Intersection.Models.Environment&gt; environmentList = new List&lt;Intersection.Models.Environment&gt;();

        string connectionString = Configuration[""ConnectionStrings:DefaultConnection""];
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string sql = ""ReadEnvironments"";
            SqlCommand command = new SqlCommand(sql, connection);
            command.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader dataReader = command.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    Intersection.Models.Environment environment = new Intersection.Models.Environment();
                    environment.Id = Convert.ToInt32(dataReader[""Id""]);
                    environment.Name = Convert.ToString(dataReader[""Name""]);
                    environmentList.Add(environment);
                }
            }

            ViewBag.Environments = environmentList;
            return View();
        }
    }

    [HttpPost]
    public IActionResult Create(Application application)
    {
        string connectionString = Configuration[""ConnectionStrings:DefaultConnection""];
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string sql = ""CreateApplication"";

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.StoredProcedure;

                // adding parameters
                SqlParameter parameter = new SqlParameter
                {
                    ParameterName = ""@Name"",
                    Value = application.Name,
                    SqlDbType = SqlDbType.VarChar,
                    Size = 50
                };
                command.Parameters.Add(parameter);

                parameter = new SqlParameter
                {
                    ParameterName = ""@Environment"",
                    Value = application.Environment,
                    SqlDbType = SqlDbType.Int
                };
                command.Parameters.Add(parameter);

                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }
        }

        return RedirectToAction(""Index"", ""Application"");
    }
</code></pre>
",https://stackoverflow.com/questions/59648106/unit-testing-in-asp-net-core-mvc-web-application,"['c#', 'asp.net-mvc', 'unit-testing', 'asp.net-core']",541,True,1,2
gridOptions.api is null when onGridReady event fires after checking gridOptions.api to be defined in unit test,"<p>In my <code>onGridReady</code> event, I'm assigning <code>api</code> to <code>this.gridApi</code>.</p>
<pre><code>private onGridReady(gridReadyEvent: GridReadyEvent): void {
  this.gridApi = gridReadyEvent.api;
}
</code></pre>
<p>I have a method in which I'm using <code>this.gridApi</code>.</p>
<pre><code>public getGridState(): GridState {
    if (this.gridApi) { 
      // code to get state
    }
}
</code></pre>
<p>I'm writing a unit test for <code>getGridState</code>.</p>
<p><strong>Unit test</strong>:</p>
<pre><code>it('should be able to get state of grid', async () =&gt; {
  waitForGridApiToBeAvailable(component.gridOptions, () =&gt; {
    component.getGridState();
  });
});
</code></pre>
<p>So, in order to make sure <code>this.gridApi</code> is defined, I'm using <code>waitForGridApiToBeAvailable</code> mentioned in <a href=""https://www.ag-grid.com/javascript-grid-e2e-test-with-jasmine/#unit-testing"" rel=""nofollow noreferrer"">ag-Grid unit testing doc</a>. So, this would mean when <code>gridOptions.api</code> is defined, <code>this.gridApi</code> would be too, right?</p>
<p><strong>The issue</strong>:</p>
<p>When I run my unit test, it does call <code>component.getGridState()</code> only after <code>component.gridOptions.api</code> is defined but <code>this.gridApi</code> is <code>undefined</code> in <code>getGridState()</code>.</p>
<p>Apart from this, the thing that baffle me more is that <code>onGridReady()</code> is getting called after <code>getGridState()</code> is called and when I consoled <code>this.gridOptions.api</code>, it turned out to be <code>null</code>. How can <code>this.gridOptions.api</code> be <code>null</code> when <code>getGridState()</code> was called from the unit test after it checked <code>component.gridOptions.api</code> to be defined and <code>onGridReady()</code> was called after <code>getGridState()</code>?</p>
<p><strong>Note</strong>: I've tried to explain as much as clearly I could. Let me know if something needs more explanation.</p>
",https://stackoverflow.com/questions/64079167/gridoptions-api-is-null-when-ongridready-event-fires-after-checking-gridoptions,"['angular', 'unit-testing', 'karma-jasmine', 'ag-grid', 'ag-grid-angular']",1023,False,1,0
React - how do I unit test an API call in Jest?,"<p>I have a bunch of API calls that I would like to unit test. As far as I know, unit testing API calls doesn't involve actually making those API calls. As far as I know you would simulate responses of those API calls and then test on the DOM changes however I'm currently struggling to do this. I have the following code:</p>

<p>App.js</p>

<pre><code>function App() {

  const [text, setText] = useState("""");

  function getApiData() {
        fetch('/api')
        .then(res =&gt; res.json())
        .then((result) =&gt; {
          console.log(JSON.stringify(result));
          setText(result); 
        })
      }

  return (
    &lt;div className=""App""&gt;
      {/* &lt;button data-testid=""modalButton"" onClick={() =&gt; modalAlter(true)}&gt;Show modal&lt;/button&gt; */}
      &lt;button data-testid=""apiCall"" onClick={() =&gt; getApiData()}&gt;Make API call&lt;/button&gt;
      &lt;p data-testid=""ptag""&gt;{text}&lt;/p&gt;
    &lt;/div&gt;
  );
}

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

<p>App.test.js</p>

<pre><code>it('expect api call to change ptag', async () =&gt; {
  const fakeUserResponse = {'data': 'response'};
  var {getByTestId} = render(&lt;App /&gt;)
  var apiFunc = jest.spyOn(global, 'getApiData').mockImplementationOnce(() =&gt; {
    return Promise.resolve({
      json: () =&gt; Promise.resolve(fakeUserResponse)
    })
  })


  fireEvent.click(getByTestId(""apiCall""))
  const text = await getByTestId(""ptag"")
  expect(text).toHaveTextContent(fakeUserResponse['data'])
})
</code></pre>

<p>I'm trying to mock the result of getApiData() here and then test a DOM change (the p tag changes to the result). The above code gives me the error:</p>

<blockquote>
  <p>Cannot spy the getApiData property because it is not a function; undefined given instead</p>
</blockquote>

<p>How do I access that class function?</p>

<p>EDIT:</p>

<p>I've adapted the code but I'm still having a bit of trouble:</p>

<p>App.js</p>

<pre><code>function App() {

  const [text, setText] = useState("""");

  async function getApiData() {
        let result = await API.apiCall()
        console.log(""in react side "" + result)
        setText(result['data'])
      }

  return (
    &lt;div className=""App""&gt;
      {/* &lt;button data-testid=""modalButton"" onClick={() =&gt; modalAlter(true)}&gt;Show modal&lt;/button&gt; */}
      &lt;button data-testid=""apiCall"" onClick={() =&gt; getApiData()}&gt;Make API call&lt;/button&gt;
      &lt;p data-testid=""ptag""&gt;{text}&lt;/p&gt;
    &lt;/div&gt;
  );
}

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

<p>apiController.js</p>

<pre><code>export const API = {
    apiCall() {
        return fetch('/api')
        .then(res =&gt; res.json())
    }
}
</code></pre>

<p>Server.js</p>

<pre><code>const express = require('express')
const app = express()
const https = require('https')
const port = 5000

app.get('/api', (request, res) =&gt; {
    res.json(""response"")
})

app.listen(port, () =&gt; console.log(`Example app listening at http://localhost:${port}`))
</code></pre>

<p>App.test.js</p>

<pre><code>import React from 'react';
import { render, shallow, fireEvent } from '@testing-library/react';
import App from './App';
import {API} from './apiController'
//import shallow from 'enzyme'

it('api call returns a string', async () =&gt; {
  const fakeUserResponse = {'data': 'response'};
  var apiFunc = jest.spyOn(API, 'apiCall').mockImplementationOnce(() =&gt; {
    return Promise.resolve({
      json: () =&gt; Promise.resolve(fakeUserResponse)
    })
  })
  var {getByTestId, findByTestId} = render(&lt;App /&gt;)
  fireEvent.click(getByTestId(""apiCall""))
  expect(await findByTestId(""ptag"")).toHaveTextContent('response');
})
</code></pre>

<p>The error I'm getting is</p>

<pre><code>expect(element).toHaveTextContent()

   Expected element to have text content:
     response
   Received:

     14 |   var {getByTestId, findByTestId} = render(&lt;App /&gt;)
     15 |   fireEvent.click(getByTestId(""apiCall""))
   &gt; 16 |   expect(await findByTestId(""ptag"")).toHaveTextContent('response');
        |                                      ^
     17 | })
     18 | 
     19 | // it('api call returns a string', async () =&gt; {

</code></pre>

<p>Reusable unit test (hopefully):</p>

<pre><code>    it('api call returns a string', async () =&gt; {
      const test1 = {'data': 'response'};
       const test2 = {'data': 'wrong'}

      var apiFunc = (response) =&gt; jest.spyOn(API, 'apiCall').mockImplementation(() =&gt; {
        console.log(""the response "" + JSON.stringify(response))
        return Promise.resolve(response)
        })

      var {getByTestId, findByTestId} = render(&lt;App /&gt;)

      let a = await apiFunc(test1);
      fireEvent.click(getByTestId(""apiCall""))
      expect(await findByTestId(""ptag"")).toHaveTextContent('response');
      let b = await apiFunc(test2);
      fireEvent.click(getByTestId(""apiCall""))
      expect(await findByTestId(""ptag"")).toHaveTextContent('wrong');

    })

</code></pre>
",https://stackoverflow.com/questions/61576450/react-how-do-i-unit-test-an-api-call-in-jest,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",46751,True,6,2
Possible collisions of asynchronous unit tests against a test database in Mocha,"<p>I am new to the javascript ecosystem, and I am trying to wrap my head around a decent way to do some basic <strike>unit</strike> testing against the REST API using a stored set of fixtures, i.e. <code>.json</code> files.</p>

<p>My entry point sets up a testing environment by connecting to a test database and emits a <code>ready</code> state.</p>

<pre><code>if (!process.env.TESTING) {
  /* Connect to MongoDB */
  connect(process.env.DEV_DB_HOST, process.env.DEV_DB, () =&gt; app.emit(ready));
  app.on(ready, () =&gt; {
    app.listen(port, () =&gt; console.log(`Listening on port ${port}!`));
  });
} else {
  connect(process.env.TEST_DB_HOST, process.env.TEST_DB, () =&gt; app.emit(ready));
}

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

<p>Once the connection is established, the collection recreated in the test database using fixtures and the tests are executed.</p>

<pre><code>import Paper from '../models/paper.js';

describe('Home Page', () =&gt; {
  before(async() =&gt; {
    await new Promise((resolve, reject) =&gt; {
      app.on(ready, () =&gt; resolve());
    }).then(async() =&gt; {
      try {
        await Paper.collection.drop();
      } catch(error) {
        /* Mongo throws an exception if the collection in question does not exist */
      }
      await Paper.create(fixtures);
    });
  });

  after(async() =&gt; {
    await Paper.collection.drop();
  });

  it('Returns a list of items ordered by date in descending order', async() =&gt; {
    const response = await chai.request(app).get('/');
    expect(response.body).to.have.lengthOf(2);
    expect(response.body).to.be.sortedBy(""date"", { descending: true });
  });
});
</code></pre>

<p>If I replace the <code>before</code> and <code>after</code> hooks with <code>beforeEach</code> and <code>afterEach</code>, since the tests are <code>async</code>, is it possible that the hook gets executed for a test and dumps out the collection before another test, which is using the collection, finishes executing? If so, what is a good way to go about populating a test database with fixtures for each test case?</p>
",https://stackoverflow.com/questions/60591246/possible-collisions-of-asynchronous-unit-tests-against-a-test-database-in-mocha,"['node.js', 'unit-testing', 'express', 'mocha.js']",214,False,1,0
How to unit test NGXS async http request?,"<p>I'm using NGXS in my angular application to manage the state. Now, I'm trying to implement  Unit Tests for NGXS async action. This is what I have implemented so far</p>

<p><strong>schedule.service.ts</strong></p>

<pre><code>public getSchedulesByOrgIdAndJobRefId(orgId: string, jobRefId: string): Observable&lt;Schedule[]&gt; {
    const url = 'http://localhost:5000/api/v1/schedules';
    return this.httpClient.get&lt;Schedule[]&gt;(url);
  }
</code></pre>

<p>and action in <strong>schedule.state.ts</strong></p>

<pre><code>@Action(LoadSchedulesAction)
  loadSchedules({patchState, getState}: StateContext&lt;ScheduleStateModel&gt;,
                         {orgId, jobRefId}: LoadSchedulesAction) {
    return this.scheduleService.getSchedulesByOrgIdAndJobRefId(orgId, jobRefId)
      .pipe(
        map((schedules: Schedule[]) =&gt; { // convert to a map
          return schedules.reduce((prev: EntityMap&lt;string, Schedule&gt;, curr: Schedule) =&gt; {
            prev[curr.id] = curr;
            return prev;
          }, {});
        }),
        tap((schedulesMap: EntityMap&lt;string, Schedule&gt;) =&gt; {
          const existingSchedules = getState().schedules;
          patchState({schedules: {...existingSchedules, ...schedulesMap}});
        })
      );
  }
</code></pre>

<p>This action is working without any issues. When it comes to <strong>Unit testing</strong> there is no documentation or any other article regarding how to test this kind of an <strong>Http async</strong> action.
This is one of my test cases to test that action
<strong>schedule.state.spec.ts</strong></p>

<pre><code>testSchedules = [...Array(5).keys()].map((cd, i: number) =&gt; {
      return {
        orgId,
        containerId: `CCD-${i}`,
        jobRefId,
        jobTitle: `Test Job ${i}`,
      };
    });

describe('Actions', () =&gt; {
    it('should load and schedules for specific job File', async () =&gt; {
      spyOn(scheduleService, 'getSchedulesByOrgIdAndJobRefId')
        .and.returnValue(of(testSchedules));
      await store.dispatch(new LoadSchedulesAction(orgId, jobRefId)).toPromise();
      expect(scheduleService.getSchedulesByOrgIdAndJobRefId).toHaveBeenCalled();
      const scheduleState = store.selectSnapshot((state) =&gt; state.schedulesState);
      // using a util method testSchedules converted to a Map type schedulesMap
      expect(scheduleState.schedules).toEqual(schedulesMap);
    });
  });
</code></pre>

<p>The issue is <strong>scheduleState.schedules</strong> always return en empty object. But if we subscribe to the service call inside <strong>loadSchedules()</strong> function, <strong>scheduleState.schedules</strong> return expected value. But I know we should not subscribe to service call inside en Action implementation</p>

<p>Does anyone know how to Unit Test this kind of action in NGXS?
or am I missing something?</p>
",https://stackoverflow.com/questions/61706233/how-to-unit-test-ngxs-async-http-request,"['angular', 'typescript', 'unit-testing', 'ngxs']",661,True,1,1
Set a custom entry file for Metro dev server in React Native build,"<p>I'm writing some scripts that do custom React Native builds for unit testing and such, specifying a custom entry file for the <code>react-native-xcode.sh</code> script using the <code>ENTRY_FILE</code> env variable. This is super useful and great. I'm able to do release builds no problem, and they work just fine, so basically I can build a RN app from any entry file at will. However, when I try a <code>Debug</code> variant build, metro doesn't seem to know about my special custom entry file, and gives me this error:</p>
<pre class=""lang-js prettyprint-override""><code>None of these files exist:
  * index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
  * index/index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
    at ModuleResolver.resolveDependency (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:165:15)
    at ResolutionRequest.resolveDependency (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)
    at DependencyGraph.resolveDependency (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/node-haste/DependencyGraph.js:285:16)
    at /Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/lib/transformHelpers.js:267:42
    at Server.&lt;anonymous&gt; (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/Server.js:841:41)
    at Generator.next (&lt;anonymous&gt;)
    at asyncGeneratorStep (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/Server.js:99:24)
    at _next (/Users/justin/dev/enmesh/testutilsnative/node_modules/metro/src/Server.js:119:9)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
IN RESOLVER
Error: Unable to resolve module `./index` from ``: 
</code></pre>
<p>Does anyone know how I can get the Debug build of the app to interface properly with the Metro development server, so I can debug my app builds better? Any guidance here would be greatly appreciated!</p>
<p>Metro is just getting launched automatically by the <code>xcodebuild</code> process, which I'm calling like this:</p>
<pre><code>const args = {
  simulator: device,
  configuration: variant,
  scheme,
  projectPath: xcodeProjectPath,
  device: undefined,
  uuid: undefined,
  packager: true,
  verbose: true,
  port: 8081,
  terminal: undefined,
};

const xcodebuildSpawnOptionsArgs: any = {
  ...args,
  cwd: folder,
  env: {
    PLATFORM: 'ios',
    ENTRY_FILE: builtEntryFilePath,
  },
};

const buildProcess = spawn(
  'xcodebuild',
  xcodebuildArgs,
  getProcessOptions(xcodebuildSpawnOptionsArgs),
);
</code></pre>
",https://stackoverflow.com/questions/62489873/set-a-custom-entry-file-for-metro-dev-server-in-react-native-build,"['react-native', 'react-native-ios', 'metro-bundler']",337,False,1,0
Testing conditions on a function&#39;s parameter using testthat,"<p>I have a function of the form <code>func(expr, data.sizes)</code>, where the parameter <code>expr</code> is an expression and the one named <code>data.sizes</code> is ordinarily as the name suggests, a vector or sequence of data sizes. (eg: <code>c(10, 100, 1000)</code> or <code>10^seq(1, 3)</code>) </p>

<p>I would like to write some test-cases for my function's parameters using <code>testthat</code>, but am new to unit-testing in R so I would like to know how does one test conditions for a function's parameter(s) using <code>testthat</code>? </p>

<p>For instance, I want to check for a possible NA value for the parameter <code>data.size</code> in my function and I wrote this snippet to test in my console: (function is available in Global Env.)</p>

<pre class=""lang-r prettyprint-override""><code>test_that(""NA test for data.sizes"", {
  expect_false(is.na(data.sizes %in% func(expression, data.sizes = c(10, 100))))
})
</code></pre>

<p>which throws the error:</p>

<pre><code>* object 'data.sizes' not found
1: expect_false(is.na(data.sizes %in% func(expression, data.sizes = c(10, 
       10)))) at :2
2: quasi_label(enquo(object), label, arg = ""object"")
3: eval_bare(get_expr(quo), get_env(quo))
4: data.sizes %in% func(expression, data.sizes = c(10, 10))
</code></pre>

<p>What might I be possibly doing wrong? Also what would be the syntax in general to apply test conditions on a function's parameters using testthat?</p>
",https://stackoverflow.com/questions/62244007/testing-conditions-on-a-functions-parameter-using-testthat,"['r', 'unit-testing', 'testthat']",357,True,1,2
CRA + Yarn 2 + jsconfig.json = Can&#39;t run unit tests,"<p>I have the following configuration in my <code>jsconfig.json</code> file:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;./src&quot;
  },
  &quot;include&quot;: [&quot;src&quot;]
}
</code></pre>
<p>Which lets me do this:</p>
<pre class=""lang-js prettyprint-override""><code>import { App } from 'components'
import * as actions from 'actions/app.actions'
</code></pre>
<p>Instead of this:</p>
<pre class=""lang-js prettyprint-override""><code>import { App } from '../components'
import * as actions from '../actions/app.actions'
</code></pre>
<p>To get started with unit testing, I've created a simple <code>App.test.jsx</code> in <code>src/components/tests</code></p>
<pre class=""lang-js prettyprint-override""><code>import { render } from '@testing-library/react'
import { App } from 'components'

it('renders without crashing', () =&gt; {
  render(&lt;App /&gt;)
})
</code></pre>
<p>However, when I run <code>yarn test</code> (which is sugar for <code>react-scripts test</code>), it throws with this ugly error:</p>
<pre><code> FAIL  src/components/tests/App.test.jsx
  ● Test suite failed to run

    Your application tried to access components, but it isn't declared in your dependencies; 
this makes the require call ambiguous and unsound.

    Required package: components (via &quot;components&quot;)
    Required by: C:\Users\Summer\Code\sandbox\src\components\tests\

      23714 |     enumerable: false
      23715 |   };
    &gt; 23716 |   return Object.defineProperties(new Error(message), {
            |                                  ^
      23717 |     code: { ...propertySpec,
      23718 |       value: code
      23719 |     },

      at internalTools_makeError (.pnp.js:23716:34)
      at resolveToUnqualified (.pnp.js:24670:23)
      at resolveRequest (.pnp.js:24768:29)
      at Object.resolveRequest (.pnp.js:24846:26)
</code></pre>
<p>It seems like Jest (or Yarn?) thinks <code>components</code> is a node package, because it's not aware of the absolute imports setting in my <code>jsconfig.json</code>. Is there a way to make it aware? Or do I have to choose between 0% coverage and relative imports?</p>
<p>I've tried entering <code>&quot;moduleNameMapper&quot;</code> under <code>&quot;jest&quot;</code> in my <code>package.json</code> like the documentation explains, but it didn't help. I got the same error + one more after it.</p>
<p>I've also tried changing <code>components</code> in the test file to <code>../components</code> but then it complains about <code>actions/app.actions</code> which is inside the <code>&lt;App /&gt;</code> component.</p>
<p>Module name mapper config:</p>
<pre class=""lang-json prettyprint-override""><code>/* package.json */
{
  /* ... */
  &quot;jest&quot;: {
    &quot;moduleNameMapper&quot;: {
      &quot;actions(.*)$&quot;: &quot;&lt;rootDir&gt;/src/actions$1&quot;,
      &quot;assets(.*)$&quot;: &quot;&lt;rootDir&gt;/src/assets$1&quot;,
      &quot;components(.*)$&quot;: &quot;&lt;rootDir&gt;/src/components$1&quot;,
      &quot;mocks(.*)$&quot;: &quot;&lt;rootDir&gt;/src/mocks$1&quot;,
      &quot;pages(.*)$&quot;: &quot;&lt;rootDir&gt;/src/pages$1&quot;,
      &quot;reducers(.*)$&quot;: &quot;&lt;rootDir&gt;/src/reducers$1&quot;,
      &quot;scss(.*)$&quot;: &quot;&lt;rootDir&gt;/src/scss$1&quot;,
      &quot;store(.*)$&quot;: &quot;&lt;rootDir&gt;/src/store$1&quot;,
      &quot;themes(.*)$&quot;: &quot;&lt;rootDir&gt;/src/themes$1&quot;,
      &quot;api&quot;: &quot;&lt;rootDir&gt;/src/api.js&quot;,
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/64874872/cra-yarn-2-jsconfig-json-cant-run-unit-tests,"['jestjs', 'create-react-app', 'yarnpkg-v2', 'vscode-jsconfig']",716,True,1,1
Unit testing Rust Syn crate,"<p>From the <a href=""https://lib.rs/crates/syn"" rel=""nofollow noreferrer"">Syn documentation</a>:</p>
<blockquote>
<p>Syn operates on the token representation provided by the <code>proc-macro2</code> crate from crates.io rather than using the compiler's built in <code>proc-macro</code> crate directly. This enables code using <code>Syn</code> to execute outside of the context of a procedural macro, such as in unit tests or <code>build.rs</code></p>
</blockquote>
<p>I am trying to enable unit testing for some Syn functions, however I can't get it to work no matter what I have tried. It does not work with the <code>proc_macro2::TokenStream</code> type, but it won't work with the <code>proc_macro::TokenStream</code> because we are not in a proc-macro context.</p>
<p><a href=""https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=79269a1175339b97213f28f3fa25a06d"" rel=""nofollow noreferrer"">link to playground</a></p>
<pre class=""lang-rust prettyprint-override""><code>use quote::quote;
use syn;

fn test() {
    // let stream: syn::export::TokenStream = quote!{fn foo() {};}.into(); // doesn't work
    let stream: proc_macro2::TokenStream = quote!{fn foo() {};}.into(); // doesn't work
    // let item = parse_macro_input!(stream as Item); // doesn't work
    let item = syn::parse(stream).unwrap();

}

fn main() {
    test();
}

</code></pre>
<p>Any help on how to test syn functions outside of the proc-macro context would be appreciated. I am aware of the <a href=""https://docs.rs/trybuild/1.0.35/trybuild/"" rel=""nofollow noreferrer"">trybuild</a> crate, but I would like to be able to unit test the macro's functions first.</p>
",https://stackoverflow.com/questions/65269173/unit-testing-rust-syn-crate,"['unit-testing', 'parsing', 'rust', 'rust-macros', 'rust-proc-macros']",828,True,1,1
How to mock parameterized method in codeception framework,"<p>I have one parameterized method which accept string parameter and returns data upon passed param. I am using codeception framework for writing unit testing for php-zend project.</p>

<p>Method: <code>getDataByView($view)</code>  <code>$view</code> can be default, all.</p>

<p>So I want mock this method such way it behave &amp; return result based on passed params. I didnt get way in codeception framework so used phpunit code for that. But getting problems in that. </p>

<pre><code>$map = array(
            array('default', $default),
            array('all', $all)
        );

$mock = $this-&gt;getMockBuilder('ViewTable')
        -&gt;setMethods(['getDataByView'])
        -&gt;disableOriginalConstructor()
        -&gt;getMock();

$mock-&gt;expects($this-&gt;any())
        -&gt;method('getDataByView')
        -&gt;will($this-&gt;returnValueMap($map));
</code></pre>

<p>Actually this code work as per my expectation. Since I am using <code>setMethods()</code> it calls the ViewTable class constructor. If I dont use <code>setMethods</code> then It doesn't call constructor. </p>

<p><strong>Problems:</strong></p>

<ul>
<li>I want to mock only one method of class, so I have used
<code>setMethods()</code> but it calls mock class constructor. I dont want that.
How can it be solved in phpunit.</li>
<li>How to mock parameterized method in codeception framework.</li>
</ul>
",https://stackoverflow.com/questions/61996274/how-to-mock-parameterized-method-in-codeception-framework,"['unit-testing', 'zend-framework2', 'codeception', 'phpunit']",405,False,1,0
How to run tests on AWS instance using Teamcity?,"<p><br>
I'm working on a C#/C++ project that need specific hardware architecture, therefore, event for unit testing, I can't run them in a standard docker; I need to use a specific AWS EC2 instance.<br>
My current build steps are the following one:<br>
Build Step 1: Teamcity is making the build in a local docker.<br>
Build Step 2: Teamcity is uploading the the artifacts on S3.<br>
Build Step 3: Teamcity is launching a specific AWS EC2 instance.<br>
<br>
Now I want to tell Teamcity to run the tests on this specific instance and still following the progress of the tests to be able to send alerts.<br>
Or, at least, I can manage the testing execution at instance Startup, then need information on the output format to send to Teamcity.<br>
<br>
Regards</p>
",https://stackoverflow.com/questions/62385623/how-to-run-tests-on-aws-instance-using-teamcity,"['amazon-web-services', 'testing', 'teamcity', 'instance']",78,False,1,0
how to create test suite as in junit 4 using Junit5,"<p>as we are upgrading to junit5 from junit4 for unit testing purpose, i couldn't able to find solution to creating a test suite in junit5 like in junit4 :
below is the our junit4 suite class :</p>
<pre><code>@RunWith(Suite.class)
@SuiteClasses({ 
    ClassA.class, 
    ClassB.class, 
    ClassC.class 
    } )
public class TestSuite {

}
</code></pre>
<p>The Code i tried after searching around is below :</p>
<pre><code>@RunWith(JUnitPlatform.class)

@SelectClasses( { 
    OrderAnnotationAlphanumericExperiment.class, 
    orderAnnotationExperiment.class, 
    ParameterizedAnnotation.class 
    } )
public class TestSuite {
    

}
</code></pre>
<p>on searching for the solution, most of them were providing a solution of using the same test suite to run it using vintage api, but what am looking for is to create test suite in junit 5.</p>
<p>Few suggesting <em>@ExtendsWith(SpringExtension.class)</em>, but there is also less documentation for it, couldn't able to find a solution to create a suite in junit 5</p>
<p>few blogs/question/sites i referred :</p>
<p><a href=""https://stackoverflow.com/questions/50485339/create-testsuite-in-junit5-eclipse"">Create TestSuite in JUnit5 (Eclipse)</a>
<a href=""https://stackoverflow.com/questions/50565724/are-test-suites-considered-deprecated-in-junit5"">Are test suites considered deprecated in JUnit5?</a>
<a href=""https://howtodoinjava.com/junit5/junit5-test-suites-examples/"" rel=""noreferrer"">https://howtodoinjava.com/junit5/junit5-test-suites-examples/</a></p>
<p>some one help me out to solve this problem.</p>
",https://stackoverflow.com/questions/62710978/how-to-create-test-suite-as-in-junit-4-using-junit5,"['java', 'spring-boot', 'junit', 'junit5', 'junit-runner']",1752,True,5,1
How to Unit Test Exception Handler Middleware,"<p>I am trying to use a custom error handler to return properly formatted exceptions for my .NET Core 3 API. The handler works great, the issue I'm having is with regards to writing proper unit tests to test the handler. I registered the middleware for this like so:</p>

<pre><code>    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IEnvService envService)
    {
        if (envService.IsNonProductionEnv())
        {
            app.UseExceptionHandler(""/Error-descriptive"");
        }
        else
        {
            app.UseExceptionHandler(""/Error"");
        }

        ...

     }
</code></pre>

<p>Here is the code for the 'Error Descriptive' endpoint:</p>

<pre><code>    public IActionResult ErrorDescriptive()
    {
        if (!_env.IsNonProductionEnv())            
            throw new InvalidOperationException(""This endpoint cannot be invoked in a production environment."");

        IExceptionHandlerFeature exFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();

        return Problem(detail: exFeature.Error.StackTrace, title: exFeature.Error.Message);
     }
</code></pre>

<p>The issue I'm dealing with specifically is this line:</p>

<pre><code>IExceptionHandlerFeature exFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();
</code></pre>

<p>I'm having trouble getting this to work from a unit testing perspective, because (as far as I know) this line of code gets the most recent exception from the server. Is there a way I can somehow set the exception it gets from the HttpContext within my test? Also, since this is using HttpContext, do I somehow need to incorporate a mocked version of that as well, such as DefaultHttpContext? </p>
",https://stackoverflow.com/questions/60288329/how-to-unit-test-exception-handler-middleware,"['c#', 'unit-testing', 'asp.net-core', 'asp.net-core-webapi']",6788,True,5,1
Why is my unit test case missing the if statements to cover in python?,"<p>I have written a test case for a function. The function basically returns an output whose content type is a text/csv. Upon running the command <code>python3 -m pytest --cov-report term-missing --cov=projfolder/</code> I get the lines which are being missed and those are all in the if statements.
My understanding of the issue is that the testcase passes but misses the statements which are in the if loop. Look at this example
func.py</p>
<pre><code>@process_bp.route(&quot;/getListCSV&quot;)
def get_list_csv():

    companies_flask_list = db.session.query(Companies, LeadsStatus).join(LeadsStatus,
                                                                         Companies.id == LeadsStatus.company_id)

    industry_sele = &quot;All&quot;
    country_sele = &quot;UK&quot;
    size_sele = &quot;All&quot;

    filters = {'open': True, 'assign': True, 'closed': True}

    status_list = ['open', 'allocated', 'converted', 'not converted']

    if 'industry' in request.form:
        industry_sele = request.form['industry']
        country_sele = request.form['country']
        size_sele = request.form['size']

        if not request.form.get('open'):
            filters['open'] = False
            if 'open' in status_list:
                status_list.remove('open')
        if not request.form.get('assign'):
            filters['assign'] = False
            if 'allocated' in status_list:
                status_list.remove('allocated')
        if not request.form.get('closed'):
            filters['closed'] = False
            if 'converted' in status_list:
                status_list.remove('converted')
            if 'not converted' in status_list:
                status_list.remove('not converted')

    if 'industry' in request.args:
        industry_sele = request.args.get('industry')
        country_sele = request.args.get('country')
        size_sele = request.args.get('size')

        if request.args.get('open') == 'False':
            filters['open'] = False
            if 'open' in status_list:
                status_list.remove('open')

        if request.args.get('assign') == 'False':
            filters['assign'] = False

            if 'allocated' in status_list:
                status_list.remove('allocated')

        if request.args.get('closed') == 'False':
            filters['closed'] = False
            if 'converted' in status_list:
                status_list.remove('converted')
            if 'not converted' in status_list:
                status_list.remove('not converted')
</code></pre>
<p>All these lines (which are inside each if statements are missing). Look at my way of unit testing this function. test_func.py</p>
<pre><code>    def test_get_list_csv_manager(self):
        with self.client.session_transaction() as session:
            session['role'] = 'manager'
            session['id'] = 2
        res = self.client.get(&quot;/getListCSV&quot;, follow_redirects=True)
        self.assertEqual(res.status_code, 200)
</code></pre>
<p>How should I write the testcase so that these if statements would be covered in these? I am stuck like a bee on this issue since 5days and I have no help or luck whatsoever.</p>
<p><strong>EDIT</strong>: Here is how I tried it the other way around.</p>
<pre><code>    def test_get_list_csv_form_requests(self):
        with self.client.session_transaction() as session:
            session['role'] = 'manager'
            session['id'] = 2

            mock_request_data = {
                'industry_sele': 'Compliance',
                'country_sele': 'UK',
                'size_sele': '5000'
            }
        res = self.client.get(&quot;/getListCSV&quot;, data=json.dumps(mock_request_data),follow_redirects=True)
        self.assertEqual(res.status_code, 200)
</code></pre>
",https://stackoverflow.com/questions/65503462/why-is-my-unit-test-case-missing-the-if-statements-to-cover-in-python,"['python', 'unit-testing', 'python-unittest']",679,True,-1,1
Dependency Injection on Arrow KT,"<p>In <a href=""https://arrow-kt.io/docs/patterns/dependency_injection/"" rel=""nofollow noreferrer"">Arrow Kt Documentation on Dependency Injection</a>, the dependency is defined at the ""Edge of the World"" or in Android could be an <code>Activity</code> or a <code>Fragment</code>. So the given example is as follow:</p>

<pre><code>import Api.*

class SettingsActivity: Activity {
  val deps = FetcherDependencies(Either.monadError(), ActivityApiService(this))

  override fun onResume() {
    val id = deps.createId(""1234"")

    user.text =
      id.fix().map { it.toString() }.getOrElse { """" }

    friends.text =
      deps.getUserFriends(id).fix().getOrElse { emptyList() }.joinToString()
  }
}
</code></pre>

<p>But now I'm thinking how could the <code>SettingsActivity</code> in the example could be <code>unit tested</code>? Since the dependency is created within the activity, it could no longer be changed for testing?</p>

<p>When using some other <code>Dependency Injection</code> library, this dependency definition is create outside of the class it will be used on. For example in <code>Dagger</code>, a <code>Module</code> class is created to define how the objects (dependencies) are created and an <code>@Inject</code> is used to ""inject"" the dependency defined inside the module. So now when unit testing the <code>Activity</code>, I just have to define a different module or manually set the value of the dependency to a mock object.</p>
",https://stackoverflow.com/questions/60830948/dependency-injection-on-arrow-kt,"['android', 'dependency-injection', 'arrow-kt']",276,True,0,1
Creating pytest plugins,"<p>I use pytest for unit testing my code. In regards to that, I was trying to create a pytest plugin that could be used throughout my directory. I could either create a conftest.py file in the main root directory or create an installable pytest plugin. I prefer the second option.</p>
<p>However, the pytest documentation does give a good guide on how to proceed with creating and installing a user defined plugin. I created the setup.py in the parent directory to the directory in which my conftest.py exists. My setup.py looked as follows:</p>
<pre><code>from setuptools import setup

setup(
    name=&quot;tryplugin&quot;,
    packages = ['pluginTry'],
    version = &quot;1.0.0&quot;,

    # the following makes a plugin available to pytest
    entry_points = {
        'pytest11': [
            'name_of_plugin = pluginTry',
        ]
    },
    classifiers=[&quot;Framework :: Pytest&quot;],
)
</code></pre>
<p>Next I run the command:
<code>python3 setup.py install</code></p>
<p>My plugin then appears on <code>pytest list</code></p>
<p>However, the command line pytest option which my conftest.py creates does not appear in <code>pytest -h</code>. Nor does my fixtures come on <code>pytest --fixtures</code></p>
<p>Rather, I get the following error:</p>
<pre><code>During handling of the above exception, another exception occurred:
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/py/_path/local.py:718: in pyimport
    issame = self.samefile(modfile)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/py/_path/local.py:204: in samefile
    return py.error.checked_call(
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/py/_error.py:86: in checked_call
    raise cls(&quot;%s%r&quot; % (func.__name__, args))
E   py.error.ENOTDIR: [Not a directory]: samefile('/Users/myName/Desktop/MainDirectory/pluginTry/conftest.py', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tryplugin-1.0.0-py3.8.egg/pluginTry/conftest.py')
</code></pre>
",https://stackoverflow.com/questions/62986126/creating-pytest-plugins,"['python', 'plugins', 'pytest', 'setup.py']",719,False,0,0
Laravel Unit Test Illegal Offset Type,"<p>I'm currently trying to understand unit testing in Laravel and I'm trying to see if I can branch off from a tutorial I found by adding an option to have a <code>/posts</code> route that displays all of the posts in a grid but I've come across an error and I'm having trouble understanding where it's going wrong.</p>
<p>ViewABlogPostTest.php</p>
<pre><code>public function testSeeAllPosts()
    {
        $response = $this-&gt;get(&quot;/posts&quot;);

        $response-&gt;assertStatus(200);
    }
</code></pre>
<p>When running it I get the following error:</p>
<p>1 ) Tests\Feature\ViewABlogPostTest::testSeeAllPosts
ErrorException: Illegal offset type</p>
<p>web.php Route:</p>
<pre><code>Route::get('/posts', 'PostController@all');
</code></pre>
<p>PostController all function:</p>
<pre><code>public function all(){
      $posts = Post::all();

      return view('all-posts')-&gt;with($posts, 'posts');
    }
</code></pre>
<p>all-posts.blade.php:</p>
<pre><code>This page is supposed to show all of the posts in the db
@foreach($posts as $post)
&lt;p&gt;{{ $post-&gt;id }} | {{ $post-&gt;title }} | {{ $post-&gt;body }}&lt;/p&gt;
@endforeach
</code></pre>
<p>I've tried to look into passing arrays into views and this should be how I do it but I don't understand what this error means and searching it doesn't make sense, did I do the post incorrectly? or is there another way I'm supposed to pass array data to the view?</p>
",https://stackoverflow.com/questions/63286210/laravel-unit-test-illegal-offset-type,['laravel'],292,False,0,1
How do I unit test functional code? (not OOP),"<p>I'm working in a hybrid environment. Some sections are procedurally written, some are object oriented, some follow the functional paradigm.</p>
<p>As we refactor code, we're implementing unit tests to all of our code as we come across it, and I'm currently in a functional area of code. However, all instruction I've ever seen for phpunit is about testing methods inside of objects and classes.</p>
<p>I've <em>heard</em> it's easier to do unit testing on functional code, but have never seen an example. How do you test functional code using phpunit?</p>
<p>For example, if I have a function</p>
<pre><code>function foo($bar, $baz){
 if (!isset($bar[&quot;foo&quot;]){
   return false;
 }
 return foobar($bar[&quot;foo&quot;], $baz);
}
</code></pre>
<p>And I currently have a test.php that looks like this:</p>
<pre><code>&lt;?php 
declare(strict_types=1);
require(&quot;../backend/foo.php&quot;);
use PHPUnit\Framework\Testcase;
final class functionTest extends TestCase{
   public function testTheFooFunction(): void{
      // ???? 
   }
}
</code></pre>
<p>What would a unit test for this function, using phpunit, look like? Am I even on the right track with my test.php?</p>
",https://stackoverflow.com/questions/63731926/how-do-i-unit-test-functional-code-not-oop,"['php', 'functional-programming', 'phpunit']",403,True,-1,1
Visual Studio Test Explorer - GTest with CMake and remote build,"<p>I have a C++ linux project, developed on Windows with VS2019 and deployed to a remote build machine.
<br>I am trying to set up unit testing with googletest.
<br>I have created an example project using CMake and am able to get my tests to run on the remote build machine, but I would like for them to appear in the VS Test Explorer.</p>
<p>I have tried the suggetions from <a href=""https://stackoverflow.com/questions/53583286"">this thread</a>, but I think they are for Windows deployment and they did not work for me.</p>
<p>Is it possible to discover tests from a project deployed to linux and if so, how?</p>
<p>My project directory is set up like this:</p>
<pre><code>ExampleProject
|  CMakeLists.txt
|  CMakeLists.txt.in
|  main.cpp
|__src
   |  CMakeLists.txt
   |  example.cpp
   |  example.h
|__test
   |  CMakeLists.txt
   |  example_add.cpp
</code></pre>
<p>The outer CMakeLists.txt is set up like this:</p>
<pre><code>cmake_minimum_required(VERSION 3.5)

# set the project name
project(ExampleProject)

set(CMAKE_CXX_FLAGS, &quot;${CMAKE_CXX_FLAGS} -std=c++11&quot;)

# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G &quot;${CMAKE_GENERATOR}&quot; .
    RESULT_VARIABLE result
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if (result)
    message(FATAL_ERROR &quot;CMake step for googletest failed: ${result}&quot;)
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
    RESULT_VARIABLE result
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if (result)
    message(FATAL_ERROR &quot;Build step for googletest failed: ${result}&quot;)
endif()

# Prevent overriding the parent project's compiler/linker
# settings on Windows
set(gtest_force_shared_crt ON CACHE BOOL &quot;&quot; FORCE)

# Add googletest directly to our build. This defines
# the gtest and gtest_main targets.
add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
                 ${CMAKE_CURRENT_BINARY_DIR}/googletest-build
                 EXCLUDE_FROM_ALL)

# The gtest/gtest_main targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later. Otherwise we have to add them here ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
    include_directories(&quot;${gtest_SOURCE_DIR}/include&quot;)
endif()

add_subdirectory(src)

enable_testing()
add_subdirectory(tests)

# add the executable
add_executable(ExampleProject main.cpp)
</code></pre>
<p>CMakeLists.txt.in is copied from googletest:</p>
<pre><code>cmake_minimum_required(VERSION 2.8.2)

project(googletest-download NONE)

include(ExternalProject)
ExternalProject_Add(googletest
    GIT_REPOSITORY    https://github.com/google/googletest.git
    GIT_TAG           master
    SOURCE_DIR        &quot;${CMAKE_CURRENT_BINARY_DIR}/googletest-src&quot;
    BINARY_DIR        &quot;${CMAKE_CURRENT_BINARY_DIR}/googletest-build&quot;
    CONFIGURE_COMMAND &quot;&quot;
    BUILD_COMMAND     &quot;&quot;
    INSTALL_COMMAND   &quot;&quot;
    TEST_COMMAND      &quot;&quot;
)
</code></pre>
<p>The CMakeLists.txt for src is:</p>
<pre><code>add_library(example example.cpp)
target_include_directories(example PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
</code></pre>
<p>And the CMakeLists.txt for test is:</p>
<pre><code>add_executable(ExampleTest example_add.cpp)
target_link_libraries(ExampleTest gtest gtest_main example)
add_test(ExampleTest ExampleTest)
</code></pre>
",https://stackoverflow.com/questions/63778979/visual-studio-test-explorer-gtest-with-cmake-and-remote-build,"['visual-studio', 'cmake', 'visual-studio-2019', 'googletest']",1886,True,0,1
How do I write regression tests for a library built with webpack?,"<p>I'm thinking of building our code with Webpack and babel, so we can mix ES6 dependencies with pre-existing AMD dependencies, and also continue supporting IE11, due to business requirements. </p>

<p>Our regression tests are essentially:</p>

<ul>
<li>one javascript test file for unit testing each class</li>
<li>one HTML file for each custom element, with a javascript file to run WebDriver tests against it</li>
</ul>

<p>This works well with Intern, where you just list all the javascript test files in your Intern configuration.  But it doesn't sound practical with Webpack, because it effectively makes hundreds of entry points.</p>

<p>Is the solution just to have a test-index.js type file that requires (i.e. includes) all the test javascript files, and then combine all the HTML test files into a single Storybook type ""app""?  Or is there something simpler?</p>
",https://stackoverflow.com/questions/60021887/how-do-i-write-regression-tests-for-a-library-built-with-webpack,"['webpack', 'intern']",76,True,0,1
How to replace a dll library for unit testing in C# Visual Studio?,"<p>I have developed a plug-in that uses a dll from a third party (third_party.dll). I have created unit tests for this plug-in, but I cannot run them using the third_party.dll, because it requires the application running.</p>

<p>I have created a dll (my_mock_up.dll) that simulates the API of the third_party.dll</p>

<p>To run the tests copy the source code to the unit test project and replace the occurrences of </p>

<pre><code>using ThirdParty.XXX.YYY.ZZZ
</code></pre>

<p>with</p>

<pre><code>using MyMockUp.XXX.YYY.ZZZ
</code></pre>

<p>but the process is manual and not very efficient. What would be a better approach? Is there a way to run unit tests for a plug-in with the host application running? Does VisualStudio have a functionality or a package for it? I could modify the code of the plug-in to accommodate the unit testing if that is also an option.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/60305277/how-to-replace-a-dll-library-for-unit-testing-in-c-visual-studio,"['c#', 'visual-studio', 'unit-testing', 'dll']",171,False,0,0
Function which one must not shadow in Matlab,"<p>I am writing some helper functions for unit testing in Matlab. For that I need to overload Matlab functions, built-ins etc. In the documentation is written, that one shall not overload the function <code>builtin</code>. I also found out that one must not overload the <code>lt</code> operator, since it seems to get called by the UI all the time.</p>
<p>Is there a list of functions which one shall not overload, or do you know of any particular problems from overloading some specific functions?</p>
<p>Further Information:
My use case: I want to do mutation-testing and faul-injection.
in ther words, sometimes the called functions shall return wrong results or throw an error. If I overload the Matlab functions, I do not have to change the source code to do that.</p>
",https://stackoverflow.com/questions/64432551/function-which-one-must-not-shadow-in-matlab,"['matlab', 'overloading']",62,False,0,0
How can I capture/handle client-side window.location changes in HtmlUnit?,"<p>I'm using <strong>HtmlUnit</strong> to unit test a jQuery-based application that makes heavy use of JavaScript, including client-side changes to <code>window.location</code>. For example, I might have an <code>onClick</code> event for a button similar to:</p>
<pre><code>var newUrl = window.location + &quot;?someParam=blah&quot;;
window.location.assign(newUrl);
</code></pre>
<p>(A bit more complicated than that, since the code deals with whether the param already exists. Trying to simplify for this example.) Then in my unit testing code, I might do:</p>
<pre><code>HtmlPage newPage = buttonObject.click();
webClient.waitForBackgroundJavaScript(60000);
String url = newPage.geturl().toString(); // always the original URL, not the new one
</code></pre>
<p>It never seems to load the new page; the <code>window.location</code> changes seem to just get ignored. I've read some posts on the interwebs saying that HtmlUnit just doesn't support client-side <code>window.location</code> changes, and other posts indicating that it can be &quot;hacked,&quot; but I haven't found out how to hack it.</p>
<p>Does HtmlUnit support <code>window.location</code> changes, or does anyone have an example of where they've hacked it to make it work?</p>
",https://stackoverflow.com/questions/62762454/how-can-i-capture-handle-client-side-window-location-changes-in-htmlunit,"['javascript', 'htmlunit']",219,False,0,2
Catching errors on actor construction in Akka TestKit,"<p>I am trying to learn unit testing with Akka.</p>
<p>I have a situation where one of my tests was throwing an exception on construction and was wondering what the best way to capture this and log or otherwise throw it would be. As it stands now I had to attach a debugger and see where it threw.</p>
<p>I thought that I could perhaps create another actor which does logging and, on error, have a message sent to it. Breakpoints I put in the ErrorActor were never hit though. It seems as though the RootActor failed and timed out before the message was sent / received.</p>
<p>Is there something I'm doing wrong here or am I fundamentally off base with this? What is the the recommended way to catch errors in unit tests?</p>
<p>Thanks very much</p>
<pre><code>    [Fact]
        public void CreateRootActor()
        {
            // Arrange
            var props = Props.Create(() =&gt; new RootActor());
            Sys.ActorOf(Props.Create( () =&gt;new TestErrorActor(TestLogger)), ActorPaths.ErrorActor.Name); // register my test actor
            
            // Act
            var actor = new TestActorRef&lt;RootActor&gt;(this.Sys, props);

            // Assert
            Assert.IsType&lt;RootActor&gt;(actor.UnderlyingActor);
        }



   public class RootActor : ReceiveActor
    {

         private ITenantRepository tenantRepository;

        public RootActor(ILifetimeScope lifetimeScope)
        {
            try
            {
                this.tenantRepository = lifetimeScope.Resolve&lt;ITenantRepository&gt;(); // this throws

            }
            catch (Exception e)
            {
                Context.ActorSelection(ErrorActor.Name).Tell(new TestErrorActor.RaiseError(e));
                throw;
            }
            .... 
</code></pre>
",https://stackoverflow.com/questions/63243277/catching-errors-on-actor-construction-in-akka-testkit,['akka.net'],57,False,0,1
Call init inside of an array struct,"<p>In the old version of the data that I got from Json, <code>Pause</code> data was not in an array, so I used this line of code to do the unit testing:</p>

<pre><code>let pause = Pause(attached: [PauseModel(range: 40 ..&lt; 305)])
</code></pre>

<p>Then </p>

<pre><code>let data = Data(pause: pause)
try lits.process(data: data)
</code></pre>

<p>The <code>pause</code> in <code>let data = Data(pause: pause)</code> is type of <code>Pause</code> struct (its struct is copied below). But I divided to <code>Pause</code>structs to two structs (First one can be considered as a root (under the named of <code>Pause</code>):</p>

<pre><code>public struct Pause: Decodable {

   public let pause: [PauseData]

   private enum CodingKeys: String, CodingKey {
      case lists
      case pause
   }

   public init(from decoder: Decoder) throws {
      let series = try decoder.container(keyedBy: CodingKeys.self).nestedContainer(keyedBy: CodingKeys.self, forKey: .lists)
      breaks = try series.decode([pauseData].self, forKey: .pause)
   }
}
</code></pre>

<p>As you can see <code>PauseData</code> is inside an array. </p>

<pre><code>public struct PauseData: Decodable {

   public let attached: [PauseModel]

   init(attached: [PauseModel] = []) {
      self.attached = attached
   }

   private enum CodingKeys: String, CodingKey {
      case attached = ""attached""
   }
}
</code></pre>

<p>So I need to write this line again:</p>

<pre><code>let pause = Pause(attached: [PauseModel(range: 40 ..&lt; 305)])
</code></pre>

<p>I can simply do it like that:</p>

<pre><code>let pause = PauseData(attached: [PauseModel(range: 40 ..&lt; 305)])
</code></pre>

<p>but the <code>let pause</code> should be a type of <code>Pause</code> struct. So Somehow I need re-write this line to be the type of <code>Pause</code> struct and also I can call the init  <code>init(attached: [PauseModel] = [])</code>. I can be appreciated if anyone can help me on that.</p>

<p>Thank you so much</p>
",https://stackoverflow.com/questions/59557494/call-init-inside-of-an-array-struct,"['arrays', 'swift', 'struct']",49,True,0,1
Best Practice : Seconds Since datetime when datetime is empty or null,"<p>I feel this question is language agnostic, but I will use PHP for my example</p>
<pre class=""lang-php prettyprint-override""><code>
abstract class myUserClass {
  private $last_visit = null;

  abstract getLastVisit() ?string;
  abstract secondsSinceLastVisit() int;

}

</code></pre>
<p>Lets say you have some datetime (like a last_visit) property on an object</p>
<p><code>last_visit</code> = <code>2020-10-10 09:25:25</code></p>
<p><code>last_visit</code> can be a string representation of the datetime OR <code>null</code> of user has never visited</p>
<p>And then you have a method like <code>secondsSinceLastVisit() : int</code></p>
<p>And this function returns an <code>int</code> representing the number of seconds SINCE <code>last_visit</code></p>
<p>What would be the best practice for returning when <code>last_visit</code> is null?</p>
<p>We could:
return <code>null</code> which means this is undefined
Return <code>some_really_large_number</code> meaning - a long time ago
Something else???</p>
<p>I ran into trouble doing this</p>
<pre class=""lang-php prettyprint-override""><code>
if( !$user-&gt;secondsSinceLastVisit() )
{
 //user has never visited
}

</code></pre>
<p>This failed during some unit testing when <code>secondsSinceLastVisit()</code> returned zero! <code>0</code></p>
<p>So, I changed by test to <code>is_null( $user-&gt;secondsSinceLastVisit() )</code> which solves this problem</p>
<p>My question is general in nature - What is a good practice here for the return value of <code>secondsSinceLastVisit()</code> when <code>last_visit</code> is null?</p>
",https://stackoverflow.com/questions/63959495/best-practice-seconds-since-datetime-when-datetime-is-empty-or-null,"['php', 'datetime', 'return-value', 'return-type']",67,True,0,1
Python unittest: Unable to mock imported functions so that conditional evaluates to False,"<p>I'm encountering a problem with unit testing in Python. Specifically, when I try to mock a function my code imports, variables assigned to the output of that function get assigned to a MagicMock object instead of the mock-function's return_value. I've been digging through the docs for python's unittest library, but am not having any luck.</p>

<p>The following is the code I want to test:</p>

<pre><code>from production_class import function_A, function_B, function_M

class MyClass:
    def do_something(self):
        variable = functionB()
        if variable:
            do_other_stuff()
        else:
            do_something_else
</code></pre>

<p>this is what I've tried:</p>

<pre><code>@mock.patch(path.to.MyClass.functionB)
@mock.patch(&lt;other dependencies in MyClass&gt;)
def test_do_something(self, functionB_mock):
    functionB_mock.return_value = None # or False, or 'foo' or whatever.
    myClass = MyClass()
    myClass.do_something()
    self.assertTrue(else_block_was_executed)
</code></pre>

<p>The issue I have is that when the test gets to <code>variable = functionB</code> in MyClass, the variable doesn't get set to my return value; it gets set to a MagicMock object (and so the if-statement always evaluates to True). How do I mock an imported function such that when executed, variables actually get set to the return value and not the MagicMock object itself?</p>
",https://stackoverflow.com/questions/61144986/python-unittest-unable-to-mock-imported-functions-so-that-conditional-evaluates,"['python', 'unit-testing', 'if-statement', 'mocking', 'magicmock']",2258,True,0,2
How to customize DateTime format for AutoFixture?,"<p>I currently have a Model class Product:</p>
<pre><code>public class ProductModel
{ 
  public string? ProductName{ get; set; }
  public DateTime ExpiryDate { get; set; }
}
</code></pre>
<p>I am using XUnit and AutoFixture for unit testing:</p>
<p>Below is my test method:</p>
<pre><code>[Theory, AutoData]
public async Task SaveProduct_ShouldSaveProductToDatabase(ProductModel productModel)
{
  var expiry = productModel.ExpiryDate; // 2020-03-17 03:01:27.2166623
  ... implementation to save to database
}
</code></pre>
<p>Autofixture is used to autogenerate the date and this is set to 2020-03-17 03:01:27.2166623. Is there a way to customize ProductModel to return a model property in a specific format. For instance I want date returned to be set as 2020-03-17 03:01:27 (Without milliseconds).</p>
<p>I have searched for examples and found one that retrieves specific dates:</p>
<pre><code>public class AllProducts2020: ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customize&lt;ProductModel&gt;(composer =&gt;
        composer.With(p =&gt; p.ExpiryDate, new DateTime(2020, 1, 1)));
    }
}
</code></pre>
<p>The above actually returns all product where date year is 2020. I want to use the Custom class like above, except that I return all products with dateformat like this:2020-03-17 03:01:27 (Without milliseconds)</p>
<p>Any hint of how this can be achieved?</p>
",https://stackoverflow.com/questions/65005972/how-to-customize-datetime-format-for-autofixture,"['c#', 'xunit', 'autofixture']",1084,False,0,1
How to inject data imported by Firestore emulator into db instance,"<p>I know that we can now <a href=""https://stackoverflow.com/a/61501928"">export and import data</a> with the Firestore emulator.</p>
<p>How might one access the imported data in a unit testing environment? That is, when using <code>@firebase/testing</code>, we typically create the test app like so:</p>
<pre><code>const db = firebase.initializeTestApp({ projectId: PROJECT_ID, auth}).firestore(); 
</code></pre>
<p><strong>How can one access the data imported thru the emulator and feed it into this db instance?</strong></p>
<p>My use case is for running unit tests on firestore rules against the imported data (for reference, the desired setup is very similar to this other <a href=""https://stackoverflow.com/questions/62953365/how-to-mock-data-for-testing-firestore-with-emulator"">related question</a>, but instead of relying on a manually built mock object, I'd like to use data coming from the emulator export/import feature)</p>
<p>Here is my test file</p>
<pre><code>/**
 * unit tests for firestore security and data validation rules
 *
 * adapted from https://github.com/firebase/quickstart-testing/blob/master/unit-test-security-rules
 */
const firebase = require(&quot;@firebase/testing&quot;);
const fs = require(&quot;fs&quot;);
const path = require(&quot;path&quot;)

/**
 * The emulator will accept any project ID for testing.
 */
const PROJECT_ID = &quot;test-dev-project&quot;;

/**
 * The FIRESTORE_EMULATOR_HOST environment variable is set automatically
 * by &quot;firebase emulators:exec&quot;
 */
const COVERAGE_URL = `http://${process.env.FIRESTORE_EMULATOR_HOST}/emulator/v1/projects/${PROJECT_ID}:ruleCoverage.html`;

/**
 * Set up mock data
 */
const mockUser = {
  uid: 'alice',
  email: 'alice@example.com',
  company: 'testCompany'
}

/**
 * Creates a new client FirebaseApp with authentication and returns the Firestore db instance.
 * @param {object} auth the object to use for authentication (typically {uid: some-uid})
 * @param {object} data the test data to use for filling the db
 * @return {object} the firestore instance db .
 */
getAuthedDb = async (auth, data) =&gt; {
  // initialize test app
  const app = firebase.initializeTestApp({ projectId: PROJECT_ID, auth });
  let db = app.firestore();
  return db;
};

beforeEach(async () =&gt; {
  // Clear the database between tests
  await firebase.clearFirestoreData({ projectId: PROJECT_ID });
});

before(async () =&gt; {
  // Load the rules file before the tests begin
  const rules = fs.readFileSync(&quot;firestore.rules&quot;, &quot;utf8&quot;);
  await firebase.loadFirestoreRules({ projectId: PROJECT_ID, rules });
});

after(async () =&gt; {
  // Delete all the FirebaseApp instances created during testing
  // Note: this does not affect or clear any data
  await Promise.all(firebase.apps().map((app) =&gt; app.delete()));
  console.log(`View rule coverage information at ${COVERAGE_URL}\n`);
});

function printDoc(doc) {
  if (doc.exists) {
      console.log(`Document ${doc.id} data:`, doc.data());
  } else {
      // doc.data() will be undefined in this case
      console.log(`No such document: ${doc.ref.path}, parent: ${doc.ref.parent.id}`);
  }
}

describe(&quot;Test Security Rules&quot;, () =&gt; {
  it(&quot;fetches data imported from emulator&quot;, async () =&gt; {
    const db = await getAuthedDb({uid: 'abcd'});
    const ref = db.doc(&quot;testdata/ac7yWTZekvGJMQj6Zq3M&quot;);
    await firebase.assertSucceeds(ref.get().then(printDoc));
  });
});
</code></pre>
<p>When I run <code>firebase emulators:exec --only firestore --import=data/ &quot;yarn run test-rules&quot;</code> (<code>test-rules</code> maps to <code>mocha --timeout 10000 test/test.spec.js</code>), the assert succeeds but the doc <code>&quot;testdata/ac7yWTZekvGJMQj6Zq3M&quot;</code> is not found, yet it exists in the data I'd imported from <code>data/</code></p>
",https://stackoverflow.com/questions/63043137/how-to-inject-data-imported-by-firestore-emulator-into-db-instance,"['firebase', 'unit-testing', 'google-cloud-firestore', 'firebase-tools']",499,False,0,1
How to handle failed asserts and abort calls with Microsofts unit testing framework?,"<p>I just moved from my catch2 testing frameworks to Microsofts native code C++ unit testing framework for the nicer integration into the IDE. </p>

<p>But my coding style is to use lots of assert statements all over the code. I cant replace them with macro calls like AssertIfTrue calls without poisoning the whole codebase with dependencies to the framework. </p>

<p>But if an assert fails the unit test runner stops with message box popup and when i press abort button the test will be reported as skipped and not as failed. This also looks like impossible behaviour for any automated continuous integration lifecycle. </p>

<p>I already tried setting a signal handler via <code>signal(SIGABRT, SignalHandler);</code> but the handler is never called. And using _set_abort_behavior to disable the message box with  <code>_set_abort_behavior( 0, _WRITE_ABORT_MSG);</code> also has no result.</p>
",https://stackoverflow.com/questions/61378525/how-to-handle-failed-asserts-and-abort-calls-with-microsofts-unit-testing-framew,"['c++', 'c', 'visual-studio', 'unit-testing', 'assert']",221,False,0,1
Heap based priority queue implementation,"<p>I've made a priority queue implementation that uses heap, but it works somewhat but I've encountered a problem where if I dequeue the priority queue it doesn't heapify correctly.
For example if I input 10 elements from an array ranging from 0 - 9, since this is a MaxHeap implementation it should always return the highest value and then heapify to correct the tree but it doesn't.</p>
<p>When I dequeue and get 9 and I don't get 8 when I dequeue again, I instead get 0 because it swaps from the last index but it doesn't fix the tree.
I've tried debugging and unit testing but I simply can't find where the problem is. I was wondering if some fresh eyes could see what I could not, thanks in advance!</p>
<pre><code>import java.lang.reflect.Array;

public class HeapPriorityQueue&lt;T extends Comparable&lt;? super T&gt;&gt; implements PriorityQueue&lt;T&gt; {
    
    private Class&lt;T&gt; clazz;
    private int lastIndex, capacity;
    private T heap[];
    
    public HeapPriorityQueue(Class&lt;T&gt; clazz, int capacity) {
        this.clazz = clazz;
        this.capacity = capacity;
        this.heap = (T[]) Array.newInstance(clazz, capacity);
        this.lastIndex = -1;
    }
    
    @Override
    public void clear() {
        this.lastIndex = -1;
        this.heap = (T[]) Array.newInstance(clazz, capacity);
        System.out.println(&quot;The queue has been destroyed!&quot;);
    }

    @Override
    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return lastIndex == -1;
    }

    @Override
    public boolean isFull() {
        // TODO Auto-generated method stub
        return lastIndex == capacity-1;
    }

    @Override
    public int size() {
        // TODO Auto-generated method stub
        return lastIndex;
    }

    @Override
    public void enqueue(T element) {
        if (!isFull()) {
            heap[++lastIndex] = element;
            shiftUp();
            
            String test = &quot;&quot;;
            for (int i = 0; i &lt; heap.length; i++) {
                test += &quot;&quot; + heap[i] + &quot; &quot;;
            }
            System.out.println(test);
        }
    }

    @Override
    public T dequeue() {
        if(isEmpty()) throw new QueueEmptyException();
        T rootValue = heap[0];
        swap(0, lastIndex);
        heap[lastIndex] = null;
        lastIndex--;
        shiftDown();
        String test = &quot;&quot;;
        for (int i = 0; i &lt; heap.length; i++) {
            test += &quot;&quot; + heap[i] + &quot; &quot;;
        }
        System.out.println(test);
        return rootValue;
    }

    @Override
    public T getFront() {
        if(isEmpty()) throw new QueueEmptyException();
        return heap[0];
    }
    
    private void shiftUp() {
        int index = lastIndex;
        int parentIndex = parent(index);
        while (parentIndex &gt; -1 &amp;&amp; heap[index].compareTo(heap[parentIndex]) &gt; 0) {
            swap(index, parentIndex);
            index = parentIndex;
            parentIndex = parent(parentIndex);
        }
    }
    
    private void shiftDown() {
        int index = 0;
        
        while (index &lt; lastIndex) {
            
            T maxValue = heap[index];
            int maxIndex = index;
            
            int leftIndex = left(index);
            if (leftIndex &gt; 0 &amp;&amp; maxValue.compareTo(heap[leftIndex]) &gt; 0) {
                maxValue = heap[leftIndex];
                maxIndex = leftIndex;
            }
            
            int rightIndex = left(index);
            if (rightIndex &gt; 0 &amp;&amp; maxValue.compareTo(heap[rightIndex]) &gt; 0) {
                maxValue = heap[rightIndex];
                maxIndex = rightIndex;
            }
            
            if (maxIndex == index) {
                break;
            }
            
            swap(maxIndex, index);
            index = maxIndex;
        }
    }
    
    private int parent(int index) {
        return index/2;
    }
    
    private int left(int index) {
        int leftChild = index * 2;
        return leftChild;
    }

    private int right(int index) {
        int rightChild = index * 2 + 1;
        return rightChild;
    }
    
    private void swap(int index1, int index2) {
        T temp = heap[index1];
        heap[index1] = heap[index2];
        heap[index2 ] = temp;
    }
    
    public static void main(String[] args) {
        Integer[] data = {1, 2, 5, 6, 7, 8, 9, 10, 15, 20};
        HeapPriorityQueue&lt;Integer&gt; pq = new HeapPriorityQueue&lt;Integer&gt;(Integer.class,10);
        for (Integer i : data) {
            pq.enqueue(i);
        }
        System.out.println(pq.dequeue());
        System.out.println(pq.dequeue());
    }
    
}
</code></pre>
",https://stackoverflow.com/questions/65277901/heap-based-priority-queue-implementation,"['java', 'oop', 'binary-tree', 'heap', 'priority-queue']",165,False,0,0
Jest test breaks when component has DOM manipulation logic,"<p>I am unit testing my React app using Jest and Enzyme. I am running into a problem wherein when the component to be tested has DOM manipulation logic, my test cases break.</p>

<p>For instance, here is the hook of component I need to test:</p>

<pre><code>componentDidMount() {
  document.getElementById('complete').style.display = 'block';
}
</code></pre>

<p>On trying to shallow mount this component, I run into the below error:</p>

<pre><code>TypeError: Cannot set property 'display' of undefined
</code></pre>

<p>I googled around and found that I need to add document to my globals in jest. The painful thing is, I also need to defined each such property used in my app on the document as follows:</p>

<pre><code>const mockUpObject = {
    focus: () =&gt; null,
    style:{
        display: ''
    }
};
global.document.getElementById = jest.fn(() =&gt; mockUpObject);
</code></pre>

<p>Why do we need it when by default jest runs in <code>jsdom</code> environment and hence simulates a DOM environment as if you were in the browser. Is there a cleaner way to make this work?</p>
",https://stackoverflow.com/questions/59826609/jest-test-breaks-when-component-has-dom-manipulation-logic,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",315,False,0,0
Clean up private static variables between unit tests,"<p>I have a class that looks similar to this:</p>

<pre><code>public class DiscoveryDocumentCache
{
    static DiscoveryDocumentCache()
    {
        cache = new MemoryCache(discoveryDocumentCacheName);
    }

    private static MemoryCache cache;

    // Other stuff...
}
</code></pre>

<p>I want the memory cache to be static so that it is shared across all instances of the class.</p>

<p>It is working great for the actual use cases.  Where I am struggling is with my unit tests.  Because the <code>cache</code> variable is static, it accumulates all the different values that get put in it.</p>

<p>My use case does not have a ""remove"" option.  (They just expire out of the cache.)</p>

<p>I have added this to my <code>DiscoveryDocumentCache</code> class:</p>

<pre><code>    public void __UnitTesting__CleanUpMemoryCacheBetweenTests()
    {
        cache.Dispose();
        cache = new MemoryCache(discoveryDocumentCacheName);
    }
</code></pre>

<p>But it feels dirty to add a method that is just to facilitate unit testing.</p>

<p>.NET Framework had some ways to access class's private variables if you really thought you should.  <strong>Is there something similar I can do to reset this static variable in my <code>TearDown</code> unit test method?</strong></p>
",https://stackoverflow.com/questions/60531042/clean-up-private-static-variables-between-unit-tests,"['unit-testing', '.net-core', 'nunit', 'private', '.net-core-3.1']",1906,True,0,1
Jest throws error that is saved to a variable in some tests but not others,"<p>I am unit testing some methods on my TypeScript class using Jest. In an effort to use the DRY coding principle I assign an error to a variable and use it throughout the test. Sometimes, however, Jest is throwing the error like it's not being assigned.</p>
<p>Here's an example:</p>
<pre><code>describe(`Jest Tests`, () =&gt; {
    let subscriptionId: string;
    let isActiveSubscription: boolean;

    beforeEach(() =&gt; {
      subscriptionId = 'ABCD1234';
      isActiveSubscription = false;

      mockSubscriptionModel = new SubscriptionModel(subscriptionId);
    });

    afterEach(() =&gt; {
      jest.clearAllMocks();
    });

    test('This is a passing test', async (done) =&gt; {
      const connectionError = new Error('This is a DB connection error');

      DbClient.connect = jest.fn().mockRejectedValueOnce(connectionError);

      try {
        const result = await SubscriptionModel.getActiveSubscriptions();
      } catch (err) {
        expect(DbClient.connect).toHaveBeenCalledTimes(1);
        expect(err).toEqual(connectionError);
        done();
      }
    });

    test(`This is a failing test`, async (done) =&gt; {
      const connectionError = new Error('This is a DB connection error');

      DbClient.connect = jest.fn().mockRejectedValueOnce(connectionError);

      try {
        const result = await mockSubscriptionModel.addSubscription(
          subscriptionId,
          isActiveSubscription
        );
      } catch (err) {
        expect(DbClient.connect).toHaveBeenCalledTimes(1);

        expect(err).toEqual(connectionError);
        done();
      }
    });
  });

</code></pre>
<p>Here is the error on the console:</p>
<pre><code> FAIL  test/models/Subscription.test.ts
  ● Subscription Model Tests › Jest Tests Tests › This is a failing test

    This is a DB connection error

      201 | 
      202 |     test(`Should fail if DB connection fails`, async (done) =&gt; {
    &gt; 203 |       const connectionError = new Error('This is a DB connection error');
          |                               ^
      204 | 
      205 |       DbClient.connect = jest.fn().mockRejectedValueOnce(connectionError);
      206 | 

      at test/models/Subscription.test.ts:203:31
      at test/models/Subscription.test.ts:8:71
      at __awaiter (test/models/Subscription.test.ts:4:12)
      at Object.&lt;anonymous&gt; (test/models/Subscription.test.ts:202:63)
</code></pre>
<p>I am confused at why the first test would pass and the second would fail since they are practically the same code.</p>
<h1>Update 1</h1>
<p>So with a little debugging, I have found that the line causing the error to be thrown is:</p>
<pre><code>const result = await mockSubscriptionModel.addSubscription(
  subscriptionId,
  isActiveSubscription
);
</code></pre>
<p>So maybe it has something to do with declaring an instance the mock model? But I do have a similar test in another model which declares an instance of a class:</p>
<pre><code>    test(`Should fail if bcrypt fails`, async (done) =&gt; {
      const bcryptError = new Error(`This is a bcrypt error.`);

      bcrypt.hash = jest.fn().mockRejectedValueOnce(bcryptError);

      try {
        await mockUserModel.hashPassword();
      } catch (err) {
        expect(bcrypt.hash).toHaveBeenCalledTimes(1);
        expect(bcrypt.hash).toHaveBeenCalledWith(mockUser.password, 12);
        expect(err).toEqual(bcryptError);
        done();
      }
</code></pre>
<p>and that does not error either.</p>
",https://stackoverflow.com/questions/62935360/jest-throws-error-that-is-saved-to-a-variable-in-some-tests-but-not-others,"['typescript', 'jestjs']",313,False,0,1
"Unit testing method that creates objects, trouble asserting","<p>I have a method that takes an XML string and parses it, returning an <code>IEnumerable&lt;Invoice&gt;</code>. The following is the definition of the classes being used. Note that an <code>Invoice</code> contains <code>InvoiceItem</code>s:</p>
<pre><code>public class Invoice
{
    public const string XmlName = &quot;invoice&quot;;

    public int id { get; set; }
    public string title { get; set; }
    public DateTime timestamp { get; set; }
    public bool paid { get; set; }
    public IList&lt;InvoiceItem&gt; items { get; set; }

    public Invoice() { this.items = new List&lt;InvoiceItem&gt;(); }

    public decimal getTotal()
    {
        if (items == null)
            return 0;

        decimal total = 0;

        foreach (InvoiceItem item in this.items)
            total += item.amount;

        return total;
    }
}

public class InvoiceItem
{
    public const string XmlName = &quot;item&quot;;

    public string description { get; set; }
    public decimal amount { get; set; }
}
</code></pre>
<p>When unit testing the method with NUnit, something strange is going on with the boolean values for <code>paid</code>. Note that I have tested the method in .NET Fiddle, and it returns all the objects it should. So it appears as though something is wrong with the following test (partial code):</p>
<pre><code>[Test]
public void readXml_Test()
{
    // arrange

    // xml stuff...

    // expected objects
    InvoiceItem item1 = new InvoiceItem { description = &quot;item 1 in invoice 1&quot;, amount = 50 };
    InvoiceItem item2 = new InvoiceItem { description = &quot;item 2 in invoice 1&quot;, amount = 50 };
    Invoice invoice1 = new Invoice
    {
        id = 1,
        title = &quot;Aug 2020&quot;,
        timestamp = DateTime.ParseExact(&quot;16/08/2020 09:01:29 AM&quot;, &quot;dd/MM/yyyy hh:mm:ss tt&quot;, System.Globalization.CultureInfo.InvariantCulture),
        paid = true,
        items = new List&lt;InvoiceItem&gt;() { item1, item2 }
     };
     InvoiceItem item3 = new InvoiceItem { description = &quot;item in invoice 2&quot;, amount = 100 };
     Invoice invoice2 = new Invoice
     {
         id = 2,
         title = &quot;Sep 2020&quot;,
         timestamp = DateTime.ParseExact(&quot;16/08/2020 09:01:29 AM&quot;, &quot;dd/MM/yyyy hh:mm:ss tt&quot;, System.Globalization.CultureInfo.InvariantCulture),
         paid = true,
         items = new List&lt;InvoiceItem&gt; { item3 }
      };

    // act
    List&lt;Invoice&gt; actual = xml.readXml().ToList(); // readXml() is the method under test.

    // assert
    Assert.That(actual.Contains(invoice1));
    Assert.That(actual.Contains(invoice2));
}
</code></pre>
<p>As mentioned before, I have tested this in .NET fiddle, and the resulting objects all have correct property values. However, the above test yields:</p>
<pre><code>Message: Expected: True
 But was: False
</code></pre>
<p>There is no mention of any exception. Since I know the method under test works, it seems to be a problem with this test. How can I fix it to make it pass?</p>
",https://stackoverflow.com/questions/63448204/unit-testing-method-that-creates-objects-trouble-asserting,"['c#', '.net', 'unit-testing', 'nunit', 'assert']",58,False,0,0
"Spring, Maven: Correct the classpath of your application","<p>I am trying to create a maven version of the gradle-based treehouse 'unit-testing-a-spring-application' project used in this <a href=""https://teamtreehouse.com/library/unit-testing-a-spring-application"" rel=""nofollow noreferrer"">course</a>. See course code <a href=""https://bitbucket.org/abitorgdout/spring-unit-testing-public/src/master/"" rel=""nofollow noreferrer"">here</a>.</p>
<p>After not being able to build initially, I ended up adding dependency versions specified in the original gradle build file. Maven will build fine, but running the app gives this:</p>
<pre><code>The following method did not exist:
    org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)
Ljava/lang/String;

The method's class, org.springframework.data.repository.config.RepositoryConfigurationSource, is 
available from the following locations:
    jar:file:/C:/Users/home/.m2/repository/org/springframework/data/spring-data-
commons/2.1.6.RELEASE/spring-data-commons-2.1.6.RELEASE.jar!/org/springframework/data/repository/config/RepositoryConfigurationSource.class

It was loaded from the following location:
    file:/C:/Users/home/.m2/repository/org/springframework/data/spring-data-commons/2.1.6.RELEASE/spring-
data-commons-2.1.6.RELEASE.jar

Action  
    Correct the classpath of your application so that it contains a single, compatible version of
 org.springframework.data.repository.config.RepositoryConfigurationSource.
</code></pre>
<p>Several similar problems are solved here on S.O. by changing the version of some related dependency. I have tried various versions of the following to no avail (I stick normally with spring-boot-starter-parent v2.1.4 cause it works all the time with my projects):</p>
<pre><code>spring-data-commons
spring-boot-starter-parent
</code></pre>
<p>I see the needed class below listed in my project Dependencies directory, but what dependency versions will work in this case? How can I solve this otherwise?</p>
<pre><code>org/springframework/data/repository/config/RepositoryConfigurationSource.class
</code></pre>
",https://stackoverflow.com/questions/63061640/spring-maven-correct-the-classpath-of-your-application,"['java', 'spring', 'maven']",872,False,0,1
Django Test Case gets diffrent redirect than Firefox or Chrome,"<p>Trying to work on a project and get my head around unit Testing.
I'm confused why client.get is getting a diffrent redirect than both Firefox and Chrome.</p>

<p>Details below, but can someone give me an idea this is occuring.</p>

<ul>
<li>Django Version 3</li>
<li>Python verson 3.8</li>
<li>Running on Ubuntu in WSL in windows.</li>
</ul>

<p>My View Function. </p>

<pre><code>class UserDashboardView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponseRedirect('/accounts/login')
</code></pre>

<p>My Test Case</p>

<pre><code>import unittest
from django.test import TestCase

class DashboardPageTest(TestCase):

    def test_unauthenticated_user_redirected_to_login(self):
        response = self.client.get('/dashboard')
        print(response)
</code></pre>

<p>What occurs.</p>

<p>1 - If I go to /dashboard in Chrome and Firefox the debug shows a 302 with a location key of /accounts/login, and so the browser follows to /accounts/login</p>

<p>2 - If I run the unit test (python manage.py test) the print of the response returns </p>

<pre><code>&lt;HttpResponsePermanentRedirect status_code=301, ""text/html; charset=utf-8"", url=""/dashboard/""&gt;
</code></pre>

<p>I have a feeling their is something I just don't get about the way the browsers vs the TestCase does redirects. Can someone please explain it?</p>
",https://stackoverflow.com/questions/59650425/django-test-case-gets-diffrent-redirect-than-firefox-or-chrome,"['python', 'django', 'django-testing']",121,True,0,2
Returning a Bad Request while setting up mock repository in an ASP.NET web api controller for a unit test,"<p>I am writing unit tests for my ASP.NET core web API controllers.
For one specific unit test I am trying to post a movie and checking whether a movie with the name already exists and if it does it returns a bad request. The API works properly but I am having issues with writing the unit test.</p>
<p>My controller code for the post request-</p>
<pre><code>        [HttpPost()]
    public async Task&lt;IActionResult&gt; AddMovie(MovieForDetailedDto movieForDetailedDto)
    { 
        if (await _repo.MovieExists(movieForDetailedDto.ATitle))
            return BadRequest(&quot;movie already exists&quot;);

        else if(!ModelState.IsValid || movieForDetailedDto.ATitle == null || movieForDetailedDto.APrice == null || movieForDetailedDto.AMovieDescription ==null)
        {
            return BadRequest(&quot;movie details not valid&quot;);
        }

        var movieToCreate = _mapper.Map&lt;TblMovie&gt;(movieForDetailedDto);

        var createdMovie = await _repo.AddMovie(movieToCreate);

        return Ok(createdMovie);
    }
</code></pre>
<p>The test I am writing-</p>
<pre><code>        [Test]
    public async Task GivenAValidMovie_WhenIPostANewMovieWithExistingName_ThenItReturnsbadRequest()
    {
        getMoviesHelper getMoviesHelper = new getMoviesHelper();
        List&lt;TblMovie&gt; movieList = getMoviesHelper.getMovieFromList();
        _mockMovieRepository = new Mock&lt;IMovieRepository&gt;();
        _mockMovieMapper = new Mock&lt;IMapper&gt;();
        _mockMovieMapper.Setup(mapper =&gt; mapper.Map&lt;TblMovie&gt;(It.IsAny&lt;MovieForDetailedDto&gt;()))
                .Returns(new TblMovie());
        _mockMovieRepository.Setup(repo =&gt; repo.AddMovie(It.IsAny&lt;TblMovie&gt;()))
                .ReturnsAsync(BadRequest());
        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.AddMovie(new MovieForDetailedDto
        {
            AMovieId = 3,
            ATitle = &quot;Big Hero 6&quot;,
            AMovieDescription = &quot;An action comedy adventure about brilliant robotics prodigy Hiro Hamada, who finds himself in the grips of a criminal plot that threatens to destroy the fast-paced, high-tech city of San Fransokyo. With the help of his closest companion-a robot named Baymax-Hiro joins forces with a reluctant team of first-time crime fighters on a mission to save their city.&quot;,
            ADuration = &quot;105 min&quot;,
            APrice = &quot;10&quot;,
            APurchasePrice = &quot;25&quot;,
            ARating = 5,
            AImageLink = &quot;http://upload.wikimedia.org/wikipedia/en/4/4b/Big_Hero_6_%28film%29_poster.jpg&quot;,
            ATrailerLink = &quot;//www.youtube.com/embed/z3biFxZIJOQ&quot;,
            AGenre = &quot;Comedy&quot;,
            AWideImage = &quot;https://github.com/tushar23091998/MovieRentalApp-FrontEnd/blob/master/src/app/images/bighero6.jpg?raw=true&quot;
        });
        Assert.IsInstanceOf&lt;BadRequestObjectResult&gt;(tblMovie);

    }
</code></pre>
<p>Not sure on how I should write the _mockMovieRepository setup line such that it returns a bad request.?</p>
<p>the function I am using to populate a list for testing purposes.</p>
<pre><code>        public List&lt;TblMovie&gt; getMovieFromList()
    {
        var movies = new List&lt;TblMovie&gt;();
        movies.Add(new TblMovie()
        {
            AMovieId = 2,
            ATitle = &quot;Big Hero 6&quot;,
            AMovieDescription = &quot;An action comedy adventure about brilliant robotics prodigy Hiro Hamada, who finds himself in the grips of a criminal plot that threatens to destroy the fast-paced, high-tech city of San Fransokyo. With the help of his closest companion-a robot named Baymax-Hiro joins forces with a reluctant team of first-time crime fighters on a mission to save their city.&quot;,
            ADuration = &quot;105 min&quot;,
            APrice = &quot;10&quot;,
            APurchasePrice = &quot;25&quot;,
            ARating = 5,
            AImageLink = &quot;http://upload.wikimedia.org/wikipedia/en/4/4b/Big_Hero_6_%28film%29_poster.jpg&quot;,
            ATrailerLink = &quot;//www.youtube.com/embed/z3biFxZIJOQ&quot;,
            AGenre = &quot;Comedy&quot;,
            AWideImage = &quot;https://github.com/tushar23091998/MovieRentalApp-FrontEnd/blob/master/src/app/images/bighero6.jpg?raw=true&quot;
        });
</code></pre>
<p>}</p>
<p>How should I go on about writing this function too-</p>
<pre><code>        public TblMovie movieByNameExists(TblMovie tMovie)
    {
        var movies = getMovieFromList();
        foreach (TblMovie tblMovie in movies)
        {
            if (tblMovie.ATitle == tMovie.ATitle)
            {
                //return &quot;movie already exists&quot;;
                // How do I return a BAD REQUEST HERE;

            }
        }
        return tMovie;
    }
</code></pre>
<p>THANKS FOR YOUR TIME. I am very new to unit testing so apologies if I am asking something too obvious</p>
",https://stackoverflow.com/questions/64334192/returning-a-bad-request-while-setting-up-mock-repository-in-an-asp-net-web-api-c,"['c#', 'unit-testing', 'nunit', 'automapper', 'asp.net-core-webapi']",1589,True,0,1
Error in mocking for embedded unit testing &quot;Address of overloaded function does not match required type &#39;void()&#39;,"<p>I am working on an Embedded C project for which I am currently writing unit tests. I am using the fff mocking framework, which essentially creates fake function calls which should overload hardware specific calls.</p>
<p>When I create a 'fake function' I get an error stating that</p>
<blockquote>
<p>Address of overloaded function does not match required type 'void()'</p>
</blockquote>
<p>This is happening every time I attempt to create a Fake. I am primarily an embedded C programmer, and only using elements of C++ for the purposes of unit testing. I don't really understand what this message is telling me or why it is a problem. If anyone could offer any insight, I would be very grateful.</p>
<p>The code in question is shown below. The error is highlighted on the function names: xTaskCreate, HAL_TIM_Base_Init and HAL_TIM_ConfigClockSource.</p>
<pre><code>#include &lt;TinyEmbeddedTest.h&gt;
#include &lt;stdio.h&gt;
#include &quot;stm32f1xx_hal.h&quot;
#include &quot;FreeRTOS.h&quot;
#include &quot;task.h&quot;
#include &quot;fff.h&quot;

#include &quot;heater.c&quot;  //source file being tested

DEFINE_FFF_GLOBALS;

FAKE_VALUE_FUNC(BaseType_t, xTaskCreate, TaskFunction_t, char *, configSTACK_DEPTH_TYPE, void *, UBaseType_t, TaskHandle_t *);
FAKE_VALUE_FUNC(HAL_StatusTypeDef, HAL_TIM_Base_Init, TIM_HandleTypeDef);
FAKE_VALUE_FUNC(HAL_StatusTypeDef, HAL_TIM_ConfigClockSource, TIM_HandleTypeDef, TIM_ClockConfigTypeDef*);
</code></pre>
",https://stackoverflow.com/questions/64821121/error-in-mocking-for-embedded-unit-testing-address-of-overloaded-function-does,"['c++', 'c', 'unit-testing', 'mocking', 'fake-function-framework']",301,True,0,1
How to define testable timer loop in kotlin (android)?,"<p>I want to have a periodic timer loop (e.g. 1 second intervals). There are many ways to do that, but I haven't found a solution that would be suitable for unit testing.</p>
<ul>
<li>Timer should be precise</li>
<li>Unit test should be able to skip the waiting</li>
</ul>
<p>The closest that I came to a solution was to use coroutines: A simple loop with <code>delay</code>, <code>runBlockingTest</code> and <code>advanceTimeBy</code>.</p>
<pre><code>coScope.launch {
    while (isActive) {
        // do stuff
        delay(1000L)
    }
}
</code></pre>
<p>and</p>
<pre><code>@Test
fun timer_test() = coScope.runBlockingTest {
    ... // start job
    advanceTimeBy(9_000L)
    ... // cancel job
}
</code></pre>
<p>It works to some degree, but the timer is not precise as it does not account for the execution time.</p>
<p>I haven't found a way to query internal timer used in a coroutine scope or a remaining timeout value inside <code>withTimeoutOrNull</code>:</p>
<pre><code>coScope.launch {
    withTimeoutOrNull(999_000_000L) {  // max allowed looping time
        while (isActive) {
            // do stuff
            val timeoutLeft // How to get that value ???
            delay(timeoutLeft.mod(1000L))
        }
    }
}
</code></pre>
<p>Next idea was to use <code>ticker</code>:</p>
<pre><code>coScope.launch {
    val tickerChannel = ticker(1000L, 0L, coroutineContext)
    var referenceTimer = 0L
    for (event in tickerChannel) {
         // do stuff
         println(referenceTimer)
         referenceTimer += 1000L
    }
}
</code></pre>
<p>However, the connection between <code>TestCoroutineDispatcher()</code> and <code>ticker</code> does not produce right results:</p>
<pre><code>private val coDispatcher = TestCoroutineDispatcher()

@Test timerTest() = runBlockingTest(coDispatcher) {
    myTimer.lauchPeriodicJob()
    advanceTimeBy(20_000L)  // or delay(20_000L)
    myTimer.cancelPeriodicJob()
    println(&quot;end_of_test&quot;)
}
</code></pre>
<p>rather consistently results in:</p>
<pre><code>0
1000
2000
3000
4000
5000
6000
end_of_test
</code></pre>
<p>I am also open for any alternative approaches that satisfy the two points above.</p>
",https://stackoverflow.com/questions/63412390/how-to-define-testable-timer-loop-in-kotlin-android,"['unit-testing', 'kotlin', 'timer', 'kotlin-coroutines']",670,False,3,0
C# ILogger dependency Injection error: There is no argument,"<p>I have a Docker DotNet Core console app that processes messages from a queue.</p>
<p>There is a class called <code>SimulationEngine</code> and I was expecting that <code>ILogger</code> is passed by Dependency Injection automatically</p>
<pre><code>public class SimulationEngine
{
    ILogger&lt;SimulationEngine&gt; logger;

    public SimulationEngine(ILogger&lt;SimulationEngine&gt; logger)
    {
        this.logger = logger;
    }
</code></pre>
<p>This is how the instance is created:</p>
<pre><code>   public class RunsQueueProcessor : ...
   {
        public RunsQueueProcessor(..., ILogger&lt;RunsQueueProcessor&gt; logger)
        {
        }

        protected override async Task ProcessMessage(...)
        {
            this.logger.LogInformation(...);

            // Here DI is not working
            var engine = new SimulationEngine();
        
</code></pre>
<p>DI works fine to inject logger into <code>RunsQueueProcessor</code>, but it fails when I try to <code>new SimulationEngine()</code> with the following error:</p>
<pre><code>Error   CS7036  There is no argument given that corresponds to the required formal parameter 'logger' of 'SimulationEngine.Simui lationEngine(ILogger&lt;SimulationEngine&gt;)'
</code></pre>
<p>How can I tell DotNet to use DI for that constructor?</p>
<p>--- EDIT ---</p>
<p>I wrote this question because I am working on a PoC and I don't need Dependency Injection everywhere. I only need it in few places where I am doing Unit Testing to validate specific algorithms.
A more concrete questions is if there is a way to configure DotNet DI framework to inject dependencies when using the <code>new</code> statement or manually instantiating objects.</p>
<p>Thanks to all comments and answers, Now I understand more about how DotNet DI works.</p>
",https://stackoverflow.com/questions/65297320/c-ilogger-dependency-injection-error-there-is-no-argument,"['c#', '.net-core', 'dependency-injection']",1115,True,2,1
Operation chmod 0777 not permitted inside a running Docker container,"<p>I am trying to execute some unit testing for my C++ code inside a Docker container that calls the command:</p>
<pre class=""lang-cpp prettyprint-override""><code>...
if (chmod(&quot;/tmp/ipc_unixdomain&quot;, 0777) != 0) {
...
</code></pre>
<p>In my PC outside of the container, I am able to run this command in both the terminal and the C++ code, but once I move inside the container I am only able to execute them if I run as the root user or with <em>sudo</em>. If I don't do it like that I get the error message</p>
<pre class=""lang-sh prettyprint-override""><code>Operation not permitted
</code></pre>
<p>I would like to have a way to normally execute my tests without the need for sudo privileges. <strong>Is there a way to solve this by modifying the Dockerfle or changing my code?</strong></p>
<p><a href=""https://stackoverflow.com/questions/45972608/how-to-give-folder-permissions-inside-a-docker-container-folder"">This other</a> question does not completely help. The folder I am using is created during the execution of my C++ program, so I think I can't give access in advance.</p>
",https://stackoverflow.com/questions/64970050/operation-chmod-0777-not-permitted-inside-a-running-docker-container,"['c++', 'linux', 'docker', 'sudo', 'chmod']",4565,True,2,1
Cannot find module in .spec.ts file in Ionic 3,"<p>I am working on Ionic 3 (Angular type) application, and to implement  <code>unit testing</code> ,I am using <strong>Jasmine</strong> and <strong>Karma</strong>. Project structure of Ionic 3 (Angular type) doesnot provide .spec.ts file for pages/components/providers. So, I, manually, created .spec file for pages, but it is showing 'Cannot find module '@angular/core' and 'Cannot find module '@angular/core/testing' error.</p>

<p><a href=""https://i.stack.imgur.com/66pRL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/66pRL.png"" alt="".spec.ts error image""></a></p>

<p>As these file are not able to fetch modules or not able to get the path to reach to those modules. </p>

<p>I have tried following ways :</p>

<ul>
<li>Removed node_modules and reinstalled it (npm install).</li>
<li>Ran command <strong><em>npm i @angular/core</em></strong>, with and without --save-dev.</li>
<li>Restarted sublime and terminal as well, after new installation.</li>
</ul>

<p>But these didn't bring any solution to the issue.</p>

<p>So, is there any way to resolve this issue ? Or am I wrongly implementing Jasmine-Karma unit testing ? Please suggest.</p>

<blockquote>
  <p>karma.conf.js :</p>
</blockquote>

<pre><code>var webpackConfig = require('./webpack.test.js');
module.exports = function(config) {
    var _config = {
        basePath: '../',
        frameworks: ['jasmine'],

        files: [{pattern: 'src/pages/**/*.spec.ts', watched: true},
        { pattern: './src/pages/**/*',
        watched: false,
        included: false,
        served: true,
        nocache: false
    }],

    proxies: {'/assets/': '/base/src/pages/'},

    preprocessors: {'**/*.spec.ts' : [""webpack""]},

    webpack: webpackConfig,

    webpackMiddleware: {stats: 'errors-only'},

    webpackServer: {noInfo: true},

    browserConsoleLogOptions: {
        level: 'log',
        format: '%b %T: %m',
        terminal: true
    },

    coverageIstanbulReporter: {
        reports: [ 'html', 'lcovonly' ],
        fixWebpackSourcePaths: true
    },

    reporters: config.coverage ? ['kjhtml', 'dots', 'coverage-istanbul'] : ['kjhtml', 'dots'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
};

config.set(_config);
};
</code></pre>
",https://stackoverflow.com/questions/60150417/cannot-find-module-in-spec-ts-file-in-ionic-3,"['angular', 'typescript', 'unit-testing', 'ionic3', 'karma-jasmine']",3151,True,2,1
How to patch the python 3 breakpoint() builtin?,"<p>I wrote a decorator that halts my program with breakpoint() if a critical error happens.</p>

<pre><code>def the_breakpoint_dec(func):
    @functools.wraps(func):
    async def my_wrapper(func):
       retval=await func(*args,**kwargs)
       return retval if retval else breakpoint()
    return my_wrapper
</code></pre>

<p>I'm doing unit testing and want to make sure the breakpoint hits, without actually triggering it, so I've been trying to patch breakpoint() with the @mock.patch decorator, but it's not working. Some of the tested paths to breakpoint of the 20 or so i've tried
are </p>

<pre><code>@mock.patch('pdb.breakpoint')
@mock.patch('builtins.breakpoint')
@mock.patch('builtins.pdb.breakpoint')
@mock.patch('my_module.breakpoint')
@mock.patch('my_module.builtins.breakpoint')
@mock.patch('sys.breakpointhook')
@mock.patch('my_module.sys.breakpointhook')
@mock.patch('my_decorator_module.sys.breakpointhook')
@mock.patch('my_decorator_module.sys.breakpoint')


</code></pre>

<p>I then make the test function def and pass in the mock:</p>

<pre><code>#testmodule.py
pytestmark=pytest.mark.asyncio
@mock.patch('just_another_path_to_breakpoint()_that_doesnt_work')
async def test_func_to_test(self, mock_breakpoint, some_other_mock): 
    mock_breakpoint.return_value=None
    await decorated_func()
    mock_breakpoint.assert_called() # never hit because pdb prompt opens in interpreter
</code></pre>

<p>module under test</p>

<pre><code>#moduleundertest.py

class bar:
    @the_breakpoint_dec
    async def decorated_func(self):
        for i in range(3)
            try:
                return await something_likely_to_fail()
            except:
                pass
</code></pre>

<p>Initially the breakpoint() I wanted to patch was being called from the mentioned decorator. After several hours of failures I commented out the decorator and moved breakpoint() directly into the method under test. The the patching still failed. What is the proper way to patch this builtin, and if some special thing must be done to patch it when it's in a decorator, what thing is that?</p>
",https://stackoverflow.com/questions/61897718/how-to-patch-the-python-3-breakpoint-builtin,"['python-3.x', 'unit-testing', 'debugging', 'mocking', 'python-asyncio']",170,True,2,1
Newly generated Angular Component and Unit Test fails with Jest Test Runner only when using Testbed,"<p>My goal is to create a unit test using the Testbed provided by Angular Core.  I happen to be using Jest Test Runner (syntax similar to Jasmine) for my unit testing.
<br><br>
Expected:<br>
I expected that after the CLI generates a component and its associated unit test that the unit test would pass (see Component and Unit Test for the minimal reproducible example below).
<br><br>
Actual:<br>
In actuality, I received two errors (see Errors below).  These errors show me that the component is not being instantiated in time for the test.
<br><br>
Things I have tried:<br>
My <a href=""https://stackoverflow.com/questions/61728890/failed-zone-is-needed-for-the-async-test-helper-but-could-not-be-found?noredirect=1#comment109191113_61728890"">previous question</a> shows a history of things I have tried thus far.  That start with the first thing I tried which was <a href=""https://stackoverflow.com/questions/53913577/cant-resolve-all-parameters-for-applicationmodule"">adding the initiation of the test environment to the setup File</a>. This just resulted in <code>Can't resolve all parameters for ApplicationModule: (?).</code> You can go to that ticket if you are interested in the riveting discussion coming from that. On to this attempt...
1. The second major attempt after the above leads to the below steps.  I tried wrapping the beforeEach Testbed call in an async function. <br>
2. This simply results in the error <code>ProxyZoneSpec is needed for the async() test helper but could not be found.</code> After that, you add <code>import 'zone.js/dist/proxy.js';</code> to your setup file.<br>
3. This results in the error <code>Expected to be running in 'ProxyZone', but it was not found.</code> After that, you find a few SO posts <a href=""https://stackoverflow.com/questions/48789782/angular-5-testing-expected-to-be-running-in-proxyzone-but-it-was-not-found"">one of which</a> suggests you use <code>fakeAsync</code> instead of <code>async</code> so you try that.  The error doesn't change this time. The test is still failing.
<br><br><br>
This post could have also been named:</p>

<blockquote>
  <p>Using Testbed to do Angular Unit testing - BeforeEach wrapped in Async causes the error: Expected to be running in 'ProxyZone', but it was not found. 
  <br>
  But I believe starting on solid ground with the MRE where the CLI leaves you is the best since that SHOULD work, but doesn't.
  Anyway, I am wondering where I went astray here.  If you have anything I could try I am all ears.  Thank you for your help.  Please let me know if I am missing anything so I can amend this post.
  <br><br><br><br>
  <strong>Component</strong></p>
</blockquote>

<pre><code>@Component({
  selector: 'app-geode-lib',
  template: `  `,
})
export class GeodeLibComponent implements OnInit {
  constructor() { }
  ngOnInit() { }
}
</code></pre>

<p><strong>Unit test</strong></p>

<pre><code>describe('GeodeLibComponent', () =&gt; {
  let component: GeodeLibComponent;
  let fixture: ComponentFixture&lt;GeodeLibComponent&gt;;
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [GeodeLibComponent]
    });
    fixture = TestBed.createComponent(GeodeLibComponent);
    component = fixture.componentInstance;
  });
  it('can load instance', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p><strong>ERROR1</strong></p>

<pre><code> FAIL  projects/geode-lib/src/lib/geode-lib.component.spec.ts
  ● GeodeLibComponent › can load instance

    TypeError: Cannot read property 'getComponentFromError' of null

      at TestBedViewEngine._initIfNeeded (../../packages/core/testing/src/test_bed.ts:378:46)
      at TestBedViewEngine.createComponent (../../packages/core/testing/src/test_bed.ts:570:10)
      at Function.TestBedViewEngine.createComponent (../../packages/core/testing/src/test_bed.ts:232:36)
      at Object.beforeEach (projects/geode-lib/src/lib/geode-lib.component.spec.ts:12:23)

  ● GeodeLibComponent › can load instance

    expect(received).toBeTruthy()

    Received: undefined

      14 |   });
      15 |   it('can load instance', () =&gt; {
    &gt; 16 |     expect(component).toBeTruthy();
         |                       ^
      17 |   });
      18 | });
      19 | 

      at Object.it (projects/geode-lib/src/lib/geode-lib.component.spec.ts:16:23)
</code></pre>

<p><strong>ERROR2</strong></p>

<pre><code>// getTestBed().initTestEnvironment(
//     BrowserDynamicTestingModule,
//     platformBrowserDynamicTesting()
// );
</code></pre>
",https://stackoverflow.com/questions/61758896/newly-generated-angular-component-and-unit-test-fails-with-jest-test-runner-only,"['angular', 'unit-testing', 'jasmine', 'jestjs', 'testbed']",710,False,2,0
Net Framework Xunit With Moq Unit Testing Keep Calling The Original Function,"<p>I have a problem with mocking cause it keep calling the original function. This is my demo code</p>

<p>First file is interface that contains the function that I want to mock.</p>

<pre><code>public interface IDemoReplace
{
    int FunctionToBeReplaced();
}
</code></pre>

<p>Second file is a class that actually has the implementation for the function</p>

<pre><code>public class DemoReplace : IDemoReplace
{
    public int FunctionToBeReplaced()
    {
        //this function contains sql query in my real project
        return 1;
    }
}
</code></pre>

<p>Third file is a class that I want to test</p>

<pre><code>public class ClassToBeTested
{
    public int TestThisFunction()
    {
        IDemoReplace replace = new DemoReplace();
        var temp = replace.FunctionToBeReplaced();
        return temp;
    }
}
</code></pre>

<p>Last file is the test class</p>

<pre><code>public class TestClass
{

    [Fact]
    public void TryTest()
    {
        using (var mock = AutoMock.GetLoose()) {
            //Arrange
            mock.Mock&lt;IDemoReplace&gt;()
                .Setup(x =&gt; x.FunctionToBeReplaced())
                .Returns(returnTwo());

            var classToBeTested = mock.Create&lt;ClassToBeTested&gt;();
            var expected = 2;

            //Act
            var actual = classToBeTested.TestThisFunction();

            //Assert
            Assert.Equal(expected, actual);
        }
    }

    public int returnTwo() {
        return 2;
    }
}
</code></pre>

<p>This test will be failed with expected is 2 and actual is 1. When I tried to debug it doesn't call <code>returnTwo</code> but call the original function instead. </p>

<p>I am new to unit testing so what did I miss? Please be considered that the code above is only a demo of what is happened in my actual project. <code>FunctionToBeReplaced</code> is actually a function that execute and return record from database so I want to mock that function. </p>

<p>Thanks :)</p>
",https://stackoverflow.com/questions/60811652/net-framework-xunit-with-moq-unit-testing-keep-calling-the-original-function,"['asp.net', 'unit-testing', 'moq', 'xunit']",165,True,1,1
ES2020 private class methods/fields and testing,"<p>As you may know, <strong>ES2020</strong> is introducing private class methods and fields, similar to what we have currently in typescript
(albeit a different keyword... TS -> private | JS -> #methodName or #fieldName).</p>

<p><strong>Link to the RC (stage 3)</strong>:
<a href=""https://github.com/tc39/proposal-private-methods"" rel=""nofollow noreferrer"">https://github.com/tc39/proposal-private-methods</a></p>

<p>We can currently use this with a <strong>babel plugin</strong>:
<a href=""https://babeljs.io/docs/en/babel-plugin-proposal-private-methods"" rel=""nofollow noreferrer"">https://babeljs.io/docs/en/babel-plugin-proposal-private-methods</a></p>

<p><strong>Tech stack:</strong></p>

<p>I work with Jest and Enzyme for unit testing.</p>

<p><strong>The problem:</strong></p>

<p>The issue I'm facing is that whenever I import a class using these fields or methods and I simply try to reference the wrapper.instance() calling them to test them, I can see that the private method is not visible in the instance (which is correct, since it's private).</p>

<p>An example error: <code>#someMethod is undefined</code></p>

<p>How would you go on approaching this? </p>

<p>Would you skip testing the private methods or is there a solution?</p>
",https://stackoverflow.com/questions/61327123/es2020-private-class-methods-fields-and-testing,"['testing', 'methods', 'jestjs', 'private', 'ecmascript-2020']",978,True,1,1
Unit testing of custom Assert function using Google Test,"<p>I am using Boost.Assert library, and have this custom assert code, which needs to be unit tested using Google Test framework:</p>
<pre class=""lang-cpp prettyprint-override""><code>    #include &lt;boost/assert.hpp&gt;
    #define ASSERT(expr)                BOOST_ASSERT(expr)
    #define ASSERT_MSG(expr, msg)       BOOST_ASSERT_MSG(expr, msg)

    namespace boost {
        inline void assertion_failed_msg(char const* expr, char const* msg, char const* function, char const* /*file*/, long /*line*/) {
            std::cerr &lt;&lt; &quot;Expression '&quot; &lt;&lt; expr &lt;&lt; &quot;' is false in function '&quot; &lt;&lt; function &lt;&lt; &quot;': &quot; &lt;&lt; (msg ? msg : &quot;&lt;...&gt;&quot;) &lt;&lt; &quot;.\n&quot;
                &lt;&lt; &quot;Backtrace:\n&quot; &lt;&lt; boost::stacktrace::stacktrace() &lt;&lt; std::endl;

            std::abort();
        }

        inline void assertion_failed(char const* expr, char const* function, char const* file, long line) {
            ::boost::assertion_failed_msg(expr, 0 /*nullptr*/, function, file, line);
        }
    } // namespace boost
</code></pre>
<p>The idea is to check that <code>ASSERT( 1!=1 )</code> terminates the program with the appropriate error code and error log message.</p>
<p>I am aware of Google Test, Death Tests. I have the following structure, which kind of works for me:</p>
<pre class=""lang-cpp prettyprint-override""><code>void assert_death_test() 
{
    ASSERT( 1!=1 );
}

TEST(unit_test_DeathTest, test_of_assert_function) {
    EXPECT_EXIT(assert_death_test(), ::testing::KilledBySignal(SIGABRT), &quot;Stuff hit the fan.&quot;);
}
</code></pre>
<p>Since I'm using a death test, <code>ASSERT(...)</code> does not terminate unit testing, and death test notices that the program exits with some log message. The problem is this:</p>
<pre><code>Death test: assert_death_test()
    Result: died but not with expected error.
  Expected: contains regular expression &quot;Stuff hit the fan.&quot;
Actual msg:
[  DEATH   ] Expression '1!=1' is false in function 'void assert_death_test()': &lt;...&gt;.
[  DEATH   ] Backtrace:
[  DEATH   ]  0# boost::assertion_failed_msg(char const*, char const*, char const*, char const*, long) in ./executable
[  DEATH   ]  1# boost::assertion_failed(char const*, char const*, char const*, long) in ./executable
[  DEATH   ]  2# assert_death_test() in ./executable
[  DEATH   ]  3# unit_test_DeathTest_test_of_assert_function_Test::TestBody() in ./executable
.
. // Continues with more log messages
.
</code></pre>
<p>Because of this problem, the test is counted as a fail, whereas it normally is a success. (The assert kills program, and sends a log message to stdout)</p>
<p>How can I solve this problem? (Alternative methods are also applicable)</p>
<p>Is there a way to force the output of a test to be successful?</p>
",https://stackoverflow.com/questions/62533438/unit-testing-of-custom-assert-function-using-google-test,"['c++', 'unit-testing', 'boost', 'googletest']",609,True,1,2
Creating an Abstract Interface around DB Connection,"<p>I was reading <a href=""http://softwaretestingfundamentals.com/unit-testing/"" rel=""nofollow noreferrer"">this article</a> on Unit Testing. It seems pretty straightforward, but there was a section that interested me and I wanted to see if someone could please provide an explanation or example of what this means. I think I understand it but maybe not well enough.</p>

<blockquote>
  <p>Write test cases that are independent of each other. For example, if a class depends on a database, do not write a case that interacts with the database to test the class. Instead, create an abstract interface around that database connection and implement that interface with a mock object.</p>
</blockquote>

<p>What does it mean to:</p>

<ol>
<li>create an abstract interface around the db connection?</li>
<li>then implement it with a mock object?</li>
</ol>

<p>I am more questioning the first part (1) but if someone can explain both parts that would be helpful. Thanks.</p>
",https://stackoverflow.com/questions/59943817/creating-an-abstract-interface-around-db-connection,"['java', 'testing']",560,True,1,1
Angular Unit Test if Component calls Http Service method : Error: &lt;spyOn&gt; : could not find an object to spy upon,"<p>My intention is to test if a Component Method calls a Service Method. The service method implementation is a Post, however I am not interested in the post mechanisms as I plan to test this in the service, rather I just want to know if the proper service method was called. </p>

<p>I am new to Unit testing however the error indicates the usage of spyon as follows Usage  spyOn('object, methodName'), indicating that I am not properly creating an instance of the service object to test, however in order to create the service object it requires the HttpClient in the constructor, I have tried so many solutions and I have been reading for hours at this point, help would be greatly appreciate.</p>

<p>Best,
SC</p>

<p>The Unit Test </p>

<pre><code>describe('SchedulerComponent', () =&gt; {
  let component : SchedulerComponent;
  let fixture : ComponentFixture&lt;SchedulerComponent&gt;;
  let schedulerReportService : SchedulerReportService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ SchedulerComponent ],
      imports: [BrowserAnimationsModule,
                MatSlideToggleModule,
                MatRadioModule,
                MatFormFieldModule,
                MatInputModule,
                MatSelectModule,
                MatNativeDateModule,
                MatDatepickerModule,
                NativeDateModule,
                NgxMaterialTimepickerModule,
                ReactiveFormsModule,
                FormsModule,
                HttpClientTestingModule],
      schemas:[CUSTOM_ELEMENTS_SCHEMA],
      providers: [{provide : SchedulerReportService}]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SchedulerComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });

  fit('onSubmit should call scheduleReportService',inject([SchedulerReportService], (service: SchedulerReportService) =&gt; {

    let scheduleServiceSpy = spyOn(schedulerReportService, 'submitScheduledReport') ;
    let submitReportSpy = spyOn(component, 'onSubmit'); 

    submitReportSpy.and.callThrough();

    expect(scheduleServiceSpy).toHaveBeenCalled();


  }))
</code></pre>

<p>The corresponding service code is as follows </p>

<pre><code>@Injectable({
  providedIn: 'root'
})
export class SchedulerReportService {

  constructor(private http: HttpClient) { }

   submitScheduledReport(servicerequest: ScheduleService) {

    console.log(servicerequest)

    // const headers = new HttpHeaders({'key':'value'});
    // return this.http.post&lt;ScheduleService&gt;(localUrl, servicerequest, {headers : headers} ).pipe(
    //   retry(1), catchError(this.handleError&lt;ScheduleService&gt;('scheduled report post error')));

  }
</code></pre>

<p>The component contained a method to trigger the service</p>

<pre><code>export class SchedulerComponent implements OnInit {

  constructor(private fb: FormBuilder,
              private schedulerReportService: SchedulerReportService) { 
    onSubmit(){

    let report = this.schedulerForm.value;
    let scheduleServiceModel = new ScheduleService(report)
    this.schedulerReportService.submitScheduledReport(scheduleServiceModel);

  }
}
</code></pre>
",https://stackoverflow.com/questions/61133970/angular-unit-test-if-component-calls-http-service-method-error-spyon-coul,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",989,True,1,1
How to observe LiveData from Repository?,"<p>I'd like to get a User from my Room database using the Repository, and then observing it in the OverviewFragment.</p>

<p><em>What I tried:</em></p>

<ul>
<li><p>using an Observer in the fragment, but I got a NullPointerException.</p></li>
<li><p>using <code>@{overviewViewModel.user.email}</code> in fragment_overview.xml: the application runs but nothing is displayed.</p></li>
<li><p>Unit Testing and Instrumented Testing with a FakeRepository. The tests pass and the data are displayed.</p></li>
</ul>

<p><em>What I use:</em></p>

<ul>
<li><p>Android Studio (up to date)</p></li>
<li><p>Kotlin</p></li>
<li><p>MVVM architecture</p></li>
<li><p>Repository pattern linked to a Room database</p></li>
<li><p>Constructor dependency injection (for the viewmodels)</p></li>
<li><p><a href=""https://proandroiddev.com/why-service-locator-is-so-unpopular-bbe8678be72c"" rel=""nofollow noreferrer"">ServiceLocator</a> pattern for testing</p></li>
</ul>

<p><em>User Flow (Navigation)</em></p>

<p>The User opens the app, fills a form and clicks the registration button in the RegistrationFragment, then navigates to the OverviewFragment, where his data (Email, Password) are displayed.</p>

<p><strong>RegistrationViewModel:</strong></p>

<pre><code>class RegistrationViewModel(private val repository: IUserRepository) : ViewModel() {

    private var viewModelJob = Job()
    private val uiScope = CoroutineScope(Dispatchers.Main +  viewModelJob)

    private val _user = MutableLiveData&lt;User&gt;()

    val user: LiveData&lt;User&gt;
        get() = _user

    val email = MutableLiveData&lt;String&gt;()
    val password = MutableLiveData&lt;String&gt;()

    [...]

    fun onRegister() {

        val userEmail = email.value.toString()
        val userPassword = password.value.toString()

        registerUser(User(userEmail, userPassword))
    }

    private fun registerUser(newUser: User) = uiScope.launch {
        repository.registerUser(newUser)
    }

    [...]
}
</code></pre>

<p><strong>OverviewViewModel</strong></p>

<pre><code>class OverviewViewModel(val database: UserDatabaseDao,
                        private val userRepository: IUserRepository
) : ViewModel() {

    private val _user = MutableLiveData&lt;User&gt;()

    val user: LiveData&lt;User&gt;
        get() = _user

    init {
        getUser()
    }

    private fun getUser() {
        runBlocking {_user.value = userRepository.getUser().value }
    }
</code></pre>

<p><strong>OverviewFragment:</strong></p>

<pre><code>class OverviewFragment : Fragment() {

[...]
        overviewViewModel.user.observe(this, Observer {
                binding.apply {
                    textview.text = overviewViewModel.user.value!!.email
                    textview2.text = overviewViewModel.user.value!!.password
                }
        })
        return binding.root
    }
}
</code></pre>

<p><strong>Repository:</strong></p>

<pre><code>class UserRepository(private val dataSource: UserDatabaseDao,
                     private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO) :
    IUserRepository {

    override suspend fun registerUser(user: User) = withContext(ioDispatcher) {
        dataSource.insert(user)
    }

    override suspend fun getUser(): LiveData&lt;User?&gt; = withContext(ioDispatcher) {
        return@withContext dataSource.getUser()
    }

    override suspend fun getUser(email: String): LiveData&lt;User?&gt; = withContext(ioDispatcher) {
        return@withContext dataSource.getUser(email)
    }
}
</code></pre>

<p><strong>DatabaseDao:</strong></p>

<pre><code>@Dao
interface UserDatabaseDao {

    @Insert
    fun insert(user: User)

    @Query(""SELECT * from user_table WHERE email = :key"")
    fun getUser(key: String): LiveData&lt;User?&gt;

    @Query(""SELECT * from user_table"")
    fun getUser(): LiveData&lt;User?&gt;

    @Query(""SELECT * from user_table"")
    fun getAllUsers(): LiveData&lt;List&lt;User&gt;&gt;

}
</code></pre>

<p>Note: there's only one user in the database, the one that fills the form in the RegistrationFragment.</p>
",https://stackoverflow.com/questions/59888501/how-to-observe-livedata-from-repository,"['android', 'kotlin', 'mvvm', 'repository', 'android-livedata']",2035,False,1,0
Jest Typescript Mock specific classes exported by module but not all,"<p>I've been trying to figure out how to best mock specific classes that are exported from a node module. In this case, I have the code that uses the classes <code>Message</code> and <code>TextChannel</code> and <code>MessageAttachment</code> from <code>discord.js</code>. I want to mock Message and TextChannel so I can easily set them up for unit testing, but I want the functionality <code>MessageAttachment</code> to remain, so I can't just <code>jest.mock(&quot;discord.js&quot;)</code>.</p>
<p>I've tried something similar to:</p>
<pre><code>const MockedMessage = jest.Mock&lt;Message&gt;;
const message = new MockedMessage();
message.content = &quot;test&quot;
...
</code></pre>
<p>That works fine <em>if the discord.js module is mocked</em>. However, as stated above, mocking that also mocks the <code>MessageAttachment</code> class, whose functionality I want to keep instead of mocking.</p>
<p>I looked at <a href=""https://stackoverflow.com/questions/57772569/mock-a-specific-class-from-a-node-module-in-jest"">Mock a specific class from a node module in jest</a> - but this approach doesn't seem like it would work when using TypeScript unless I am really missing something.</p>
<p>I've also looked in to trying to and then using</p>
<pre><code>import * as Discord from 'discord.js'
jest.mock('discord.js')
const {MessageAttachment} = jest.requireActual('discord.js');
Object.defineProperty(Discord, 'MessageAttachment', MessageAttachment);
</code></pre>
<p>but that doesnt seem to work either</p>
",https://stackoverflow.com/questions/63208575/jest-typescript-mock-specific-classes-exported-by-module-but-not-all,"['typescript', 'mocking', 'jestjs']",361,False,1,0
Flutter BLoC Testing,"<p>I am using the flutter_bloc library and trying to do unit testing.
I am doing this pretty much as explained in <a href=""https://medium.com/flutter-community/unit-testing-with-bloc-b94de9655d86"" rel=""nofollow noreferrer"">this tutorial</a> and it's doing fine. </p>

<p>However, if a BlocState which extends Equatable (which required) has many properties or large list of items which extends Equatable, as well with their props[] defined as required. </p>

<p>This makes hard for the <code>expectLater()</code> to match proper emitted states because it tries to match the exact instance with its content and not only the state type or instance of.</p>

<p>For example: </p>

<p>Consider the following State class:</p>

<pre><code>class BlocState extends Equatable{
     final List&lt;String&gt; data;
     BlocState({this.data});

     @override
     List&lt;Object&gt; get props =&gt; [data];
}
</code></pre>

<p>Then for emitted state like this:</p>

<pre><code>List&lt;String&gt; data = ['Mark', 'Mike', 'John']
BlocState({data: data}); 
</code></pre>

<p>This expectLater will fail  </p>

<pre><code> expectLater(
    bloc,
    emitsInOrder([BlocState(),]), //This will fail as the state does't equals exactly to the real state
  )
</code></pre>

<p>And this one will pass: </p>

<pre><code>expectLater(
    bloc,
    emitsInOrder([BlocState(data: ['Mark', 'Mike', 'John']),]), //This will pass 
  )
</code></pre>

<p>On such simple state it's fine to verify exact content, but if the list will have 100 items how it can be tested?</p>

<p>Is there a way to verify just the instance type without the content?</p>
",https://stackoverflow.com/questions/62280312/flutter-bloc-testing,"['flutter', 'flutter-test', 'flutter-bloc']",1704,True,1,2
How to capture arguments from Swift generic function,"<p>I have a Swift protocol that defines a generic function for making network requests. It looks something like this:</p>
<pre><code>protocol TaskManagerProtocol {
    func run&lt;V&gt;(
        task: Task&lt;V&gt;,
        completion: @escaping (Result&lt;V, Error&gt;) -&gt; Void
    )
}
</code></pre>
<p>This works great in production code, letting me make requests that receive different types of results. So far, so good.</p>
<p><strong>The problem:</strong> For unit testing, I want a Test Spy that captures the arguments, especially the closure. The spy looks like this:</p>
<pre><code>class TaskManagerSpy&lt;Value&gt;: TaskManagerProtocol {
    var callCount = 0
    var task: [Task&lt;Value&gt;] = []
    var completion: [(Result&lt;Value, Error&gt;) -&gt; Void] = []

    func run&lt;V&gt;(
        task: Task&lt;V&gt;,
        completion: @escaping (Result&lt;V, Error&gt;) -&gt; Void
    ) {
        guard V.self == Value.self else {
            fatalError(&quot;run&lt;V&gt; doesn't match init&lt;Value&gt;&quot;)
        }
        callCount += 1
        self.task.append(task)
        self.completion.append(completion)
    }
}
</code></pre>
<p>My intention is to have test code instantiate <code>TaskManagerSpy&lt;SomeType&gt;</code> and inject that into the System Under Test, which calls <code>run&lt;V&gt;(task:completion:)</code>. But as it stands, the <code>append()</code> calls fail to compile:</p>
<pre><code>Cannot convert value of type 'Task&lt;V&gt;' to expected argument type 'Task&lt;Value&gt;'
</code></pre>
<p>and the same for the closure. If I comment out these lines, the test succeeds without triggering the fatal error.</p>
<p><strong>Question:</strong> I have demonstrated that the types are the same. Is there a way to coerce one type into the other, so that I can capture the arguments?</p>
",https://stackoverflow.com/questions/65349973/how-to-capture-arguments-from-swift-generic-function,"['swift', 'generics', 'xctest']",319,True,1,2
Mockito UnfinishedStubbingException thrown on a JUnit test case which calls a void ServiceImplementationLayer method,"<p>I am using Mockito/JUnit on a Maven project for a console-based application with a DAO design pattern. My IDE is Spring Toools Suite 3.</p>
<p>The problem is that I am getting an <code>UnfinishedStubbingException</code> every time I run this particular test on my particular JUnit test, and I don't know why that is since the syntax looks correct. I am <strong>very new</strong> to unit testing and Mockito, but I assume that this is occurring because the level of abstraction from one layer to the next is confusing Mockito for some reason. Therefore, I initially tried to use a <em>Spy</em> versus a <em>Mock</em> on the service object in the test case (but then the <code>NotAMockException</code> is being thrown instead).</p>
<p>Any advice and/or recommendations how to resolve this issue will be appreciated.</p>
<p>Here is the stack trace:</p>
<pre><code>org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-&gt; at com.revature.testing.BankAccountEvaluationService.testMakeDeposit_ValidUserId(BankAccountEvaluationService.java:91)

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 com.revature.testing.BankAccountEvaluationService.testMakeDeposit_ValidUserId(BankAccountEvaluationService.java:91)
    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.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:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
</code></pre>
<p>Here is the sample code:</p>
<p><code>BankAccountEvaluationTest</code> class:</p>
<pre><code>@InjectMocks
private AccountServiceImpl service;

@Mock
private AccountDaoImpl daoMock;

@Before
public void setUp() {
    service = Mockito.spy(new AccountServiceImpl());
    MockitoAnnotations.initMocks(this);
}

@Test
public void testMakeDeposit_ValidUserId() {
    //setup
    Account account = Mockito.mock(Account.class);
    account.setAccountId(1);
    double amount = 20.50;
    //gives UnfinishedStubbingException -&gt; Mockito doesn't like this because it's mocking within a mocking object
    //doNothing().when(daoMock).updateAccountBalance(account.getBalance() + amount, accountNumber); //Solution?
    
    //run
    service.makeDeposit(amount, account.getAccountId());
    
    //verify
    verify(service, times(1)).makeDeposit(amount, account.getAccountId());
}
</code></pre>
<p><code>AccountServiceImpl</code> class:</p>
<pre><code>package com.revature.serviceimpl;
import java.util.List;

import org.apache.log4j.Logger;
import com.revature.dao.AccountDao;
import com.revature.daoimpl.AccountDaoImpl;
import com.revature.model.Account;
import com.revature.service.AccountService;

public class AccountServiceImpl implements AccountService {
    private static Logger logger = Logger.getLogger(AccountServiceImpl.class);
    private AccountDao accountDao = new AccountDaoImpl();
    
    //other overridden methods from AccountService interface

    @Override
    public void makeDeposit(double addedCash, int id) {
        logger.info(&quot;Sending deposit request to the database.&quot;);
        // find the account
        Account account = accountDao.selectAccountByAccountId(id);
        System.out.println(account);
        // set new balance
        account.setBalance(account.getBalance() + addedCash);
        double myNewBalance = account.getBalance();
        logger.info(&quot;New balance: &quot; + account.getBalance());
        logger.info(&quot;Updating account balance to account number &quot; + id);
        // update the database
        accountDao.updateAccountBalance(myNewBalance, id);
    }
}
</code></pre>
<p><code>AccountDaoImpl</code> class:</p>
<pre><code>package com.revature.daoimpl;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.revature.dao.AccountDao;
import com.revature.model.Account;
import com.revature.model.AccountStatus;
import com.revature.model.AccountType;

public class AccountDaoImpl implements AccountDao {
    private static Logger logger = Logger.getLogger(UserDaoImpl.class);

    private static String url = MY_URL;
    private static String dbUsername = MY_DATABASE_NAME;
    private static String dbPassword = MY_DATABASE_PASSWORD;

    //other overridden methods from AccountDao interface

    @Override
    public void updateAccountBalance(double balance, int id) {
        try (Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword)) {

            String sql = &quot;UPDATE accounts SET account_balance = ?  WHERE account_id = ?;&quot;;
            PreparedStatement ps = conn.prepareStatement(sql);

            ps.setDouble(1, balance);
            ps.setInt(2, id);
            ps.executeUpdate();
            logger.info(&quot;new balance is now set&quot;);
        } catch (SQLException e) {
            logger.warn(&quot;Error in SQL execution to update balance. Stack Trace: &quot;, e);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/64725199/mockito-unfinishedstubbingexception-thrown-on-a-junit-test-case-which-calls-a-vo,"['java', 'spring', 'maven', 'mockito', 'junit4']",1093,True,1,2
NGXS: Testing Asynchronous Actions: Automatic subscription doesn&#39;t work,"<p><strong>from official website NGXS</strong></p>

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

<ol>
<li>I write unit tests for NGXS store(Jasmine + Karma, angular 2)</li>
<li>In NGXS store in Asynchronous Actions(it's like Effect in NGRX) we don't subscribe inside - we just return observable. And it's fine, because the automatics subscription works.</li>
<li>BUT when I launch my tests, the automatic subscription on Asynchronous Actions(EFFECTS) - just doesn't work. As the result - test failed. </li>
<li>To sum up - I can't test Asynchronous Actions NGXS</li>
<li>What I have already  tried : 
1) I wrote like in the official website NGXS(in the picture) 2)I tried it(done()) construction, 3) I tried actions$.subscribe() construction.</li>
<li>It works when I make manually - .subscribe() in the Action - but it's problem, because it have to work without this </li>
<li>This is link to official page: <a href=""https://www.ngxs.io/recipes/unit-testing"" rel=""nofollow noreferrer"">https://www.ngxs.io/recipes/unit-testing</a> (topic : Testing Asynchronous Actions)
Please, help :)</li>
</ol>
",https://stackoverflow.com/questions/60205311/ngxs-testing-asynchronous-actions-automatic-subscription-doesnt-work,"['angular', 'unit-testing', 'jasmine', 'store', 'ngxs']",297,True,1,2
Dependency Injection in ExpressJS,"<p>I'm learning about Dependency Injection and trying to use it in a simple nodejs app. This application has to fetch some data with an external API. Using DI in that case was simple, I just added the dependency as a parameter of the function and it worked like a charm.</p>

<pre><code>async function foo(URL,get_data){
    var bar = await get_data(URL);

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

<p>When the application is running, <code>get_data</code> would be the function that does the real request and when unit testing my app it would be a dummy function.</p>

<p>How do I apply this same methodology for ExpressJS?  </p>

<p>I want it to access the database when is using the application and dummy data when it is testing, but I can't figure out how because I'm not dealing with properties of functions anymore.</p>

<p>In this example:</p>

<pre><code>// index.js
const express = require('express');
const app     = express();
const PORT = process.env.PORT || 5000;
var db = require('./model/db')

app.get('/users',(req,res) =&gt;{
    db.get_users(function(users){
        res.send(users);
    })
});

app.listen(PORT, () =&gt; console.log(`Server listening to port: ${PORT}`));

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

<p>I need to use the real db when the server is running and a mock one when testing with supertest.</p>

<pre><code>// index.text.js
const request = require('supertest');
const app = require('index');

describe(""GET /user"", function(){
    it('should respond with a json', function(done){
        request(app)
            .get('/users')
            .expect('Content-Type',/json/)
            .expect(200,done);
    });
});
</code></pre>
",https://stackoverflow.com/questions/60786544/dependency-injection-in-expressjs,"['javascript', 'node.js', 'express']",247,False,0,0
Why does Jenkins multibranch pipeline job page show junit test result for each stage of pipeline which makes count of test incorrect,"<p>I am using Jenkins Ver:2.176.3 for declarative multibranch pipeline.
I have junit test in my application code base and using maven surefire plugin to run unit test using maven command.</p>

<p>Multibranch job page shows 'Test Result' link and 'Test Result Trend' graph also.
I think this is being displayed/published here due to plugin 'test-results-analyzer'.</p>

<p>In declarative pipeline we have two stages as shown in code sample and we use maven commands.
Now my problem is that this test result count same unit test for each stage of pipeline so the count of unit tests are being double on this Test Result of Jenkins job page.</p>

<p>I tried skipping unit test in stage 'package-IT' using maven option -DskipTests and as per log it does skip unit testing but still see the duplicate test results.</p>

<p>if know please suggest</p>

<pre><code>stages{ 
                        stage('compile-N-test') {
                            agent {label 'agent'}
                            steps {
                                script {
                                    // mvn clean test
                                }
                            }
                        }

                        stage('packaging-IT') {
                            agent {label 'agent'}                           
                            steps {
                                script {
                                    //mvn verify                                
                                }
                            }
                        }   
</code></pre>
",https://stackoverflow.com/questions/61846777/why-does-jenkins-multibranch-pipeline-job-page-show-junit-test-result-for-each-s,"['maven', 'unit-testing', 'jenkins', 'multibranch-pipeline', 'test-results']",598,False,0,1
Make multiple axios calls using jest,"<p>I am working with rest js using typescript and I am trying to mock multiple API calls using jest for unit testing.</p>
<p>My api calls are in the following format:</p>
<pre><code>await axios.request({
    method: 'POST',
    url: //api url,
      data: {},
    headers: {}
  })
  .then()
  .catch()
</code></pre>
<p>I am mocking the axios as follows:</p>
<pre><code>jest.mock('axios', () =&gt; {
  return {
    request: jest.fn().mockResolvedValue({
      data: ['responseData', 'responseData1']
        headers: //response header
    })
  }
});
</code></pre>
<p>The test case for api call is created as follows:</p>
<pre><code>expect(axios.request).toHaveBeenCalled(); expect(axios.request).toHaveBeenCalledWith({ 
method: 'POST', 
url: //api url, 
data: {}, 
headers: {} 
});
</code></pre>
<p>For multiple API calls, I am mocking it multiple times with different response data but it is taking the last mocked value as the response of all the API calls in the test cases.</p>
<p>for example: for multiple data mocks like:</p>
<pre><code>jest.mock('axios', () =&gt; {
  return {
    request: jest.fn().mockResolvedValue({
      data: ['responseData', 'responseData1']
        headers: //response header
    })
  }
});
</code></pre>
<pre><code>jest.mock('axios', () =&gt; {
  return {
    request: jest.fn().mockResolvedValue({
      data: ['secondResponseData', 'secondResponseData1']
        headers: //response header
    })
  }
});
</code></pre>
<p>when I am running the test cases I am getting the response for all my apis as:</p>
<pre><code>data: ['secondResponseData', 'secondResponseData1']
headers: //response header

data: ['secondResponseData', 'secondResponseData1']
headers: //response header
</code></pre>
<p>instead of:</p>
<pre><code>data: ['responseData', 'responseData1']
headers: //response header

data: ['secondResponseData', 'secondResponseData1']
headers: //response header
</code></pre>
<p>I don't know how to mock the correct response with the correct api call in the test cases. Is there any way that I can mock the correct response with the API calls?</p>
",https://stackoverflow.com/questions/64314754/make-multiple-axios-calls-using-jest,"['reactjs', 'axios', 'jestjs', 'mocking']",4127,False,0,2
Failing following the basic QUnit for GAS tutorial,"<p>I tried to follow rigorously this basic ""QUnit for Google Apps Script"" tutorial: <a href=""https://blog.ohheybrian.com/2019/11/unit-testing-gas-part-1-qunit-setup/"" rel=""nofollow noreferrer"">https://blog.ohheybrian.com/2019/11/unit-testing-gas-part-1-qunit-setup/</a></p>

<p>But when I connect to the deployed web-app, I get this error ""Error: An error has occurred on the server. We apologize for this and invite you to try again later. (line 0, ""undefined"" file)"".</p>

<p><img src=""https://i.stack.imgur.com/pSPWr.png"" alt=""QUnit for GAS web-app error""></p>

<p>So I tried to make a basic web-app with just this code to make sure a simple web-app works fine: </p>

<pre><code>function doGet(e) {
  var params = JSON.stringify(e);
  return HtmlService.createHtmlOutput(params);
}
</code></pre>

<p>And it works.</p>

<p>But when I just had this line ""QUnit.helpers(this);"" and the QUnit library, I get the error message mentioned before.</p>

<p>Any idea of what is wrong?</p>

<p>I'm really surprised that Google Developers still not provide a builtin testing framework for GAS and related tutorials. It could encourages to make clean code.</p>

<p>Best regards,
Florent</p>
",https://stackoverflow.com/questions/60408490/failing-following-the-basic-qunit-for-gas-tutorial,"['unit-testing', 'google-apps-script', 'tdd', 'qunit']",109,False,0,0
What is &#39;should create&#39; test case in Jasmine,"<p>I'm new to Unit testing in Angular using Jasmine and Karma. I'm an intern. I was going through a spec file. I want to know what is meant by <em>should create</em> in this context. <strong>TimeselectorComponent</strong> is the component that I want to test. I took the code from my senior. The code is like this:</p>

<pre><code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () =&gt; {
    let fixture: ComponentFixture&lt;TimeselectorComponent&gt;;

    beforeEach(async(() =&gt; {

        TestBed.configureTestingModule({
            imports: [
                ...
            ],
            providers: [...],
            declarations: [TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(TimeselectorComponent);
    });

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

    // other test cases
});
</code></pre>

<p>There are other test cases also but for now I'm curious about <strong>'should create'</strong> case. My understanding says that it is trying to test whether the component was initialized/created or not. Please correct me if I'm wrong. Please tell me more about the above code. Would like to know about <code>compileComponent()</code> method also. I checked this link but could understand only a little:</p>

<p><a href=""https://github.com/angular/angular-cli/issues/4774"" rel=""nofollow noreferrer"">compileComponents() is asynchronous, we must use async()</a></p>

<p>I'm going through this question also:</p>

<p><a href=""https://stackoverflow.com/questions/40432734/error-please-call-testbed-compilecomponents-before-your-test"">Error: Please call “TestBed.compileComponents” before your test</a></p>
",https://stackoverflow.com/questions/62118384/what-is-should-create-test-case-in-jasmine,"['angular', 'unit-testing', 'karma-jasmine']",744,True,0,2
How to test the returned value of a method [Jasmine],"<p>I'm new in unit testing using Jasmine and Karma. My question is very much similar to this:</p>

<p><a href=""https://stackoverflow.com/questions/55230057/how-to-unit-test-return-value-of-function-angular-jasmine-karma"">How to unit test return value of function - Angular (Jasmine/Karma)</a></p>

<p>But mine is different as I want to check the length of the returned value instead of the value itself. I've a method which takes <code>n</code> as a number. If the number is below 10 then the method should return the same number but with a preceding <strong>0</strong> as string. Valid range is <strong>0 to 12</strong> (actually it is a part of month picker component. I'm trying to achieve <code>MM</code> format.). For e.g if <strong>5</strong> is input then the returned value should be <strong>05</strong> as string. Here's the code:</p>

<pre><code>convertToDoubleDigit(n) {
    n = String(n);
    if (n.length === 1) {
        n = '0' + n;
    }
    return n;
}
</code></pre>

<p>and my test case is:</p>

<pre><code>it('should call convertToDoubleDigit and convert to double digit', () =&gt; {
    fixture.componentInstance.convertToDoubleDigit(2);
    expect(fixture.componentInstance.length) &lt;----- This is what I'm asking
})
</code></pre>

<p>I know that I should do something like:</p>

<p><code>expect(fixture.componentInstance......length).toBe(2)</code></p>

<p>Please help me test this part. I'm unable to think out of the box.</p>
",https://stackoverflow.com/questions/61736389/how-to-test-the-returned-value-of-a-method-jasmine,"['angular', 'unit-testing', 'jasmine']",4609,True,0,1
JUnit 5 Unit Testing Get and Post methods,"<p>I am new to spring boot and Junit testing. I am facing problem in testing Rest Api's Get and Post method. Many tutorials online guide about the use of mockMvc in JUnit testing. But are those still valid for JUnit 5. </p>

<pre><code>@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = RegisterRestController.class)
class RegisterRestControllerTest {
  @Autowired
  private MockMvc mockMvc;

  @Autowired
  private ObjectMapper objectMapper;

  @MockBean
  private RegisterUseCase registerUseCase;

  @Test
  void whenValidInput_thenReturns200() throws Exception {
    mockMvc.perform(...);
  }

}
</code></pre>

<p>However I read a article that you don't need to include @ExtendWith extension from SpringBoot 2.1 onwards.
Since Junit 5 and spring boot both updated with lot of changes from previous version it has become difficult to analyse which code available online is correct regarding testing. 
I am not able to use MockMvc.perform().andExpect(status().isOk()).</p>

<pre><code>mockMvc.perform(post(""/forums/{forumId}/register"", 42L)
    .contentType(""application/json"")
    .param(""sendWelcomeMail"", ""true"")
    .content(objectMapper.writeValueAsString(user)))
    .andExpect(status().isOk());
</code></pre>

<p>What is the correct use of testing Get and post methods. And testing Rest verbs comes under unit testing or integration testing?</p>

<p>Also guide me good source to check updated features of Junit 5 with Spring Boot(JUnit 5 doc is not helpful in my case).</p>
",https://stackoverflow.com/questions/61935864/junit-5-unit-testing-get-and-post-methods,"['spring-boot', 'unit-testing', 'spring-mvc', 'junit5', 'spring-restcontroller']",4625,True,0,1
Framework Usage in C,"<p>There are a lot of frameworks for C ,but most of them just give the frameworks file ,but don't explain how to link them to an IDE,what i did was include the header file of the frameworks ,but most of them had some more header file dependencies which i most of the times could not find anywhere in the framework ,I am a beginner and have no experience in framework usage.
It would help me a lot if someone explains me in steps how to link an IDE(Visual Studio,CodeBlocks or any other) to a framework.</p>

<p>I am searching for a unit testing tool based on Embedded C language(searching for a framework).I got many many frameworks like GOOGLE Test Framework,CUnit Framework,Embunit framework,AceUnit Framework and many more ,but couldn't find how to integrate with an IDE.</p>
",https://stackoverflow.com/questions/62003997/framework-usage-in-c,"['c++', 'c', 'frameworks', 'ide']",144,False,0,0
Testing @ControllerAdvice NO REST,"<p>My question is: How can I test if EmailNotSendHandler is used when EmailNotSendException is thrown?
or
Second question: Whats the correct terminology to solve this Exception handling riddle?</p>

<p>**GOAL: Test to see if EmailNotSendHandler class is called when EmailNotSendException exception is thrown. WITH NO REST ANYTHING CONTROLLER **</p>

<p>Im fairly new to programming and do <strong>NOT KNOW</strong> the correct <strong>TERMINOLOGY</strong>. Im trying to learn pure Unit testing and exception handling with Spring, <strong>INTERNAL</strong> to the Spring Boot application. I've googled on how to test. Every search result boils down to: Write REST controllers so you can do REST calls to REST controller. I do not want to write REST controller for its out of scope of learning goals.
Bassically anything that contains REST something is out of scope. </p>

<p>The @ControllerAdvice annotated class. </p>

<pre><code>@ControllerAdvice
@Slf4j
public class EmailNotSendHandler {
    @ExceptionHandler(EmailNotSendException.class)
    private void processEmailNotSendExceptions(EmailNotSendException e){
        log.info(""[QUATRO] Error handling? {}"", e.getMessage());
    }
}
</code></pre>

<p>The exception class.</p>

<pre><code>public class EmailNotSendException extends RuntimeException {
     public EmailNotSendException(String error) {
         super(""test: "" + error);
     }
}
</code></pre>

<p>The EmailService class</p>

<pre><code>@Service
public class EmailService {
    private final JavaMailSender emailSenderContainer;

    @Value(""email@email.email"")
    private String receivingEmailAdress;

    public void sendSimpleMessage(String emailText) {
        SimpleMailMessage message = new SimpleMailMessage();

        if (emailTekst.isEmpty()) {
            return;
        }
        message.setTo(receivingEmailAdress);
        message.setSubject(""Error"");
        message.setText(emailText);
        emailSenderContainer.send(message);
    }
}
</code></pre>

<p>The Unit test</p>

<pre><code>@Test()
public void testSimpleMailMessageSendFailed() {
    doThrow(new EmailNotSendException("""")).when(emailServiceMocked).sendSimpleMessage("""");
    emailServiceMocked.sendSimpleMessage("""");
}
</code></pre>
",https://stackoverflow.com/questions/62406821/testing-controlleradvice-no-rest,"['java', 'spring-boot', 'junit']",235,False,0,0
Testing a Redux connected component with enzyme and jest,"<p>I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a  and then shallow mounting it. However I am not able to run assertions after updating the props of component, nor I am able to spy on the class methods being called or not.</p>

<p>Below is my sample code:</p>

<pre><code>const wrapper = shallow(
    &lt;Provider store={store}&gt;
        &lt;TestComponent {...props}  /&gt;
    &lt;/Provider&gt;
).dive();
</code></pre>

<p>Now when I try t set the props of the wrapper and run assertions, it fails:</p>

<pre><code>wrapper.setProps({
  showHeader:  true
})
expect(wrapper.find('h1')).toHaveLength(1);
</code></pre>

<p>Interesting part is, if I export the unconnected component as also <a href=""https://redux.js.org/recipes/writing-tests/#connected-components"" rel=""nofollow noreferrer"">suggested</a> in redux docs, the assertions work well. Is it fine to export the unconnected component just for the purpose of testing? I can't spy on instance methods/lifecycle methods if I try to test the connected component.</p>
",https://stackoverflow.com/questions/60256195/testing-a-redux-connected-component-with-enzyme-and-jest,"['reactjs', 'unit-testing', 'redux', 'jestjs', 'enzyme']",1098,False,0,1
Cannot shallowMount a Vue Compoent for unit testing,"<p>I'm new to Vue, but have a project with a login page. I can run it fine, but I'm trying to retro-add unit-testing (I know, I'm doing this backwards). I'm using Mocha + Chai and vue test utils. when I try to shallowMount I get an error saying that it cannot read a property. Here is the full error text:</p>

<pre><code>  1) Login
       Has login text:
     TypeError: Cannot read property 'email' of undefined
      at Proxy.render (webpack:///./src/views/user/Login.vue?./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options:65:34)
      at VueComponent.Vue._render (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:3640:22)
      at VueComponent.updateComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4168:21)
      at Watcher.get (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4582:25)
      at new Watcher (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4569:45)
      at mountComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4175:3)
      at VueComponent.Vue.$mount (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:8512:10)
      at init (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:3232:13)
      at createComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:6053:9)
      at createElm (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:6001:9)
      at VueComponent.patch [as __patch__] (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:6611:7)
      at VueComponent.Vue._update (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4039:19)
      at VueComponent.updateComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4168:10)
      at Watcher.get (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4582:25)
      at new Watcher (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4569:45)
      at mountComponent (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:4175:3)
      at VueComponent.Vue.$mount (webpack:///./node_modules/vue/dist/vue.runtime.esm.js?:8512:10)
      at mount (webpack:///./node_modules/@vue/test-utils/dist/vue-test-utils.js?:13265:21)
      at shallowMount (webpack:///./node_modules/@vue/test-utils/dist/vue-test-utils.js?:13278:10)
      at Context.eval (webpack:///./tests/unit/login.spec.js?:17:87)
      at processImmediate (internal/timers.js:439:21)
</code></pre>

<p>Here is my packages file:</p>

<pre><code>{
  ""name"": ""client"",
  ""version"": ""0.1.0"",
  ""private"": true,
  ""scripts"": {
    ""serve"": ""vue-cli-service serve"",
    ""build"": ""vue-cli-service build"",
    ""test:unit"": ""vue-cli-service test:unit"",
    ""test:e2e"": ""vue-cli-service test:e2e"",
    ""test"": ""mochapack --webpack-config webpack.config.js --require tests/setup.js tests/**/*.spec.js""
  },
  ""dependencies"": {
    ""axios"": ""^0.19.2"",
    ""core-js"": ""^3.6.4"",
    ""vue"": ""^2.6.11"",
    ""vue-axios"": ""^2.1.5"",
    ""vue-router"": ""^3.1.5"",
    ""vuelidate"": ""^0.7.5"",
    ""vuetify"": ""^2.1.0"",
    ""vuex"": ""^3.1.2""
  },
  ""devDependencies"": {
    ""@vue/cli-plugin-babel"": ""^4.2.0"",
    ""@vue/cli-plugin-e2e-cypress"": ""^4.2.0"",
    ""@vue/cli-plugin-router"": ""^4.2.0"",
    ""@vue/cli-plugin-unit-mocha"": ""^4.2.0"",
    ""@vue/cli-plugin-vuex"": ""^4.2.0"",
    ""@vue/cli-service"": ""^4.2.0"",
    ""@vue/test-utils"": ""^1.0.0-beta.31"",
    ""chai"": ""^4.1.2"",
    ""jsdom"": ""^16.1.0"",
    ""jsdom-global"": ""^3.0.2"",
    ""mocha"": ""^7.0.1"",
    ""mochapack"": ""^1.1.13"",
    ""node-sass"": ""^4.12.0"",
    ""sass"": ""^1.19.0"",
    ""sass-loader"": ""^8.0.2"",
    ""vue-cli-plugin-vuetify"": ""^2.0.4"",
    ""vue-template-compiler"": ""^2.6.11"",
    ""vuetify-loader"": ""^1.3.0""
  }
}
</code></pre>

<p>Here is my component code:</p>

<pre><code>&lt;template&gt;
  &lt;v-container fluid fill-height&gt;
    &lt;v-layout align-center justify-center&gt;
      &lt;v-flex xs12 sm8 md4&gt;
        &lt;v-card class=""elevation-12""&gt;
          &lt;v-toolbar color=""primary"" dark flat&gt;
            &lt;v-toolbar-title&gt;Login form&lt;/v-toolbar-title&gt;
          &lt;/v-toolbar&gt;
          &lt;v-card-text&gt;
            &lt;v-form @submit.prevent=""login""&gt;
              &lt;v-text-field
                autofocus
                v-model=""email""
                label=""Email""
                prepend-icon=""mdi-account-circle""
                @blur=""$v.email.$touch()""
              /&gt;
              &lt;div class=""red--text text--lighten-1"" v-if=""$v.email.$error""&gt;
                &lt;div v-if=""!$v.email.required""&gt;
                  &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                  Email is required
                &lt;/div&gt;
                &lt;div v-if=""!$v.email.email""&gt;
                  &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                  Invalid email address.
                &lt;/div&gt;
              &lt;/div&gt;

              &lt;v-text-field
                v-model=""password""
                :type=""showPassword ? 'text' : 'password'""
                label=""Password""
                prepend-icon=""mdi-lock""
                :append-icon=""showPassword ? 'mdi-eye' : 'mdi-eye-off'""
                @click:append=""showPassword = !showPassword""
                @blur=""$v.password.$touch()""
              /&gt;

              &lt;div
                class=""red--text text--lighten-1""
                v-if=""$v.password.$error &amp;&amp; !$v.password.required""
              &gt;
                &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                Password is required
              &lt;/div&gt;

              &lt;v-btn
                type=""submit""
                color=""success""
                name=""button""
                :disabled=""$v.$invalid""
              &gt;
                Login now
              &lt;/v-btn&gt;

              &lt;v-btn
                text
                small
                color=""primary""
                :to=""{ name: 'forgotPassword' }""
              &gt;
                Forgot your password?
              &lt;/v-btn&gt;

              &lt;div v-if=""error"" class=""red--text text--lighten-1""&gt;
                &lt;v-icon color=""red""&gt;mdi-alert-circle-outline&lt;/v-icon&gt;
                {{ getLoginErrorMsg() }}
              &lt;/div&gt;
            &lt;/v-form&gt;
          &lt;/v-card-text&gt;
        &lt;/v-card&gt;
      &lt;/v-flex&gt;
    &lt;/v-layout&gt;
  &lt;/v-container&gt;
&lt;/template&gt;

&lt;script&gt;
import { required, email } from ""vuelidate/lib/validators"";

export default {
  name: ""Login"",

  data() {
    return {
      email: """",
      password: """",
      error: null,
      showPassword: false
    };
  },

  validations: {
    email: {
      required,
      email
    },
    password: {
      required
    }
  },

  methods: {
    login() {
      console.log(""Entering component login method"");

      this.$store
        .dispatch(""user/login"", {
          username: this.email,
          password: this.password
        })
        .then(() =&gt; {
          console.log(
            'this.$store.getters[""user/passwordChangeRequired""]' +
              this.$store.getters[""user/passwordChangeRequired""]
          );
          if (this.$store.getters[""user/passwordChangeRequired""]) {
            console.log(""push to changePassword"");
            this.$router.push({ name: ""changePassword"" });
          } else {
            console.log(""pushing to home"");
            this.$router.push({ name: ""home"" });
          }
        })
        .catch(err =&gt; {
          this.error = err.response;
        });
    },

    getLoginErrorMsg() {
      if (this.error.status == 401) {
        return ""Invalid username or password"";
      } else {
        // return `Login failed: {this.error.statusText}`;
        return ""failed"";
      }
    }
  }
};
&lt;/script&gt;

&lt;style&gt;&lt;/style&gt;
</code></pre>

<p>Here is the test file:</p>

<pre><code>import { expect } from ""chai"";
import { mount, shallowMount } from ""@vue/test-utils"";
import Login from ""../../src/views/user/Login.vue"";

describe(""Login"", () =&gt; {

  it(""Has login text"", () =&gt; {
    // const wrapper = mount(Login);
    const wrapper = shallowMount(Login);
    // not getting here.
    expect(2).to.equal(2);
  });
});
</code></pre>

<p>Note: neither mount or shallowMount works. They both throw the same error.</p>

<p>Here is my webpack.config.js file:</p>

<pre><code>const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      // this will apply to both plain `.js` files
      // AND `&lt;script&gt;` blocks in `.vue` files
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      // this will apply to both plain `.css` files
      // AND `&lt;style&gt;` blocks in `.vue` files
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    // make sure to include the plugin for the magic
    new VueLoaderPlugin()
  ]
}
</code></pre>

<p>I've spent hours googling and I can't really find anything. So, I'm clearly doing something really stupid, because no one else seems to be having this issue. Please tell me why it is throwing this error and unable to shallowMount or mount this vue component.</p>
",https://stackoverflow.com/questions/60158928/cannot-shallowmount-a-vue-compoent-for-unit-testing,"['unit-testing', 'vuejs2', 'vue-component']",555,True,0,1
Spring MVC Mockito Test returning 406 error instead of 200,"<p>So I am working with a working UI, and using a DB2 database. I am trying to run unit testing on the controller/service/dao layers and I am using mockito and junit to test. Here are the pieces of each layer:</p>
<p><code>Measures.java</code></p>
<pre><code>@Controller
@RequestMapping(value = &quot;/measures&quot;})
public class Measures {

    @Resource
    private CheckUpService checkUpService;
    
    public void setCheckUpService(CheckUpService checkUp) {
        this.checkUpService = checkUpService;
    }    

    @RequestMapping(value = &quot;/eligibility/{userId}/{effDate}/{stageInd}&quot;, method = RequestMethod.POST, produces = &quot;application/json&quot;)
    public @ResponseBody List&lt;Model&gt; findEligibility(@PathVariable int userId, @PathVariable String effDate, @PathVariable String stageInd) throws Exception
    {
        List&lt;Model&gt; result = new ArrayList&lt;Model&gt;();

        if (stageInd.equals(&quot;stage&quot;))
        {
            result = checkUpService.findEligibilityStage(userId, effDate);
        }

        if (stageInd.equals(&quot;prod&quot;))
        {
            result = checkUpService.findEligibility(userId, effDate);
        }

        return result;
    }
...
}
</code></pre>
<p><code>CheckUpService.java</code></p>
<pre><code>public class CheckUpService {

    @Resource
    EligibilityDao eligDao;

    public List&lt;Model&gt; findEligibility(int userId, String effDate) throws Exception
        {
             return eligDao.findEligibility(userId, effDate, db_table);
        }
}
</code></pre>
<p><code>EligibilityDao.class</code></p>
<pre><code>public class EligibilityDao {

    public List&lt;Model&gt; findEligibility(int userId, String effDate, String table) throws Exception
        {
            // uses some long sql statement to get some information db2 database and 
            // jdbctemplate helps return that into a list.
        }
}
</code></pre>
<p>Here is the controller test that I am trying to do, I've spent about 10 hours on this and I really can't figure out why it's giving me a 406 error instead of 200.</p>
<p><code>ControllerTest.java</code></p>
<pre><code>@EnableWebMvc
@WebAppConfiguration
public class ControllerTest {
    
    @Autowired
    private Measures measures;
    
    @Autowired
    private WebApplicationContext webApplicationContext;
    
    private MockMvc mockMvc;
    
    private List&lt;Model&gt; findEligibility() {
        
        List&lt;Model&gt; list = new ArrayList&lt;&gt;();
        
        Model test_model = new Model();
        
        test_model.setUserId(99);
        test_model.setCreateID(&quot;testUser&quot;);
        test_model.setEffDate(&quot;2020-07-30&quot;);
        
        list.add(test_model);
        
        return list;
    }
    
    @Before
    public void setup() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
    
    @Test
    public void test_find() throws Exception {
        
        CheckUpService checkUpService = mock(CheckUpService.class);
        
        when(checkUpService.findEligibility(99, &quot;2020-07-30&quot;)).thenReturn(findEligibility());
        
        measures.setCheckUpService(checkUpService);
        
        String URI = &quot;/measures/eligibility/99/2020-07-30/prod&quot;;
        
        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
        
        MvcResult handle = mockMvc.perform(requestBuilder).andReturn();

//      MvcResult handle = mockMvc.perform(requestBuilder).andExpect(status().isOk()).andReturn();

        MvcResult result = mockMvc.perform(asyncDispatch(handle)).andExpect(status().isOk()).andReturn();
        
//      assertThat(result.getResponse().getContentAsString()).isEqualTo(findEligibility()); 

    }
    
    
    
}
</code></pre>
<p>The MvcResult result is what is throwing the &quot;StatusExpected &lt;200&gt; but was &lt;406&gt;&quot; error in junit and i'm going mad on why it is. Another issue is that, if you can see, I commented out the handle with the .andExpect(status().isOk()) and that one was also throwing the same issue. Is it something i'm setting up wrong with the test or something?</p>
",https://stackoverflow.com/questions/63202397/spring-mvc-mockito-test-returning-406-error-instead-of-200,"['java', 'spring', 'spring-boot', 'spring-mvc', 'junit']",545,False,0,1
Permission errors unit-testing Google Cloud Functions calling firestore db,"<p>I'm following the guide at <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a>, but I always get "" FirebaseError: Missing or insufficient permissions"" when I run my test. I have the correct <code>service-account.json</code> file and I'm setting up <code>firebase-functions-test</code> with it (that part goes without error).</p>

<p>I've tried it with the emulator running (setting the FIRESTORE_EMULATOR_HOST var), and without it (which I assume uses live data) but I always get this error, as soon as my code under test does a db request such as:</p>

<pre><code>  data = await db().collection('/machines').get()
</code></pre>

<p>So my function under test is getting called, but it just can't do anything.
I also tried calling <code>firebase.initializeApp()</code> the same way I do in my front-end app, but that doesn't help, although without it I get the error telling me to call Firebase App.initializeApp().</p>

<p><code>firebase use</code> is set to my current project.</p>

<p>I also tried running my test as <code>firebase emulators:exec jest</code>, no difference.</p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/60624919/permission-errors-unit-testing-google-cloud-functions-calling-firestore-db,"['firebase', 'unit-testing', 'google-cloud-functions', 'firebase-cli']",134,False,0,0
Jest mocking return value of a static method of connected component,"<p>I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a  and then shallow mounting it. However I am not able to mock return value of the static methods defined in my connected component.</p>

<p>Below is my sample code:</p>

<pre><code>const wrapper = shallow(
    &lt;Provider store={store}&gt;
        &lt;TestComponent {...props}  /&gt;
    &lt;/Provider&gt;
).dive();
</code></pre>

<p>Now when I try to mock the return value of static method defined in TestComponent, it doesn't have any effect, it fails:</p>

<pre><code>TestComponent.myStaticMethod = jest.fn().mockReturnValue(true);
</code></pre>

<p>Interesting part is, if I export the unconnected component as also <a href=""https://redux.js.org/recipes/writing-tests/#connected-components"" rel=""nofollow noreferrer"">suggested</a> in redux docs, the above mock syntax work well. Is it fine to export the unconnected component just for the purpose of testing? I tried mocking before the shallow and then after it, both ways didn't work.</p>
",https://stackoverflow.com/questions/60258396/jest-mocking-return-value-of-a-static-method-of-connected-component,"['reactjs', 'unit-testing', 'redux', 'jestjs', 'enzyme']",1223,False,0,1
How to unit test a public method that calls a private method,"<p>Here is a very basic example to illustrate my point</p>
<pre><code>class SomeClass {

    publicMethod1(param1, param2) {

        if (param1 === &quot;some value&quot;) {
            // do stuff
        } else {
            // do stuff
        }

        this.privateMethod(true);

    }

    publicMethod2(param1, param2, param3, param4) {

        if (param3) {
            // do stuff
        } else {
            // do stuff
        }

        this.privateMethod(false);

    }

    privateMethod(param) {

        // do stuff

        let obj = database.getObject(param); // call to database

        if (obj.property === &quot;random&quot;) {
            // do stuff
        } else {
            // do stuff
        }

    }
}
</code></pre>
<p>I've done a bit of research into this topic but didn't find any people asking the exact question I'm asking. I think I'm clear that I should only be unit testing my public methods and not private ones. But I'm just wondering <strong>how</strong> I should be testing my public methods that make calls to private methods that are within the same class.</p>
<p>Should I simply be testing to make sure that private method was called? Or should I be delving into the logic of the private method to make sure I test every possible route of execution? And if it's a &quot;yes&quot; to the latter, I was wondering if it is common to reuse unit tests when dealing with private methods that are called multiple times (like in the example above).</p>
",https://stackoverflow.com/questions/65300492/how-to-unit-test-a-public-method-that-calls-a-private-method,"['javascript', 'unit-testing']",102,True,0,1
Custom gradle plugin throws Unable to load class &#39;io.github.classgraph.ClassGraph&#39;,"<p>I'm using the <a href=""https://github.com/classgraph/classgraph"" rel=""nofollow noreferrer"">ClassGraph library</a> inside a custom gradle plugin: <a href=""https://github.com/RoRoche/plantuml-gradle-plugin/tree/feature/using_classgraph"" rel=""nofollow noreferrer"">https://github.com/RoRoche/plantuml-gradle-plugin/tree/feature/using_classgraph</a></p>

<p>It's OK during unit testing and while releasing into local Maven and used in another project.</p>

<p>But since it has been released to gradle plugin portal (<a href=""https://plugins.gradle.org/plugin/com.github.roroche.plantuml"" rel=""nofollow noreferrer"">https://plugins.gradle.org/plugin/com.github.roroche.plantuml</a>), when using inside another project (<a href=""https://github.com/RoRoche/eo-plantuml-builder"" rel=""nofollow noreferrer"">https://github.com/RoRoche/eo-plantuml-builder</a>), when running my <code>buildClassDiagram</code> task, it throws</p>

<pre class=""lang-sh prettyprint-override""><code>* What went wrong:
Execution failed for task ':buildClassDiagram'.
&gt; Lio/github/classgraph/ClassGraph;
</code></pre>

<p>Any idea of what's going wrong? Gradle plugin packaging?</p>

<p>Update with stacktrace option </p>

<pre class=""lang-sh prettyprint-override""><code>* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':buildClassDiagram'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:205)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$$Lambda$395/0000000000000000.accept(Unknown Source)
        at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:263)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:203)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:184)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:109)
        at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
        at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:372)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:359)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:352)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:338)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$$Lambda$315/0000000000000000.execute(Unknown Source)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
Caused by: java.lang.NoClassDefFoundError: io.github.classgraph.ClassGraph
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.readFields(ClassDiagramBuilder.java:346)
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.lambda$createJavaClass$20(ClassDiagramBuilder.java:313)
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder$$Lambda$305/0000000000000000.apply(Unknown Source)
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.createJavaClass(ClassDiagramBuilder.java:313)
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.lambda$readClasses$19(ClassDiagramBuilder.java:305)
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder$$Lambda$304/0000000000000000.accept(Unknown Source)
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.readClasses(ClassDiagramBuilder.java:305)
        at ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.build(ClassDiagramBuilder.java:153)
        at com.github.roroche.plantuml.diagrams.ClassDiagram.&lt;init&gt;(ClassDiagram.kt:28)
        at com.github.roroche.plantuml.diagrams.ClassDiagram.&lt;init&gt;(ClassDiagram.kt:37)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at com.github.roroche.plantuml.tasks.BuildClassDiagramTask.execute(BuildClassDiagramTask.groovy:60)
        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 org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:104)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:49)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:42)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:727)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:694)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$3.run(ExecuteActionsTaskExecuter.java:568)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:553)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:536)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:109)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:276)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:265)
        at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$1(ExecuteStep.java:33)
        at org.gradle.internal.execution.steps.ExecuteStep$$Lambda$360/0000000000000000.get(Unknown Source)
        at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:33)
        at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
        at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:63)
        at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:35)
        at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:49)
        at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:34)
        at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:43)
        at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
        at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
        at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:34)
        at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:44)
        at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:54)
        at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:38)
        at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
        at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:153)
        at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:67)
        at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:41)
        at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:44)
        at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:33)
        at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
        at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
        at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:92)
        at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:85)
        at org.gradle.internal.execution.steps.SkipUpToDateStep$$Lambda$354/0000000000000000.apply(Unknown Source)
        at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:55)
        at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:39)
        at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:76)
        at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
        at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
        at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
        at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:94)
        at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:49)
        at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:79)
        at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:53)
        at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:74)
        at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:78)
        at org.gradle.internal.execution.steps.SkipEmptyWorkStep$$Lambda$338/0000000000000000.get(Unknown Source)
        at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:78)
        at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:34)
        at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:39)
        at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:40)
        at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:28)
        at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:192)
        ... 31 more
Caused by: java.lang.ClassNotFoundException: io.github.classgraph.ClassGraph
        ... 113 more

</code></pre>

<p>Here are the steps to reproduce:</p>

<pre class=""lang-sh prettyprint-override""><code>$ git clone https://github.com/RoRoche/plantuml-gradle-plugin
$ git fetch
$ git checkout feature/using_classgraph 
</code></pre>

<p>Then in the <code>build.gradle</code> file, change the line 18 to set the version you want.</p>

<p>Then publish it to local Maven using <code>./gradlew publishToMavenLocal</code></p>

<p>In another Gradle-based project, define the Local Maven repository for plugin management in <code>settings.gradle</code> such as:</p>

<pre><code>pluginManagement {
    repositories {
        gradlePluginPortal()
        mavenLocal()
    }
}
</code></pre>

<p>Then, in the <code>build.gradle</code> file:</p>

<pre><code>plugins {
    id ""com.github.roroche.plantuml"" version ""{version}""
}

classDiagram {
    packageName = ""{your_package}""
    outputFile = project.file('diagrams/class_diagram.plantuml')
}
</code></pre>

<p>And launch task <code>./gradlew buildClassDiagram</code></p>

<p>Here are debug logs of the task execution:</p>

<pre class=""lang-sh prettyprint-override""><code>2020-05-07T13:18:29.039+0200 [DEBUG] [org.gradle.internal.operations.DefaultBuildOperationExecutor] Build operation 'Execute execute for :buildClassDiagram' started
2020-05-07T13:18:29.040+0200 [DEBUG] [org.gradle.api.Task] Package to scan: com.github.roroche.eoplantumlbuilder
2020-05-07T13:18:29.040+0200 [DEBUG] [org.gradle.api.Task] Output file: /Users/Romain/GitHub/eo-plantuml-builder/diagrams/class_diagram.plantuml
2020-05-07T13:18:29.040+0200 [DEBUG] [org.gradle.api.Task] Classes to ignore: [com.github.roroche.eoplantumlbuilder.classes.Classes$Simple, com.github.roroche.eoplantumlbuilder.diagrams.Diagram$Wrap, com.github.roroche.eoplantumlbuilder.diagrams.Diagram$Simple, com.github.roroche.eoplantumlbuilder.classes.Classes$Wrap]
2020-05-07T13:18:29.040+0200 [DEBUG] [org.gradle.api.Task] URLs to scan: [file:/Users/Romain/GitHub/eo-plantuml-builder/build/classes/java/main, file:/Users/Romain/GitHub/eo-plantuml-builder/build/classes/kotlin/main/]
2020-05-07T13:18:29.738+0200 [DEBUG] [org.gradle.api.Task] Classes to print in class diagram: [interface com.github.roroche.eoplantumlbuilder.classes.Classes, class com.github.roroche.eoplantumlbuilder.classes.ClsFiltered, class com.github.roroche.eoplantumlbuilder.classes.ClsInPackage, class com.github.roroche.eoplantumlbuilder.classes.ClsWithNames, class com.github.roroche.eoplantumlbuilder.classes.exceptions.InvalidPackageException, class com.github.roroche.eoplantumlbuilder.diagrams.ClassDiagram, interface com.github.roroche.eoplantumlbuilder.diagrams.Diagram]
</code></pre>
",https://stackoverflow.com/questions/61645090/custom-gradle-plugin-throws-unable-to-load-class-io-github-classgraph-classgrap,"['gradle', 'groovy', 'gradle-plugin', 'classgraph']",1618,False,0,1
Pytest RuntimeError: No application found. Either work inside a view function or push an application context,"<p>I am trying to implement unit testing to my Flask application. In this function I am trying to search an image in my database by a keyword. </p>

<p>Search image in database file: </p>

<pre><code>from models import ImageKeyword, Image
import random

keyword_limit_in_database = 100


def search_image_in_db(keyword):
    query = ImageKeyword.query.filter_by(keyword=keyword)  # query for keyword table
    row_count = int(query.count())  # row count for keywords
    if row_count &gt; keyword_limit_in_database:
        image_keyword = query.offset(int(row_count * random.random())).first()
        if image_keyword is not None:
            image = Image.query.filter_by(id=image_keyword.image_id).first()
            if image is not None:
                return image  # found Image in our database by keyword
</code></pre>

<p>Here is my current test function: </p>

<pre><code>from image_search import image_search_in_db


def test_search_image_in_db():
    keyword = ""sun""
    result = image_search_in_db.search_image_in_db(keyword)
    assert result is not None
</code></pre>

<p>The image with a keyword ""sun"" currently is in my database. 
The error code I am receiving when running pytest:</p>

<pre><code>self = &lt;sqlalchemy.util._collections.ScopedRegistry object at 0x7f2e42b75b10&gt;

    def __call__(self):
        key = self.scopefunc()
        try:
&gt;           return self.registry[key]
E           KeyError: &lt;greenlet.greenlet object at 0x7f2e440fa3c0&gt;

/usr/local/lib/python3.7/dist-packages/sqlalchemy/util/_collections.py:1030: KeyError

During handling of the above exception, another exception occurred:

    def test_search_image_in_db():
        keyword = ""sun""
&gt;       result = image_search_in_db.search_image_in_db(keyword)

TestCases/test_search_in_db.py:6: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
image_search/image_search_in_db.py:8: in search_image_in_db
    query = ImageKeyword.query.filter_by(keyword=keyword)  # query for keyword table
/usr/local/lib/python3.7/dist-packages/flask_sqlalchemy/__init__.py:519: in __get__
    return type.query_class(mapper, session=self.sa.session())
/usr/local/lib/python3.7/dist-packages/sqlalchemy/orm/scoping.py:78: in __call__
    return self.registry()
/usr/local/lib/python3.7/dist-packages/sqlalchemy/util/_collections.py:1032: in __call__
    return self.registry.setdefault(key, self.createfunc())
/usr/local/lib/python3.7/dist-packages/sqlalchemy/orm/session.py:3254: in __call__
    return self.class_(**local_kw)
/usr/local/lib/python3.7/dist-packages/flask_sqlalchemy/__init__.py:136: in __init__
    self.app = app = db.get_app()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = &lt;SQLAlchemy engine=None&gt;, reference_app = None

    def get_app(self, reference_app=None):
        """"""Helper method that implements the logic to look up an
        application.""""""

        if reference_app is not None:
            return reference_app

        if current_app:
            return current_app._get_current_object()

        if self.app is not None:
            return self.app

        raise RuntimeError(
&gt;           'No application found. Either work inside a view function or push'
            ' an application context. See'
            ' http://flask-sqlalchemy.pocoo.org/contexts/.'
        )
E       RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

/usr/local/lib/python3.7/dist-packages/flask_sqlalchemy/__init__.py:982: RuntimeError
=================================================================================================== short test summary info ===================================================================================================
FAILED TestCases/test_search_in_db.py::test_search_image_in_db - RuntimeError: No application found. Either work inside a view function or push an application context. 
</code></pre>

<p>I think the issue is that my application during the test is unable to connect to my database. I have 3 environments, local, development and production. I have set up that when running the application PyCharm would select the local environment. Should I connect to my database in my test file or maybe I could set the environment in my test file, I am not sure how to do that.I am new to testing. Any help will be appreciated.</p>

<p>app.py file content:</p>

<pre><code>from flask import Flask, render_template, session
from models import db
from flask_restful import Api
from flask_socketio import SocketIO, emit
from controllers.image_controller import ImageController
from controllers.question_controller import model
from flask_cors import CORS

app = Flask(__name__)
app.config.from_object(""config.Config"")
app.config['SECRET_KEY'] = '123456'
db.init_app(app)
socketio = SocketIO(app, cors_allowed_origins='*')
api = Api(app)
CORS(app)

api.add_resource(ImageController, '/images')


@app.route('/chatbot')
def index():
    return render_template('index.html', async_mode=socketio.async_mode)


@socketio.on('my_event', namespace='/chatbot')
def test_message(question):
    answer = model.get_answer(question['data'])
    session['receive_count'] = session.get('receive_count', 0) + 1
    emit('my_response', {'data': answer})


if __name__ == '__main__':
    socketio.run(app, host=""0.0.0.0"", debug=True, use_reloader=False)
</code></pre>

<p>The current error I am receiving:</p>

<pre><code>FAILED TestCases/test_search_in_db.py::test_search_image_in_db - NameError: name 'create_app' is not defined
</code></pre>
",https://stackoverflow.com/questions/61983525/pytest-runtimeerror-no-application-found-either-work-inside-a-view-function-or,"['mysql', 'python-3.x', 'flask', 'flask-sqlalchemy', 'pytest']",2508,True,4,1
CMake Error: Unable to find package GTest,"<p>I am developing a C/C++ app using CMake. I want to use GTest in my project for unit testing. For this I have decided to use GTest as a git submodule in my repository.</p>
<p>My directory hierarchy is as follows:</p>
<pre><code>/
--include
--lib
  --GoogleTest
--src
--Tests
</code></pre>
<p>The <code>GoogleTest</code> subdirectory in <code>lib</code> contains the source code of GTest from their official repository.</p>
<p>But I am unable to use it to test my source. The <code>CMakeLists.txt</code> file at the root of my repository is as follows:</p>
<pre><code>OPTION (BUILD_UNIT_TESTS &quot;Build unit tests&quot; ON)

if (BUILD_UNIT_TESTS)
    enable_testing ()
    find_package (GTest REQUIRED)
    add_subdirectory (Tests)
endif ()
</code></pre>
<p>But I receive the error:</p>
<blockquote>
<p>Error:Could NOT find GTest (missing: GTEST_LIBRARY GTEST_INCLUDE_DIR
GTEST_MAIN_LIBRARY)</p>
</blockquote>
<p>When I searched for this, there were many questions similar to mine, but none of them addressed my problem. And their manual is very limited and does not tell much about its usage properly.</p>
<p>CMake is successfully able to build  the target GTest but fails to recognise it when I try to use it as an external package.</p>
",https://stackoverflow.com/questions/63011027/cmake-error-unable-to-find-package-gtest,"['c++', 'cmake', 'googletest']",2415,True,3,1
Enzyme mount() rerender after state change in useEffect()?,"<p>I'm new to React and to React unit testing. I have a component which loads some divs based on state set with useState. Inside useEffect, if a rejected promise is returned from a function then an error div should be shown instead. I want to test this scenario, but because initial state is set as error = false, the original divs are still shown instead.</p>

<p>My question is, how can I do this so that the test registers updated divs? I'm using Enzyme's mount(), but I've also tried it with shallow(). I've also verified that it's actually going into .catch() with some console.logs.</p>

<p>component:</p>

<pre><code>export const Main = (props) =&gt; { 
  const [showLoadError, setShowLoadError] = useState(false);
  const [loadError, setLoadError] = useState('');

  React.useEffect(() =&gt; {
    const { categories, actions } = props;

    // retrieve categories from Db if they don't exist in state
    if (categories.length === 0) {
      actions.loadCategories().catch(err =&gt; {
        setShowLoadError(true);
        setLoadError(err.message);
      })
    } else {
      setShowLoadError(false);
      setLoadError('');
    }
  }, []);

  return (

    &lt;&gt;
      {/* conditional show for error container if loading failed */}
      {showLoadError &amp;&amp;
        &lt;div className=""load-error""&gt;
          Error loading categories. {loadError}
        &lt;/div&gt;
      }
      {/* conditional show for no Load error */}
      {!showLoadError &amp;&amp;
        &lt;div className=""grid-container grid-container--fit""&gt;
          &lt;div&gt;&lt;CategoryContainer /&gt;&lt;/div&gt;
          &lt;div&gt;&lt;ItemContainer /&gt;&lt;/div&gt;
          &lt;div&gt;&lt;FileAssociationsContainer /&gt;&lt;/div&gt;
        &lt;/div&gt;
      }
    &lt;/&gt;
  );
}
</code></pre>

<p>test:</p>

<pre><code>import React from 'react';
import ConnectedApp, { Main } from './Main';
import { shallow, mount } from 'enzyme';

jest.mock(""../category/CategoryContainer"");
jest.mock(""../item/ItemContainer"");
jest.mock(""../fileAssociations/FileAssociationsContainer"");

describe(""Main component"", () =&gt; {

  beforeEach(() =&gt; {
    fetch.resetMocks()
  });

  test('should render error div after loadCategories fail',  () =&gt; {
    const categories = [];
    const errMessage = {message: 'test error'}
    const actions = {
      loadCategories: jest.fn(() =&gt; {
        return Promise.reject(errMessage);
      })
    };

    const wrapper = mount(&lt;Main categories={categories} actions={actions} /&gt;);

    wrapper.setProps(); // rerenders

    // expect there to be a load-error div
    expect(wrapper.find('div').hasClass('load-error')).toBe(true)

    // expect loadCategories to be called because component was passed in empty categories
    expect(actions.loadCategories).toBeCalled();

  });



});
</code></pre>

<p>I've tried <code>wrapper.setProps()</code>, <code>wrapper.update()</code> before my expects with no luck.</p>

<p>Additionally, this unit test gives a jest warning that <code>An update to Main inside a test was not wrapped in act(...)</code>. This only happens if actions.loadCategories() returns a rejected promise. It does not do this when it returns a resolved promise. I've tried moving code into act() with no luck in removing the error, like such:</p>

<pre><code>act(() =&gt; {
      actions = {
        loadCategories: jest.fn(() =&gt; {
          return Promise.reject(errMessage);
        })
      };
      wrapper = mount(&lt;Main categories={categories} actions={actions} /&gt;);
      wrapper.setProps(); // rerenders
    });
</code></pre>
",https://stackoverflow.com/questions/61275432/enzyme-mount-rerender-after-state-change-in-useeffect,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",5453,False,7,0
Internal working of field injection in spring and why is it not recommended to use,"<p>As the title suggests , I want to know how does field injection internally works in spring , I read many articles on this and got to know few things like below but didn't understood the exact reason behind it :</p>
<p>-&gt; It should not be used because when you do unit testing then you are dependent upon the spring
container to instantiate the class in case of field injection.</p>
<p>-&gt; You cannot use &quot;final&quot; keyword in case of field injection , means you cannot make the field immutable.</p>
<p>-&gt; It internally uses reflection</p>
<p>I want to know how exactly does @Autowired works internally , how does it uses reflection , I am trying to understand the exact reason behind all the above mentioned points, what happens behind the scenes when we write the below code :</p>
<pre><code>@Component
public class B {

    @Autowired
    private A a1;

}
</code></pre>
<p>I have read similar questions on stack overflow about this topic , but I couldn't find the exact explanation that I am looking.</p>
",https://stackoverflow.com/questions/62774713/internal-working-of-field-injection-in-spring-and-why-is-it-not-recommended-to-u,"['java', 'spring', 'spring-annotations']",1990,True,2,1
How to rewrite the table qualifier at runtime with JOOQ,"<p>When generating code using JOOQ for a SQL Server database the generation creates three-part qualifiers like: <code>[catalog].[schema].[table]</code>. This is exactly what I want when working with the SQL Server databases but is an issue when using the generated code with another database like an H2 in memory database for unit testing.</p>

<p>The H2 dialect does not support these three-part qualifiers, H2 expects something like [catalog].[table]. This causes syntax errors when executing commands like the following against H2:</p>

<pre><code>context.createTable(TBLBUSINESSENTITY).columns(TBLBUSINESSENTITY.fields()).execute();
</code></pre>

<p>To solve this I need to change the qualifier at runtime which I thought could be done using a render mapping and mapped schema. Unfortunately, this seems to only have the ability to modify the schema portion of the qualifier like this:</p>

<pre><code>Settings settings = new Settings().withRenderMapping(new RenderMapping().withSchemata(
      new MappedSchema().withInput(""dbo"").withOutput(""mySchema"")));
</code></pre>

<p>Given the qualifier <code>[MyDatabase].[dbo].[MyTable]</code>, this maps to <code>[MyDatabase].[mySchema].[MyTable]</code> but I cant figure out how to remove that section entirely.</p>

<p>Is there some way to rewrite the mapping to <code>[MyDatabase].[MyTable]</code>?</p>
",https://stackoverflow.com/questions/60439324/how-to-rewrite-the-table-qualifier-at-runtime-with-jooq,['jooq'],134,True,2,1
Unit Testing nested methods,"<p>While I understand that when unit testing a method it is very important to mock all it's dependencies, what I still have confusion about is what happens when the method is nested? Do I mock only the dependencies of the parent method or do I mock the dependencies of the child method(s) as well or do I set expectations on the calls to the dependent object and set the exact return values so that I can perform the test that I want?</p>

<p>For instance, in the below example, if we want to unit test the method B, do we only mock <code>IHttpClientFactory</code> &amp; <code>ILogger</code> or do we  also set the method's return value to what we are actually expecting because otherwise when the test method executes it goes ahead and tries to execute methodC where it fails because the value of <code>client</code> after the line <code>var client = _clientFactory.CreateClient()</code> executes is null?</p>

<pre><code>using System.Net.Http;
...

public class classA
{
   private readonly IHttpClientFactory _clientFactory;
   private sting url = ""..."";
   private ILogger _log { get; set; }
   ...

   public classA(ILogger log, IHttpClientFactory clientFactory, ...)
   {
     _log = log;
     _clientFactory = clientFactory;
     ...
   }

   public string methodB(string inputB)
   {
      var varB = methodC(inputB);
      ...
      return ..;
   }

   public string methodC(string inputC)
   {
      ...
      var client = _clientFactory.CreateClient();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/json""));
      HttpResponseMessage httpResponseMessage = await client.PostAsync(url, new StringContent(inputC, Encoding.UTF8, ""application/json""));
      responJsonText = await httpResponseMessage.Content.ReadAsStringAsync();
      ...
      return ..;
   }

}
</code></pre>
",https://stackoverflow.com/questions/60513623/unit-testing-nested-methods,"['c#', 'unit-testing', 'mocking', 'moq']",1023,True,2,1
Testing app containing AppLoading component,"<p>I am new to the world of unit testing and I have just began to write tests for my React Native (Expo) app. After doing research I have finally landed in using <a href=""https://github.com/callstack/react-native-testing-library"" rel=""nofollow noreferrer"">Jest and React Native Testing Library</a>.</p>
<p>Consider the following that uses the <a href=""https://docs.expo.io/versions/latest/sdk/app-loading/"" rel=""nofollow noreferrer"">AppLoading component</a>.</p>
<pre class=""lang-js prettyprint-override""><code>    const App: React.FC = () =&gt; {
        const [resourcesHasLoaded, setResourcesHasLoaded] = useState&lt;boolean&gt;(false);
    
        const cacheResources = useCallback(async (): Promise&lt;any&gt; =&gt; {
            const images = [require('./assets/icon.png')];
    
            const cacheImages = images.map((image) =&gt; {
                return Asset.fromModule(image).downloadAsync();
            });
    
            return Promise.all([cacheImages]);
        }, []);
    
        if (resourcesHasLoaded) {
            return &lt;Text&gt;Hello world&lt;/Text&gt;;
        }
    
        return (
            &lt;AppLoading
                startAsync={cacheResources}
                onError={console.warn}
                onFinish={() =&gt; setResourcesHasLoaded(true)}
            /&gt;
        );
    };

When running my test, that looks like this:

    describe('App.tsx', () =&gt; {
        it('should be able to render', async () =&gt; {
            render(&lt;App /&gt;);
        });
    });
</code></pre>
<p>I end up with the following error (although, test passes):</p>
<pre><code>    Warning: An update to App inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() =&gt; {
      /* fire events that update state */
    });
    /* assert on the output */

So, I wrapped my `render` in with `act` the following way:

    act(() =&gt; {
        render(&lt;App /&gt;);
    });
</code></pre>
<p>... which resulted in the same error.</p>
<p>If I however wrap the <code>onFinish</code>-callback in my component the following way the test passes without warnings.</p>
<pre class=""lang-js prettyprint-override""><code>    onFinish={() =&gt; act(() =&gt; setResourcesHasLoaded(true))}
</code></pre>
<p>But do I really want to pollute my React Component with test-specific functions? I saw no example of this, so I can only assume that this is bad practice.</p>
<p>Any suggestions here?</p>
<p><strong>Update</strong>
I got the suggestion to use <code>waitFor</code> after my <code>render</code> by @Estus Flask in my comments. That did the trick... the test now passes.</p>
<p><a href=""https://callstack.github.io/react-native-testing-library/docs/api/#waitfor"" rel=""nofollow noreferrer"">https://callstack.github.io/react-native-testing-library/docs/api/#waitfor</a></p>
<pre class=""lang-js prettyprint-override""><code>    describe('App.tsx', () =&gt; {
        it('should be able to render', async () =&gt; {
            const { findByText } = render(&lt;MyApp /&gt;);
            await waitFor(() =&gt; findByText('Hello world'));
        });
    });
</code></pre>
",https://stackoverflow.com/questions/62733687/testing-app-containing-apploading-component,"['react-native', 'jestjs', 'expo', 'react-native-testing-library']",503,False,2,0
Instantiating Qt application and widget within Googletest results in __acrt_first_block == header assertion fail,"<p>I am creating a simple Qt window application with CMake and decided I to use googletest for unit testing. Unfortunately, when creating my main window widget within a single test, I sometimes receive an assertion fail message: <code>__acrt_first_block == header</code>. I have already set all CMakeLists to use /MTd runtime mode (as google test library does, <code>set(CMAKE_CXX_FLAGS_DEBUG &quot;/MTd&quot;</code>).</p>
<p>Assertion failed message window leads me to the comment in gtest source stating: <code>// We create the exception message on the heap because VC++ prohibits creation of objects with destructors on stack in functions using __try (see error C2712).</code></p>
<p>Obviously, every Qt object defines a custom destructor so the problem lies here. But what's the way around to make those tests work? Can I somehow instantiate my mainwindow globally once in tests.cpp file rather than individually in every test?</p>
<pre><code>class CalcTests : public testing::Test
{
protected:
    Calc* calc = nullptr;
    
    void SetUp() override
    {
        calc = new Calc{};
    }

    void TearDown() override
    {
        delete calc;
    }
};

// A sample test...
TEST_F(CalcTests, sin_pi_6)
{
    //auto calc = std::make_unique&lt;Calc&gt;(nullptr);
    calc-&gt;menuViewScientificTriggered(); // just in case

    const double pi_rounded = disp_rounding(std::numbers::pi).toDouble();
    calc-&gt;getCurrDisplay()-&gt;setText(disp_rounding(pi_rounded / 6));

    calc-&gt;sinClicked();
    const QString actual{ calc-&gt;getCurrDisplay()-&gt;text() };
    const QString expected{ &quot;0.5&quot; };

    ASSERT_EQ(actual, expected) &lt;&lt; &quot;\n\n\n&quot;
                    &lt;&lt; &quot;Expected: &quot; &lt;&lt; expected.toStdString() &lt;&lt; &quot;\nActual: &quot; &lt;&lt; actual.toStdString();
}
</code></pre>
<p>I've also read that templates may cause this assertion fail. But in my case they are only two of them and there are fairly simple. They are not explicitly allocating memory on heap, but I attach sample source for reference:</p>
<pre><code>template&lt;typename Float&gt;
bool nearly_equal(const Float a, const Float b, const Float eps_factor)
    requires std::is_floating_point_v&lt;Float&gt;
{
    const auto abs_a = std::abs(a);
    const auto abs_b = std::abs(b);
    
    return std::abs(abs_a - abs_b)
        &lt;= std::numeric_limits&lt;Float&gt;::epsilon() * eps_factor;
}
</code></pre>
",https://stackoverflow.com/questions/63204532/instantiating-qt-application-and-widget-within-googletest-results-in-acrt-firs,"['c++', 'visual-studio', 'qt', 'googletest']",173,False,1,0
How to mock a static getter&#39;s return value in Dart or Flutter?,"<p>I would like to figure out how to modify the return value of a static getter for my unit tests in Flutter and Dart.</p>

<p>I'm unit testing a simple function:</p>

<pre><code>  Future&lt;bool&gt; exampleFunc() async {
    if (Platform.isIOS) {
      // Do some iOS-specific things
      return false;
    } else if (Platform.isAndroid) {
      // Do some Android-specific things
      return true; // just as an example
    }
    throw 'Unexpected platform';
  }
</code></pre>

<p>And I would like to modify the return values of the static getters of a class: I would like to tweak <code>Platform.isIOS</code> and <code>Platform.isAndroid</code> return value for the different test cases.</p>

<p>Please note that I know of workarounds for this issue, for example, I could split the function into two functions (one for each platform), I could inject my own <code>enum</code> (or in this case, even a <code>bool</code> might work) that represents the supported platforms. In this example, I am actually going to do that, but I would like to know how to ""modify"" the return values of the <code>Platform</code> class's getters, because sometimes, you don't want to modify the signature of a function, as others might depend on it and yet, you still want to unit test the function.</p>
",https://stackoverflow.com/questions/59592097/how-to-mock-a-static-getters-return-value-in-dart-or-flutter,"['unit-testing', 'flutter', 'dart', 'mockito', 'platform']",3811,True,6,2
Corrections to CMakeList.txt file for Google testing?,"<p>I have been looking at examples of CMake to help me build my project with its test folder. The main issue is that I have to include all the <em>test/</em>.cpp* files in my test folder into <em>tests/main.cpp</em> for the tests to run. I think I should include my tests with the <code>add_test</code> call in my <em>test/CMakeLists.txt</em>. Below is my current CMakeLists file:</p>
<blockquote>
<p>enable_testing()</p>
<p>find_package(GTest REQUIRED)</p>
<p>add_executable(test main.cpp)</p>
<p>target_include_directories(test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../include)</p>
<p>target_link_libraries(test MainProjectLib ${GTEST_LIBRARIES})</p>
</blockquote>
<p>And my <em>main.cpp</em> is the following.</p>
<pre><code>#include &quot;file_in_test1.cpp&quot;
#include &quot;file_in_test2.cpp&quot;
#include &lt;gtest/gtest.h&gt;

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&amp;argc, argv);
  return RUN_ALL_TESTS();
}
</code></pre>
<p>I read some examples that use the standard CTest library for unit testing, but I am using Google Test. <strong>I would like to be able to run <code>cmake</code>, <code>make</code>, and then <code>./test</code> to run all test methods found in <em>file_in_test1.cpp</em> and <em>file_in_test2.cpp</em> without having to directly import those files into <em>test/main.cpp</em>.</strong> What additions to <em>CMakeLists.txt</em> do I have to make?</p>
",https://stackoverflow.com/questions/60251076/corrections-to-cmakelist-txt-file-for-google-testing,"['c++', 'cmake', 'include', 'googletest']",275,False,1,1
How to do integration testing on an app depending on injected service with a Mock for the service?,"<p>I don't think it matters what the application is - Asp.NET, Blazor, WPF ... whatever -- if dependency injection is implemented, say:</p>
<pre><code>class Foo {
    public void ConfigureServices(IServiceCollection services) {
        services.AddSingleton&lt;IDispatcher, DispatchProvider&gt;();
        services.AddSingleton&lt;IAuthenticator, AuthenticationProvider&gt;();
    }
}
</code></pre>
<p>... then:</p>
<pre><code>class Bar {
    public Bar (IDispatcher dispatcher) {
        // do something with dispatcher...
    }
}
</code></pre>
<p>... the dependency creates a <em>not-so-straight-forward-approach</em> to unit testing.</p>
<p>Obviously, if I'm going to perform integration testing on <code>Bar</code> (with a dependency on <code>IDispatcher</code>), I don't necessarily want to fire up the relevant resources.</p>
<p>If <code>Bar</code> is a standalone object, I can create a <code>Mock&lt;IDispatcher&gt;</code> and manually inject into <code>Bar</code>; however, in my case, I am developing a Blazor component. The component has a dependency on <code>IDispatch</code> and another component on <code>IAuthenticator</code>.</p>
<p>The only thing I can come up with to alternatively inject a <em>mock</em> is to do the following:</p>
<pre><code>if (!isTest)) {
    services.AddSingleton&lt;IDispatcher, DispatchProvider&gt;();
    services.AddSingleton&lt;IAuthenticator, AuthenticationProvider&gt;();
} else {
    services.AddSingleton&lt;IDispatcher, MockDispatchProvider&gt;();
    services.AddSingleton&lt;IAuthenticator, MockAuthenticationProvider&gt;();
}

</code></pre>
<p>Here, I have a separate class library with just the <em>mocks</em> in it. My web app has to reference that .DLL which really stinks.</p>
<p>Is there a more practical solution? I really don't like having to do this.</p>
",https://stackoverflow.com/questions/63585343/how-to-do-integration-testing-on-an-app-depending-on-injected-service-with-a-moc,"['c#', 'unit-testing', 'dependency-injection', 'blazor-server-side']",231,False,1,0
"Not being able to simulate change on input and call onChange function using both shallow and mount. Enzyme, jestjs, react","<p>This is not a duplicate question because non of them worked for me and they were doing something different as well.</p>
<p>I have a component of email and password with form validation and now I want to do unit testing, and i want to simulate change on input but i am not able to do it. I have tried both shallow and mount i didn't try render but it wouldn't work either i read it in some documentations. I read somewhere that functions are needed to be binded or something but i am new to testing so i don't know much. This question might be super easy but i have been working on it for hours and i need to get it done. So please guide me and also suggest me if what i am doing is optimal or not.</p>
<p><em>sign-in.test.jsx</em></p>
<pre><code>import React from &quot;react&quot;;
import { shallow } from &quot;enzyme&quot;;
import { BrowserRouter } from &quot;react-router-dom&quot;;
import { findByTestAttr } from &quot;../../Utils/testUtils.js&quot;;

import SignIn from &quot;./sign-in.component&quot;;

const INITIAL_STATE = {
  email: &quot;&quot;,
  password: &quot;&quot;,
  rememberme: false,
  emailErr: &quot;&quot;,
  passwordErr: &quot;&quot;,
  buttonErr: &quot;&quot;,
  progressBar: 0,
  disable: true,
};

const setUp = (props = {}) =&gt; {
  const component = shallow(&lt;SignIn /&gt;); // Have also done like this: mount(&lt;BrowserRouter&gt;&lt;SignIn /&gt;&lt;BrowserRouter /&gt;)
  return component;
};

//Issue is with the last test case but feel free to suggest me about other tests as well

describe(&quot;Sign in component should render &quot;, () =&gt; {
  let component;
  beforeEach(() =&gt; {
    component = setUp();
  });
  test(&quot;Email input field&quot;, () =&gt; {
    const wrapper = findByTestAttr(component, &quot;email&quot;);
    expect(wrapper.length).toBe(1);
  });
  test(&quot;It should render password input field&quot;, () =&gt; {
    const wrapper = findByTestAttr(component, &quot;password&quot;);
    expect(wrapper.length).toBe(1);
  });
  test(&quot;It should render a remember me checkbox&quot;, () =&gt; {
    const wrapper = findByTestAttr(component, &quot;remember-me&quot;);
    expect(wrapper.length).toBe(1);
  });
  test(&quot;It should render a forget password link&quot;, () =&gt; {
    const wrapper = findByTestAttr(component, &quot;forget-password&quot;);
    expect(wrapper.length).toBe(1);
  });
  test(&quot;It should render a sign in button&quot;, () =&gt; {
    const wrapper = findByTestAttr(component, &quot;sign-in&quot;);
    expect(wrapper.length).toBe(1);
  });
  test(&quot;It should render a google sign in button&quot;, () =&gt; {
    const wrapper = findByTestAttr(component, &quot;google-sign-in&quot;);
    expect(wrapper.length).toBe(1);
  });
  test(&quot;It should render a facebook sign in button&quot;, () =&gt; {
    const wrapper = findByTestAttr(component, &quot;facebook-sign-in&quot;);
    expect(wrapper.length).toBe(1);
  });
});

describe(&quot;Form validation with different values&quot;, () =&gt; {
  let component;
  beforeEach(() =&gt; {
    component = setUp();
  });
  test(&quot;Form values&quot;, () =&gt; {
    const input = component.find(&quot;.email&quot;).at(0);

    input.simulate(&quot;change&quot;, { target: { value: &quot;check&quot; } });
    console.log(component.state.email); //undefined
  });
});

</code></pre>
<p><em>sign-in.component.jsx</em></p>
<pre><code>import React from &quot;react&quot;;
import { Link } from &quot;react-router-dom&quot;;
import CustomButton from &quot;../../components/custom-button/custom-button.component&quot;;
import CompanyLogo from &quot;../../components/company-logo-header/company-logo-header.component&quot;;
import InputField from &quot;../../components/input-field/input-field.component&quot;;
import InputError from &quot;../../components/input-field-error/input-field-error.component&quot;;
import { mailFormat, passwordFormat } from &quot;../../Utils/regularExpressions&quot;;
import &quot;./sign-in.styles.scss&quot;;

const INITIAL_STATE = {
  email: &quot;&quot;,
  password: &quot;&quot;,
  rememberme: false,
  emailErr: &quot;&quot;,
  passwordErr: &quot;&quot;,
  buttonErr: &quot;&quot;,
  progressBar: 0,
  disable: true,
};

class SignIn extends React.Component {
  constructor() {
    super();
    this.state = INITIAL_STATE;
  }
  handleChange = (event) =&gt; {
    this.setState({
      [event.target.name]: event.target.value,
    });
    const isValid = this.validate();
    if (isValid) {
      this.setState({ disable: false });
    } else {
      this.setState({ disable: true });
    }
  };
  validate = () =&gt; {
    let emailErr = &quot;&quot;;
    let passwordErr = &quot;&quot;;

    if (!this.state.email.match(mailFormat)) {
      emailErr = &quot;Please enter a valid email format&quot;;
    }
    if (!this.state.password.match(passwordFormat)) {
      passwordErr = &quot;Password should be eight digit with letters and numbers&quot;;
    }
    if (emailErr || passwordErr) {
      this.setState({
        emailErr,
        passwordErr,
      });
      return false;
    }
    this.setState({
      emailErr,
      passwordErr,
    });
    return true;
  };
  handleSubmit = async (event) =&gt; {
    event.preventDefault();
    if (this.state.disable) {
      await this.setState({
        buttonErr: &quot;Please enter the email and password&quot;,
      });
      return;
    }
    const isValid = this.validate();
    if (isValid) {
      console.log(isValid);
      this.setState(INITIAL_STATE);
    }
  };
  render() {
    const { disable } = this.state;
    return (
      &lt;div className=&quot;sign-in&quot;&gt;
        &lt;CompanyLogo /&gt;
        &lt;form noValidate className=&quot;sign-in-form&quot; onSubmit={this.handleSubmit}&gt;
          &lt;InputField
            name=&quot;email&quot;
            type=&quot;email&quot;
            placeholder=&quot;Email Address&quot;
            data-test=&quot;email&quot;
            className=&quot;email&quot;
            onChange={this.handleChange}
            value={this.state.email}
          /&gt;
          &lt;InputError&gt;{this.state.emailErr}&lt;/InputError&gt;
          &lt;InputField
            name=&quot;password&quot;
            type=&quot;password&quot;
            placeholder=&quot;Password&quot;
            data-test=&quot;password&quot;
            onChange={this.handleChange}
            value={this.state.password}
          /&gt;
          &lt;InputError&gt;{this.state.passwordErr}&lt;/InputError&gt;
          &lt;div className=&quot;remember-forget&quot;&gt;
            &lt;span className=&quot;remember-me&quot;&gt;
              &lt;input
                type=&quot;checkbox&quot;
                name=&quot;rememberme&quot;
                value=&quot;Remember Me&quot;
                data-test=&quot;remember-me&quot;
              /&gt;
              &lt;label htmlFor=&quot;rememberme&quot; className=&quot;rememberme&quot;&gt;
                {&quot; &quot;}
                Remember me
              &lt;/label&gt;
            &lt;/span&gt;
            &lt;Link
              to=&quot;password-reset&quot;
              className=&quot;forgot-password&quot;
              data-test=&quot;forget-password&quot;
            &gt;
              Forgot password?
            &lt;/Link&gt;
          &lt;/div&gt;
          &lt;div className=&quot;center-buttons&quot;&gt;
            &lt;CustomButton
              data-test=&quot;sign-in&quot;
              type=&quot;submit&quot;
              SignIn
              disabled={disable}
            &gt;
              Sign In
            &lt;/CustomButton&gt;
            &lt;InputError&gt;{this.state.buttonErr}&lt;/InputError&gt;
          &lt;/div&gt;
          &lt;div className=&quot;separator&quot;&gt;Or&lt;/div&gt;
          &lt;div className=&quot;center-buttons&quot;&gt;
            &lt;CustomButton data-test=&quot;facebook-sign-in&quot; type=&quot;button&quot; Options&gt;
              Sign in with facebook
            &lt;/CustomButton&gt;
            &lt;CustomButton data-test=&quot;google-sign-in&quot; type=&quot;button&quot; Options&gt;
              Sign in with google
            &lt;/CustomButton&gt;
          &lt;/div&gt;
        &lt;/form&gt;
      &lt;/div&gt;
    );
  }
}

export default SignIn;

</code></pre>
",https://stackoverflow.com/questions/64859059/not-being-able-to-simulate-change-on-input-and-call-onchange-function-using-both,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'jsdom']",127,False,1,0
Is there a way to unit test an innaccessible callback function that is called from a child React component using jest,"<p>I am unit testing a React 16 functional component that defines a callback and passes it as a property down to the next component to be invoked when a click event fires.  </p>

<pre><code>import React from 'react'

function OuterComponent() {

  const handleClick = useCallback(() =&gt; {
    openDialog() // &lt;--- This code is inaccessible from my ""OuterComponent.test.js"" unit test 
  }

  return &lt;MyDialog clickHandler={handleClick} /&gt;
}
export default OuterComponent
</code></pre>

<p>I am seeking 100% test coverage and would like to mock all other components/functions using jest that are not part of the ""OuterComponent"" component.  </p>

<p>The problem I am having is that I can't seem to mock the <strong>MyDialog</strong> component in order to have it trigger the <strong>handleClick</strong> function. </p>

<p>I also tried to mock the component using this snippet but it still seems to try to load all the imports from <strong>MyDialog</strong></p>

<pre><code>jest.doMock('components/MyDialog', () =&gt; {
    return () =&gt; () =&gt; &lt;div /&gt;
})
//... other mocks along with **openDialog**

//...and in my describe/it...
MyDialog.mockImplementation(() =&gt; {})

OuterComponent().handleClick()
expect(openDialog).toHaveBeenCalled()
</code></pre>

<p>The hope here was that I could render an empty div for <strong>MyDialog</strong> and just simply call the <strong>handleClick</strong> function to test it.  Does anyone know what I could be doing wrong or have any other ideas of how to test it?</p>
",https://stackoverflow.com/questions/60712671/is-there-a-way-to-unit-test-an-innaccessible-callback-function-that-is-called-fr,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",3332,True,1,1
Reset class and class variables for each test in Python via pytest,"<p>I created a class to make my life easier while doing some integration tests involving workers and their contracts. The code looks like this:</p>
<pre><code>class ContractID(str):
    contract_counter = 0
    contract_list = list()

    def __new__(cls):
        cls.contract_counter += 1
        new_entry = super().__new__(cls, f'Some_internal_name-{cls.contract_counter:10d}')
        cls.contract_list.append(new_entry)
        return new_entry

    @classmethod
    def get_contract_no(cls, worker_number):
        return cls.contract_list[worker_number-1]  # -1 so WORKER1 has contract #1 and not #0 etc.
</code></pre>
<p>When I'm unit-testing the class, I'm using the following code:</p>
<pre><code>from test_helpers import ContractID

@pytest.fixture
def get_contract_numbers():
    test_string_1 = ContractID()
    test_string_2 = ContractID()
    test_string_3 = ContractID()
    return test_string_1, test_string_2, test_string_3


def test_contract_id(get_contract_numbers):
    assert get_contract_ids[0] == 'Some_internal_name-0000000001'
    assert get_contract_ids[1] == 'Some_internal_name-0000000002'
    assert get_contract_ids[2] == 'Some_internal_name-0000000003'


def test_contract_id_get_contract_no(get_contract_numbers):
    assert ContractID.get_contract_no(1) == 'Some_internal_name-0000000001'
    assert ContractID.get_contract_no(2) == 'Some_internal_name-0000000002'
    assert ContractID.get_contract_no(3) == 'Some_internal_name-0000000003'
    with pytest.raises(IndexError) as py_e:
        ContractID.get_contract_no(4)
    assert py_e.type == IndexError
</code></pre>
<p>However, when I try to run these tests, the second one (<code>test_contract_id_get_contract_no</code>) fails, because it does not raise the error as there are more than three values. Furthermore, when I try to run all my tests in my folder <code>test/</code>, it fails even the first test (<code>test_contract_id</code>), which is probably because I'm trying to use this function in other tests that run before this test.</p>
<p>After reading <a href=""https://www.springer.com/gp/book/9783030259426"" rel=""nofollow noreferrer"" title=""Advanced Guide to Python 3 Programming by John Hunt"">this book</a>, my understanding of fixtures was that it provides objects as if they were never called before, which is obviously not the case here. Is there a way how to tell the tests to use the class as if it hasn't been used before anywhere else?</p>
",https://stackoverflow.com/questions/63813830/reset-class-and-class-variables-for-each-test-in-python-via-pytest,"['python', 'python-3.x', 'unit-testing', 'pytest']",2125,True,1,1
add gitlab-ci job when including an gitlab-ci template,"<p>here is my problem:
I have a GitLab-ci.yml template in a separate repository with all basic stages/steps in it. In another repo with the actual code, I include that template and overwrite a variable for unit testing for example.</p>
<p>Here is how the base template looks like:</p>
<pre><code>---
image: docker:git

variables:
  TEST_CMD: unit-test $UNIT_TEST_CMD_OPTIONS

stages:
  - pre-build
  - build
  - test

actual_build:
  stage: build
  &lt;&lt;: *only-default
  script:
    - echo &quot;build it&quot;
    - ...

....
</code></pre>
<p>Now I include that template into my actual repo gitlab-ci.yml file to execute the whole pipeline:</p>
<pre><code>---
include:
  - project: blahfubar/gitlab-ci-template
    ref: master
    file: basic.gitlab-ci.yml

variables:
  UNIT_TEST_CMD_OPTIONS: --testsuite unit
</code></pre>
<p>Now the problem:
I want to add an extra job just in this repo to i.e. execute a security check there, but this does not work and with the &quot;extends:&quot;-keyword only jobs can be extended.</p>
<pre><code>---
include:
  - project: blahfubar/gitlab-ci-template
    ref: master
    file: basic.gitlab-ci.yml

variables:
  UNIT_TEST_CMD_OPTIONS: --testsuite unit

security-step:
  stage: test
  script:
    - ./security-check

</code></pre>
<p>If I do it like that, only the &quot;security-step&quot; will be executed, but not all the other steps from the included template.</p>
<p>May anyone has a solution for that because I didn't find anything in the gitlab-ci docs.</p>
<p>Thanks in advance :)</p>
",https://stackoverflow.com/questions/64785672/add-gitlab-ci-job-when-including-an-gitlab-ci-template,"['gitlab', 'gitlab-ci', 'pipeline']",2578,True,1,1
Jest - Testing Certificate Validation,"<p>Seeking some advice on the best way to handle unit testing with Jest of some Certificate handling functions.</p>
<p>I have a validation function that validates a passed in certificate (via and API Call) against a root CA and another that uses the above certificate to encrypt some data before passing it back to the caller.</p>
<p>Thinking about how I could test this reliably I came up with the idea of using OpenSSL to create my own CA and the required test certificates. I could save them in the projects tests directory as files and having a test case to check that were valid before further use of them as mocks for the functions I'm testing.</p>
<p>My thinking here is that the test certificates could be saved into source control with no issues and would be robust test cases.</p>
<p>Does that sound like a reasonable approach or is it overkill?</p>
",https://stackoverflow.com/questions/62590506/jest-testing-certificate-validation,"['node.js', 'jestjs']",870,True,0,1
Is EasyMock&#39;s .times(x) method an issue for unit testing robustness?,"<p>I'm currently working on some unit tests for my application using JUnit and EasyMock for mocking complex objects, and I'm facing a <strong>dilemma</strong>. 
For instance, I'm testing each function with the following test template:</p>

<pre><code>public static int foo(Object a){
// my function that needs to be tested

  int quantity = 0;
  if(a != null &amp;&amp; a.getInt() != null ){
    quantity = a.getInt();
  }
  return quantity;

}

public void testFoo(){
// my unit test for the function foo
  int expectedValue = 0;
  int output = 0;

//Setting up my mocks
  Object a_mock = EasyMock.create(Object.class)
  EasyMock.expect(a_mock.getInt()).andReturn(null).times(1);
  EasyMock.expect(a_mock.getInt()).andReturn(1).times(2);

//Executing
  // Case 1: a is null
  expectedValue = 0;
  output = foo(null);
  assertEquals(expectedValue, output);

  // Case 2: a.getIn() is null
  expectedValue = 0;
  output = foo(a_mock);
  assertEquals(expectedValue, output);

  //Case 3: nominal case
  expectedValue = 1;
  output = foo(a_mock);
  assertEquals(expectedValue, output);

}
</code></pre>

<p>This structure works pretty well, but here is my point: unit testing is a testing process that allows you to validate if each unit (here a function) gives you the wanted output, knowing the input. This means that if I need to modify my function foo, but without modifying what it does, my unit tests still have to pass.
Theoretically, if foo is changed like this:</p>

<pre><code>public static int foo(Object a){

  int quantity = 0;
  if(a != null &amp;&amp; a.getInt() != null &amp;&amp; a.getInt() != 5){ //modification here
    quantity = a.getInt();
  }
  return quantity;

}
</code></pre>

<p>Then testFoo still has to pass.
<strong>But it doesn't</strong>, because the <code>.times(2)</code> must be changed in <code>.times(3)</code>.</p>

<p>So here is my question : is the .times(x) method of EasyMock an issue for the robustness of unit tests ? And if no, then what is the minimal level of robustness a unit test must have ?</p>
",https://stackoverflow.com/questions/60439102/is-easymocks-timesx-method-an-issue-for-unit-testing-robustness,"['unit-testing', 'automated-tests', 'easymock']",43,False,0,1
Is there any sqlalchemy list interpolation syntax that works in both sqlite (for test) and mysql (for prod)?,"<p>Here is the tiniest example of code that I need to work (we use mysql in prod, we like raw sql queries for complicated queries because the data analysts can read/modify/audit them, we use sqlite for unit testing)</p>

<pre><code>    from typing import List, Any

    def test_sqlite_params_demo(self, session):
      session.add(build_foo())
      session.commit()
      query = ""select * from foo where id not in :id_list""
      result = session.execute(query, {""id_list"": [9, 99, 999]})
      result_dict: List[Any] = [dict(r) for r in result]
      assert len(result_dict) is 1
</code></pre>

<p>Here is the error that the above causes:</p>

<pre><code>        def do_execute(self, cursor, statement, parameters, context=None):
&gt;       cursor.execute(statement, parameters)
E       sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near ""?"": syntax error
E       [SQL: select * from patient where id not in ?]
E       [parameters: ([9, 99, 999],)]
E       (Background on this error at: http://sqlalche.me/e/e3q8)
</code></pre>

<p>If I use a tuple instead <code>result = session.execute(query, {""id_list"": (9, 99, 999)})</code> then the error reads:</p>

<pre><code>&gt;       cursor.execute(statement, parameters)
E       sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near ""?"": syntax error
E       [SQL: select * from foo where id not in ?]
E       [parameters: ((9, 99, 999),)]
E       (Background on this error at: http://sqlalche.me/e/e3q8)
</code></pre>

<p>Note: this problem only happens when interpolating a <em>list</em> not just a single value </p>

<p>I am using <code>SQLAlchemy==1.3.11</code> in my requirements.txt file</p>

<p>Right now I am faced with the unpleasant choice between rewriting the complex code (to a less desirable format) before adding a test, or adding a test which skips/mocks the part of the code that I most want to test. What is a better option?</p>

<p>This question must have been asked before but I haven't been able to find it. Please point me to it if you know where it is :)</p>
",https://stackoverflow.com/questions/59954884/is-there-any-sqlalchemy-list-interpolation-syntax-that-works-in-both-sqlite-for,"['python', 'mysql', 'sqlite', 'sqlalchemy']",535,True,0,2
"MSUnit test assertion is WRONG. I know why, but I can&#39;t think of how to fix it. Help! What can I do to get my assertion that 3 is the count of users?","<p>I'm new to unit testing and need some help. This example is only for me to learn, I'm not actually counting the number of users in a static variable when I clearly could just use the count property on the List data structure. Help me figure out how to get my original assertion that there are 3 users. Here is the code:</p>

<p>Class User</p>

<pre><code>namespace TestStatic
{
    public class User
    {
        public string Name { get; set; }
        public int Dollars { get; set; }
        public static int Num_users { get; set; }

        public User(string name)
        {
            this.Name = name;
            Num_users++;
        }


        public int CalculateInterest(int interestRate)
        {
            return Dollars * interestRate;
        }
    }
}
</code></pre>

<p>Test using MSTest</p>

<pre><code>namespace TestStaticUnitTest
{
    [TestClass]
    public class CalcInterest
    {
        [TestMethod]
        public void UserMoney()
        {
            // arrange
            User bob = new User(""Bob"");
            bob.Dollars = 24;

            // act
            int result = bob.CalculateInterest(6);

            // assert
            Assert.AreEqual(144, result);

            //cleanup?
        }

        [TestMethod]
        public void UserCount()
        {
            // arrange
            List&lt;User&gt; users = new List&lt;User&gt;(){ new User(""Joe""), new User(""Bob""), new User(""Greg"") };

            // act
            int userCount = User.Num_users;

            // assert
            Assert.AreEqual(3, userCount);
        }
    }
}
</code></pre>

<p>The result in the UserCount test fails because a fourth user exist. The user from the UserMoney test is still in memory. What should I do to get three users? Should I garbage collect the first Bob?</p>

<p>Also, I would think that a test that reaches into another test wouldn't be a good unit test. I know that could be an argument, but I'll take any advice from the community on this code. Thanks for the help.</p>
",https://stackoverflow.com/questions/61564796/msunit-test-assertion-is-wrong-i-know-why-but-i-cant-think-of-how-to-fix-it,"['c#', 'mstest']",74,True,-1,1
GoogleTest - error E0145 - &quot;google::protobuf::internal::ExtensionSet::kMaximumFlatCapacity&quot; may not be initialized,"<p>I was adding some code to a project and wanted to add a Google Test case for it, on the unit testing project called UnitTests. Everything was going fine, my test failed because of some silly copy+paste mistake I made but after I fixed it I couldn't run the test anymore because during the build stage I'd get this error</p>
<blockquote>
<p>Error (active)    E0145   member
&quot;google::protobuf::internal::ExtensionSet::kMaximumFlatCapacity&quot; may
not be initialized    UnitTests</p>
</blockquote>
<p>Which stems from google\protobuf\extension_set.h.</p>
<p>and</p>
<blockquote>
<p>Error LNK1104 cannot open file '\UnitTests.exe'</p>
</blockquote>
<p>I commented-out my new test and tried to rebuild but encountered the same issue.
Then I tried to change to a different branch in my local repository - one without any of that new code and building the unit tests project still resulted in the same issue.</p>
<p>What could be the problem?</p>
<p>I'm using Visual Studio 2017 if it could matter.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/63017197/googletest-error-e0145-googleprotobufinternalextensionsetkmaximumfl,"['c++', 'linker-errors', 'googletest']",191,False,0,0
"How do I test if my data changes? (Vue JS, Jest, Unit Testing)","<p>I am working on unit testing my code with Jest in my frontend Vue JS project, and one of the tests I want to write is:</p>

<pre><code>it('should show the advanced filters if user_id exists', () =&gt; {
  })
</code></pre>

<p>This is part of a created property in the Javascript code:</p>

<pre><code>this.user_id = localStorage.getItem(""user_id"");
      if (this.user_id) {
        this.renderAdvancedFilters = true;
      }
</code></pre>

<p>Also, below is part of the data that is being exported: </p>

<pre><code>export default {
  data: () =&gt; ({
    renderAdvancedFilters: false,
    user_id: localStorage.getItem(""user_id""),
</code></pre>

<p>So, renderAdvancedFilters is originally set to false, but if a user id exists, then it is set to true, and the advanced filters are then displayed. How do I write a unit test where I am showing that if a user id exists, then advanced filters is shown on the app? Since this is a created property, there is no interaction with the app to test, so I think I should just be testing the data, but I'm not sure how to.</p>

<p>Should I be mocking the data of this.user_id? If so, how do I do that?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/59635384/how-do-i-test-if-my-data-changes-vue-js-jest-unit-testing,"['unit-testing', 'vue.js', 'jestjs', 'vuetify.js']",709,True,0,1
Setting a property into request in Django test client,"<p>I have a middleware (tenant_schemas.BaseTenantMiddleware) that will inject <code>tenant</code> property into the request object. I can't use that middleware when unit testing.</p>
<p>In a view I can then get the tenant object from the request. This view is mapped to the URL &quot;myapp:member_info&quot;.</p>
<pre><code>class MemberView(TemplateView):
    template_name = 'myapp/member.html'
    
    def get_context_data(self, member_id=None, *args, **kwargs):
        ctx = super().get_context_data(*args, **kwargs)
        tenant = self.request.tenant
        ctx['tenant_name'] = tenant.name
        return ctx
</code></pre>
<p>This view works when the project is run normally as the middleware will set <code>request.tenant</code> correctly.</p>
<p>Now, if I want to test this view I try to write following test:</p>
<pre><code>class MemberViewTest(TestCase):
    def setUp(self):
        self.tenant = Tenant(name=&quot;test tenant&quot;)
        self.member = Member.objects.create(
            first_name='Test',
            last_name='Person')
        
    def test_saldo(self):
        self.client = Client(tenant=self.tenant) # Here I try to inject the tenant into the request
        print(self.client.defaults) # This will print {'tenant': &lt;Tenant: test tenant&gt;}
        response = self.client.get(reverse('myapp:member_info', kwargs={ 'tenant': self.tenant, 'member_id': self.member.token }))
</code></pre>
<p>This test fails to error:</p>
<pre><code>File &quot;myapp/views.py&quot;, line xxx, in get_context_data
    tenant = self.request.tenant
AttributeError: 'WSGIRequest' object has no attribute 'tenant'
</code></pre>
<p>So, the django.tests.Client class is not injecting the defaults to the request.</p>
<p>One thing I tried is to override the RequestFactory (<a href=""https://github.com/django/django/blob/ac6c4260074de43a978e5c6553ef89441e1d6748/django/test/client.py#L308"" rel=""nofollow noreferrer"">https://github.com/django/django/blob/ac6c4260074de43a978e5c6553ef89441e1d6748/django/test/client.py#L308</a>) so that it would inject the tenant.</p>
<pre><code>class TenantRequestFactory(RequestFactory):
    def request(self, **request):
        req = super().request(**request)
        req.tenant = Tenant()
        print(req)
        return req
        
class TenantClient(Client, TenantRequestFactory):
    pass

views.py
    def test_saldo(self):
        self.client = TenantClient(tenant=self.tenant)
</code></pre>
<p>But the <code>TenantRequestFactory.request()</code> is never called (the print command is not hitting). I don't know if I should subclass it some other way? In <code>client.py</code> the Client class is created like this: <code>class Client(ClientMixin, RequestFactory)</code></p>
",https://stackoverflow.com/questions/64351759/setting-a-property-into-request-in-django-test-client,"['django', 'django-tests']",245,False,0,0
Why are instances of my mocked class sharing attributes?,"<p>I've got the following 3 files:</p>
<p><em>shape.py</em></p>
<pre><code>import danger_import

class Polygon:
  def __init__(self, height=10, width=10):
    self.height = height
    self.width = width
    self.isActive = False

  def activate():
    self.isActive = True
</code></pre>
<p><em>polygon_utility.py</em></p>
<pre><code>import shape

poly1 = None
poly2 = None

def activate_polygon():
  poly1.activate()
  if False:
    poly2.activate()

if __name__ != '__main__':
  poly1 = shape.Polygon()
  poly2 = shape.Polygon(4,12)
</code></pre>
<p><em>test_polygon_utility.py</em></p>
<pre><code>import pytest
import sys
from unittest import mock

sys.modules['danger_import'] = mock.MagicMock()
import polygon_utility
import shape

@mock.patch('shape.Polygon')
def test_activate_polygon(mock_poly):
  polygon_utility.poly1 = mock_poly()
  polygon_utility.poly2 = mock_poly(4,12)
  polygon_utility.activate_polygon()
  assert polygon_utility.poly1.activate.call_count == 1
  assert polygon_utility.poly2.activate.call_count == 0
</code></pre>
<p>Basically I have this polygon class that I will be creating several polygons from. The polygon utility manages several polygons based on some logic I did not include. I am intending to unit test the activate_polygon function, which relies on the polygons object existing.for that I am importing the shape file so that I can create mock instances of the Polygon class. then i assign them to the global variables poly1 and poly2 in the file I am unit testing, and attempt to run the function.</p>
<p>When I run this unit test I get a failure on the second assertion. it seems that for some reason the 2 polygon instances I have created are tied together. Could anyone explain to me why that is and how I would go about getting the behavior I want?</p>
",https://stackoverflow.com/questions/63079046/why-are-instances-of-my-mocked-class-sharing-attributes,"['python', 'python-3.x', 'unit-testing', 'mocking']",53,False,0,1
@Autowired should not work without @RunWith(SpringRunner.class) but does,"<p>Here is a unit testing class for a java spring data repository layer.
I have a spring data repository layer in which the annotation @Autowired is used to inject TestEntityManager type object (belongs to spring data package).
The autowiring works whitout adding @RunWith(SpringRunner.class) annotation !
So what is the problem ? Well, I think that injection should not be possible whitout adding @RunWith(SpringRunner.class) annotation to the class : it should not work without it theorically.
How is it possible ? Does someone have any answer ?</p>
<p><a href=""https://github.com/userInterview/LoizSpringRestPersistenceTests/blob/main/src/test/java/org/loiz/demo/LoizPersistenceTest.java"" rel=""nofollow noreferrer"">&gt;&gt;&gt;&gt; view complete spring boot app code on github available here</a></p>
<ul>
<li>Someone else have had <strong>the opposite problem</strong> in stackoverflow :</li>
</ul>
<p><a href=""https://stackoverflow.com/questions/58634359/test-annotated-with-datajpatest-not-autowiring-field-annotated-with-autowired"">Someone else have had the opposite problem : see link here</a></p>
<p>Here is my strange bloc of code that amazingly that works :</p>
<p>package org.loiz.demo;</p>
<pre><code>import org.assertj.core.api.BDDAssertions;
import org.junit.Assert;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test ;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.Order ;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import demo.LoizBootSpringDemoApplication;
import demo.crepository.UserRepositoryInterface;
import demo.dmodel.User;
import demo.helper.helperUtils;

//Test de la couche de persistence
//@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = { LoizBootSpringDemoApplication.class})
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@SuppressWarnings(&quot;unused&quot;)
public class LoizPersistenceTest 
{
    
    @Autowired
    private TestEntityManager testEntityManager;

    @Autowired
    private UserRepositoryInterface repository; 

    private static Long idStub ;
    
    @Test
    @Order(1)
    @Rollback(false)
    @DisplayName(&quot;Test de sauvegarde d\'un user \&quot;prenom21 Nom21\&quot;&quot;)    
    public void saveShouldMapCorrectly() throws Exception {
        
        User userStub = new User(&quot;prenom21&quot;, &quot;Nom21&quot;);                       
        
        User UserSaved = this.testEntityManager.persistFlushFind(userStub);
        
        BDDAssertions.then(UserSaved.getId()).isNotNull();                    
        idStub = UserSaved.getId() ;
        
        User UserRead = this.testEntityManager.find(User.class, idStub) ;       
        
        BDDAssertions.then(UserSaved.getFirstName()).isNotBlank();
        BDDAssertions.then(UserSaved.getFirstName()).isEqualToIgnoringCase(&quot;prenom21&quot;);
        

        BDDAssertions.then(UserSaved.getLastName()).isEqualToIgnoringCase(&quot;Nom21&quot;);
        BDDAssertions.then(UserSaved.getLastName()).isNotBlank();
    }

    @Test
    @Order(2) 
    @DisplayName(&quot;Test d'existence du user \&quot;prenom21 Nom21\&quot;&quot;) 
    public void readShouldMapCorrectly() throws Exception {
        User userStub = new User(idStub, &quot;prenom21&quot;, &quot;Nom21&quot;);          
        User userFetched  = this.testEntityManager.find(User.class, idStub) ;
        
        String sUserStub = userStub.toString() ;        
        String sUserFetched = userFetched.toString() ;      
        
        
        boolean bolSameObject = userStub.equals(userFetched) ;
        
        boolean bolAttrEgalEgal = sUserStub == sUserFetched ;       
        
        boolean bolStringEqual = sUserStub.equals(sUserFetched) ;           
        
        boolean bBeanUtil = helperUtils.haveSamePropertyValues (User.class,userStub,userFetched) ;
        
                
        Assert.assertTrue(bBeanUtil);
        
    }

}
</code></pre>
<p>Maybe it is normal, but what do i have to know ?
I would appreciate some answer please :)</p>
<p><a href=""https://github.com/userInterview/LoizSpringRestPersistenceTests/blob/main/src/test/java/org/loiz/demo/LoizPersistenceTest.java"" rel=""nofollow noreferrer"">&gt;&gt;&gt;&gt; view complete spring boot app code on github available here</a></p>
",https://stackoverflow.com/questions/65348079/autowired-should-not-work-without-runwithspringrunner-class-but-does,"['spring', 'spring-boot', 'unit-testing', 'dependency-injection', 'repository']",999,True,4,2
How to mock IDocumentClient using Moq?,"<p>I am new to unit/integration testing, and to the .NET world.</p>
<p>Problem-1 : In one of the integration tests, I have to pass a (mock of) IConfiguration variable, which I currently build as</p>
<p><code>var mockConfig = GetConfiguration();</code></p>
<pre><code>    private static IConfiguration GetConfiguration() =&gt;
        new ConfigurationBuilder()
            .SetBasePath($&quot;{Directory.GetCurrentDirectory()})
            .AddJsonFile(&quot;appSettings.json&quot;, true)
            .AddCommonVariables()
            .Build();
</code></pre>
<p>Trial-1: I have tried to do this</p>
<pre><code>    private static Mock&lt;IConfiguration&gt; GetConfiguration() =&gt;
        new Mock&lt;IConfiguration&gt;(new ConfigurationBuilder()
            .SetBasePath($&quot;{Directory.GetCurrentDirectory()})
            .AddJsonFile(&quot;appSettings.json&quot;, true)
            .AddCommonVariables()
            .Build());
</code></pre>
<p>but, it exceptioned out with</p>
<blockquote>
<p>Constructor arguments cannot be passed for interface mocks.</p>
</blockquote>
<p>Trial-2: I tried to create with the Setup options of Moq</p>
<pre><code>    private static Mock&lt;IConfiguration&gt; GetMockConfiguration()
    {
        var _mockConfigurationBuilder = new Mock&lt;ConfigurationBuilder&gt;();

        //How to setup these methods?
        _mockConfigurationBuilder.Setup(x =&gt; x.SetBasePath(It.IsAny&lt;String&gt;())).Returns();
        -_mockConfigurationBuilder.Setup(x =&gt; x.AddJsonFile()).Returns()
    }
</code></pre>
<p>but I am not sure how to set up these methods.</p>
<p>Problem-2: Is to ultimately mock IDocumentClient, which I use to query my entities</p>
<p><code>_cosmosWrapper = new CosmosWrapper(mockLogger.Object, mockConfig.Object);</code> use it as</p>
<pre><code>private readonly IDocumentClient _documentClient;
public CosmosWrapper(ILogger&lt;CosmosWrapper&gt; logger, IConfiguration config)
{
  var cosmosConnectionSecretKey = config[&quot;cosmosSecretName&quot;];
  var cosmosConnectionString = config[cosmosConnectionSecretKey];
  var cosmosInfo = ConnectionStringParser.Parse(cosmosConnectionString);
  _documentClient = new DocumentClient(new Uri(cosmosInfo[&quot;AccountEndpoint&quot;]), cosmosInfo[&quot;AccountKey&quot;]);
}
</code></pre>
<p><em><strong>Update:</strong></em></p>
<p>I had to refactor the setup of document client, by creating a cosmos connection class.</p>
<p>And the setup for mock - cosmos connection was,</p>
<pre><code>    var cosmosConnection = new Mock&lt;ICosmosConnection&gt;();

    cosmosConnection.Setup(c =&gt; c.CosmosInfo)
        .Returns(new Dictionary&lt;string, string&gt;(new List&lt;KeyValuePair&lt;string, string&gt;&gt;
        {
            new KeyValuePair&lt;string, string&gt;(&quot;AccountEndpoint&quot;, &quot;//string1.string2&quot;)
        }));
</code></pre>
<p>And finally for mocking the document client, I took ideas from <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>and implemented few more helper methods, for my needs.</p>
<pre><code>private static void SetupProvider(Mock&lt;IFakeDocumentQuery&lt;MyClass&gt;&gt; mockDocumentQuery,
    Mock&lt;IQueryProvider&gt; provider)
{
    provider.Setup(p =&gt; p.CreateQuery&lt;MyClass&gt;(It.IsAny&lt;Expression&gt;())).Returns(mockDocumentQuery.Object);
    mockDocumentQuery.As&lt;IQueryable&lt;MyClass&gt;&gt;().Setup(x =&gt; x.Provider).Returns(provider.Object);
}
</code></pre>
<p>and</p>
<pre><code>private static void SetupMockForGettingEntities(Mock&lt;IDocumentClient&gt; mockDocumentClient,
    IMock&lt;IFakeDocumentQuery&lt;MyClass&gt;&gt; mockDocumentQuery)
{
    mockDocumentClient.Setup(c =&gt; c.CreateDocumentQuery&lt;MyClass&gt;(It.IsAny&lt;Uri&gt;(), It.IsAny&lt;FeedOptions&gt;()))
        .Returns(mockDocumentQuery.Object);
}
</code></pre>
",https://stackoverflow.com/questions/62767856/how-to-mock-idocumentclient-using-moq,"['unit-testing', '.net-core', 'integration-testing', 'azure-cosmosdb', 'moq']",287,True,0,1
Mocking data using Moq and xunit,"<p>I am new to unit testing and by following so many articles, I am able to write below unit test but it is not working since there is no relationship between main class and factory class. How to solve this problem? Is it possible to write unit test without changing the structure of my class.</p>

<p>My Class:</p>

<pre><code>public class SomeClass : ISomeClass
        {    
            public ServiceClientManager&lt;IScan&gt; scan;

            public SomeClass(Action&lt;String&gt; logMessages)
            {
                this.logMessage = logMessages;
            }

            public void Process(string a, string b, string c)
            {
            if (this.Scan == null)
            {
               ConnectToScan();                   
            }

            if (status)
            {
                Scan.Proxy.MethodScan(a, b, c);
            }
        }
} 



public bool ConnectToScan()
        {
            this.Scan = null;
                NetTcpBinding netTcpBinding = new NetTcpBinding();
                netTcpBinding.MaxBufferSize = int.MaxValue;
                netTcpBinding.MaxReceivedMessageSize = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxArrayLength = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxDepth = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;
                netTcpBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
                netTcpBinding.ReceiveTimeout = TimeSpan.FromMinutes(5);
                netTcpBinding.CloseTimeout = TimeSpan.FromMinutes(5);
                netTcpBinding.OpenTimeout = TimeSpan.FromMinutes(5);
                netTcpBinding.SendTimeout = TimeSpan.FromMinutes(5);
                barcodeScanner = new ServiceClientManager&lt;IScan&gt;(netTcpBinding, new EndpointAddress(""net.tcp://localhost/XXXX""));
                return true;
        }
</code></pre>

<p>Here, ConnectToScan() will establish the connection to the service and I am using it inside Process method to pass parameters to that service. In order to write unit test for this method, I am trying to mock the service ""IScan"" and assert that service method is called atleast once.</p>

<p>My unit test:</p>

<pre><code>  private Action&lt;string&gt; _logMessage = msg =&gt; Console.WriteLine(msg);

       [Fact]
    public void MethodTest()
    {
        var factoryScanMoq = new Mock&lt;IScan&gt;();
        factoryScanMoq.Setup(x =&gt; x.MethodScan(""test"", ""S000"", ""test2""))
        .Returns(null);

        var mockService = new ServiceClientManager&lt;IScan&gt;(factoryBarcodeScanMoq.Object);

        classObj.process(""test"", ""S000"", ""test2""); // FactoryScanMoq is not passed here

        classObj.Scan = mockService;

        factoryScanMoq.Verify(x =&gt; x.MethodScan(""test"", ""S000"", ""test2""), Times.Once);
    }
</code></pre>

<p>I Know there is no relation between factory Mock and SomeClass but I am not sure how to create a relation since I cannot pass FactoryMoq to SomeClass as a constructor argument.</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/61365977/mocking-data-using-moq-and-xunit,"['c#', 'unit-testing', 'moq', 'xunit']",182,False,0,0
Remove a source file after adding it with target_sources() in CMake,"<p>I am using CMake 3.16.</p>
<p>I add my source files to my target with target_sources(). I would like later in my CMakeLists.txt to remove a source file I previously added with target_sources().</p>
<p>For example:</p>
<pre><code>target_sources(my_target PRIVATE main.c abc.c def.c ghi.c)

# Later...

# Remove def.c from the previously added source files.
</code></pre>
<p>Is there a way to do this ideally without setting a custom &quot;sources&quot; variable and removing it from this list with list(REMOVE_ITEM ...)?</p>
<p>EDIT:<br />
The context of this question is unit testing static functions in C.
My program is made of a lot of static functions that I want to unit test. To test them, I decided to include the .c file in the test files instead of the .h.</p>
<p>For example:<br />
abc.c:</p>
<pre class=""lang-c prettyprint-override""><code>#include &quot;abc.h&quot;
// several static functions defined here
</code></pre>
<p>abc.h:</p>
<pre class=""lang-c prettyprint-override""><code>// some stuff
</code></pre>
<p>test_abc.c:</p>
<pre class=""lang-c prettyprint-override""><code>#include &quot;unity.h&quot; // a unit test framework
#include &quot;abc.c&quot; // notice the .c instead of the .h to be able to test the static functions

// the test functions
</code></pre>
<p>By doing this, I need to remove in CMake the xxx.c file if I add the test_xxx.c file because otherwise the content of the xxx.c file will be defined 2 times and the linker will not be happy with it.</p>
",https://stackoverflow.com/questions/63157793/remove-a-source-file-after-adding-it-with-target-sources-in-cmake,"['c++', 'c', 'cmake']",1206,True,0,1
readonly object for unit testing is being disposed when using &#39;using&#39;,"<p>I have an object that is used a bunch of times within the same unit test, and in other unit tests within the same class, that is defined as follows:</p>

<pre><code>private readonly Task&lt;HttpResponseMessage&gt; successfulResponse = Task.FromResult(
            new HttpResponseMessage()
            {
                StatusCode = System.Net.HttpStatusCode.OK,
                Content = new StringContent(@""{""""EntitySets"""":[{""""ResultSets"""":[{""""Results"""":[{""""Type"""":""""Message""""}],""""Total"""":2}],""""EntityType"""":""""Message""""}]}"")
            });
</code></pre>

<p>Then in each of my relevant unit tests, I'm doing something like this:</p>

<pre><code>mockHttpClient.Setup(m =&gt; m.SendAsync(It.Is&lt;HttpRequestMessage&gt;(v =&gt;
            v.RequestUri.Host.Equals(""example.com"")),
            It.IsAny&lt;CancellationToken&gt;())).Returns(successfulResponse);
</code></pre>

<p>... where <code>mockHttpClient</code> is a mocked <code>HttpClient</code>.</p>

<p>But when I'm unit testing, this sort of logic is executed in a lot of places inside the code being tested:</p>

<pre><code>using (HttpResponseMessage response = await this.client.SendAsync(request, cancellationToken))
{
//...
}
</code></pre>

<p>... where <code>this.client</code> is <code>mockHttpClient</code> from above. As you can tell, <code>Moq</code> provides my pre-prepared <code>successfulResponse</code> object here to simulate a http response.</p>

<p>Problem is, when the <em>very first</em> execution of such a <code>using</code> statement is executed, it disposes <code>successfulResponse</code> when it gets out of the <code>using</code> block, and all following <code>using</code> blocks fail with the following exception:</p>

<pre><code>Test method TestProbe_Success threw exception: 
    System.ObjectDisposedException: Cannot access a disposed object.
    Object name: 'System.Net.Http.StringContent'.
</code></pre>

<p>So my question is, how can I prevent the code being tested from disposing this object, which is used multiple times within the same unit test and in other unit tests ? </p>
",https://stackoverflow.com/questions/60608041/readonly-object-for-unit-testing-is-being-disposed-when-using-using,"['c#', 'unit-testing', 'moq', 'dispose', 'using']",933,True,0,1
DataflowBlock ITargetSource.AsObservable() not triggering OnNext(),"<p>I'm trying to use a dataflowblock and I need to spy the items passing through for unit testing.</p>
<p>In order to do this, I'm using the <code>AsObservable()</code> method on <code>ISourceBlock&lt;T&gt;</code> of my <code>TransformBlock&lt;Tinput, T&gt;</code>,
so I can check after execution that each block of my pipeline have generated the expected values.</p>
<h3>Pipeline</h3>
<pre class=""lang-cs prettyprint-override""><code>{
   ...
   var observer = new MyObserver&lt;string&gt;();
   _block  = new TransformManyBlock&lt;string, string&gt;(MyHandler, options);
   _block.LinkTo(_nextBlock);
   _block.AsObservable().Subscribe(observer);
   _block.Post(&quot;Test&quot;);
   ...
}
</code></pre>
<h3>MyObserver</h3>
<pre class=""lang-cs prettyprint-override""><code>public class MyObserver&lt;T&gt; : IObserver&lt;T&gt;
{
    public List&lt;Exception&gt; Errors = new List&lt;Exception&gt;();
    public bool IsComplete = false;
    public List&lt;T&gt; Values = new List&lt;T&gt;();

    public void OnCompleted()
    {
        IsComplete = true;
    }

    public void OnNext(T value)
    {
        Values.Add(value);
    }

    public void OnError(Exception e)
    {
        Errors.Add(e);
    }
}
</code></pre>
<p>So basically I subscribe my observer to the transformblock, and I expect that each value passing through get registered in my observer &quot;values&quot; list.</p>
<p>But, while the <code>IsComplete</code> is set to true, and the <code>OnError()</code> successfully register exception,
the <code>OnNext()</code> method never get called unless it is the last block of the pipeline...
I can't figure out why, because the &quot;nextblock&quot; linked to this sourceBlock successfully receive the data, proving that some data are exiting the block.</p>
<p>From what I understand, the <code>AsObservable</code> is supposed to report every values exiting the block and not only the values that have not been consumed by other linked blocks...</p>
<p>What am I doing wrong ?</p>
",https://stackoverflow.com/questions/63630681/dataflowblock-itargetsource-asobservable-not-triggering-onnext,"['c#', '.net', 'tpl-dataflow']",116,True,3,1
Useless test failure messages for Jasmine in Visual Studio 2019,"<p>I'm trying to figure out how to use Visual Studio 2019 for unit testing Jasmine tests written in TypeScript.</p>

<p>The standard <em>TypeScript Jasmine UnitTest file</em> template generates this file:</p>

<pre><code>describe('Test Suite 1', () =&gt; {
    it('Test 1', () =&gt; {

        expect(1).toBe(1);
    });

    it('Test 2', () =&gt; {

        fail(""this is expected to fail."")
    });
});
</code></pre>

<p>When I run it, I have, as expected, 1 succeeding and 1 failing test. When I click on the failing test (<em>Test 2</em>), I get this:</p>

<pre><code> Test 2
   Source: MazeGameTests.ts line 2
   Duration: 4 ms

   Open additional output for this result
</code></pre>

<p>This already seems wrong to me, because it reports that the failure happens on <strong>line 2</strong>. That's also where Visual Studio takes me when I click on the file name. <em>Test 2</em>, however, starts on line 7.</p>

<p>It gets worse, though. When I click on <em>Open additional output for this result</em>, I get this:</p>

<pre><code>Test Name:  Test 2
Test Outcome:   Failed
Result StandardOutput:  
Using Jasmine settings:  {}
Randomized with seed 00316
Started
F
</code></pre>

<p>Notice the last line: <strong>F</strong>.</p>

<p>It's not that I clipped the text. That's what it looks like.</p>

<p>This means that <strong>assertion messages are not shown</strong>.</p>

<p>That makes the test runner basically useless, since I can't see where and why tests fail. Is this a known problem? Can it be addressed?</p>
",https://stackoverflow.com/questions/59578959/useless-test-failure-messages-for-jasmine-in-visual-studio-2019,"['typescript', 'jasmine', 'visual-studio-2019']",246,False,3,0
How do I fail a Jenkins pipeline with below a certain PHPUnit code coverage percentage?,"<p>I am using a Jenkins declarative pipeline to implement continuous integration with my code. The code is a PHP project that uses PHPUnit for unit testing.</p>

<p>Currently, the pipeline</p>

<ol>
<li>builds the project</li>
<li>runs a code sniffer to find coding violations</li>
<li>runs PHPUnit tests, generating coverage reports and publishing them</li>
</ol>

<p>If any PHPUnit test fails, the Jenkins job fails (which is good).</p>

<p>Now, I also want to fail the job if the code coverage percentage is below a certain amount. I can't find how to do so.</p>

<p>The current Jenkinsfile looks like this:</p>

<pre><code>pipeline {

    agent any

    stages {
        stage ('Build') {
            steps {
                sh '''
                    cd symfony &amp;&amp; composer install --prefer-dist
                    ./vendor/bin/pcov clobber
                '''
            }
        }

        stage('PHP CodeSniffer') {
            steps {
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                    sh './symfony/vendor/bin/phpcs-meq.sh ./symfony/src/AppBundle'
                }
            }
        }

        stage('PHPUnit Tests') {
            steps {
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                    sh '''
                        cd symfony
                        cp phpunit.xml.dist phpunit.xml
                        ./bin/console cache:warmup --env=test
                        ./vendor/bin/phpunit\
                            --coverage-clover '../reports/coverage/coverage.xml'\
                            --coverage-html '../reports/coverage'\
                            --log-junit '../reports/unitreport.xml'
                    '''
                }

                junit 'reports/unitreport.xml'

                publishHTML([
                    allowMissing: true,
                    alwaysLinkToLastBuild: false,
                    keepAll: true,
                    reportDir: 'reports/coverage',
                    reportFiles: 'index.html',
                    reportName: 'PHPUnit Test Coverage Report'
                ])
            }
        }
    }
}
</code></pre>

<p>I have found this snippet, which publishes the clover report. I thought that perhaps making the ""failingTarget"" high enough would exit 1 (fail the pipeline) if the coverage didn't make the requirement. It doesn't -- it outputs a warning, but the step still succeeds. </p>

<pre><code>            step([
                $class:'CloverPublisher',
                cloverReportDir: '../reports/coverage',
                cloverReportFileName: 'coverage.xml',
                healthyTarget: [methodCoverage: 90, conditionalCoverage: 90, statementCoverage: 90],
                unhealthyTarget: [methodCoverage: 89, conditionalCoverage: 89, statementCoverage: 89],
                failingTarget: [methodCoverage: 88, conditionalCoverage: 88, statementCoverage: 88]
            ])
</code></pre>

<p>How can I fail a Jenkins pipeline if my PHP code coverage is below a certain threshold?</p>
",https://stackoverflow.com/questions/60233612/how-do-i-fail-a-jenkins-pipeline-with-below-a-certain-phpunit-code-coverage-perc,"['jenkins', 'continuous-integration', 'phpunit', 'jenkins-pipeline']",1480,True,2,1
How to test Window beforeunload event method - Angular Unit Test,"<p>I'm working in an Angular 8 project.</p>

<p>I wanted to have the window throw a confirm prompt if the user tried to navigate away from the site, I was able to do this by adding this function to my component.</p>

<pre><code>@HostListener(""window:beforeunload"", [""$event""])
  unloadNotification($event: any) {
    if (this.confirmNavigation) {
      $event.returnValue = true;
    }
  }
</code></pre>

<p>Now I'm trying to figure out how to unit test this, and I'm not sure how to do it. Would I need to mock the window in order to trigger the event? Would I make some sort of event object and call <code>unloadNotification</code> with it directly (not sure how to verify the result of it though)?</p>

<p>I'm even sure if this is needed in unit testing, would it be more of an integration test?</p>

<p>I also need to make sure this prompt isn't actually triggered when I run the tests in karma (because it'll stop the test). So I need to mock that?</p>

<p>Also, I think I want to destroy this listener in the afterEach of my tests, but not sure how.</p>

<p>Any help would be appreciated, thanks.</p>
",https://stackoverflow.com/questions/62470487/how-to-test-window-beforeunload-event-method-angular-unit-test,"['angular', 'unit-testing', 'testing', 'window', 'onbeforeunload']",2837,True,2,1
How to get Context in unit test to create Room database in memory database object,"<p>I'm trying to test this one function in my application repository class which performs a database insertion. I'm using <code>Koin</code> as my dependency injection library. To do the testing I need to create a Database version that gets built in memory. To create that database I need the Android application context. So I created my test class like below.</p>

<pre><code>import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.platform.app.InstrumentationRegistry
import com.chathuranga.shan.mycontacts.di.applicationModule
import com.chathuranga.shan.mycontacts.di.repositoryModule
import com.chathuranga.shan.mycontacts.room.AppDatabase
import org.junit.After
import org.junit.Test

import org.junit.Before
import org.junit.Rule
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.loadKoinModules
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.inject
import org.mockito.MockitoAnnotations

class ContactRepositoryTest : KoinTest {

    private val contactRepository: ContactRepository by inject()
    private lateinit var appDatabase: AppDatabase

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Before
    fun setUp() {

        startKoin {
            printLogger()
            modules(listOf(applicationModule,repositoryModule))
        }

        MockitoAnnotations.initMocks(this)

        val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()
        //val instrumentationContext = InstrumentationRegistry.getInstrumentation().targetContext

        appDatabase = Room
            .inMemoryDatabaseBuilder(context, AppDatabase::class.java)
            .allowMainThreadQueries()
            .build()

        loadKoinModules(module { single(override = true) { appDatabase } })
    }

    @Test
    fun insertContact() {

        val firstName = ""Chathuranga""
        val secondName = ""Shan""
        val phone = ""07711247890""

        contactRepository.insertContact(firstName,secondName,phone,null,null)

    }

    @After
    fun tearDown() {
        stopKoin()
    }
}
</code></pre>

<p>And I'm getting this exception.</p>

<p><strong>java.lang.IllegalStateException: No instrumentation registered! Must run under registering instrumentation.</strong></p>

<p>As you can see I tried two ways to get <code>Context</code> (check the commented line in above class) and both failed the same way. And error pointed to the place where I create <code>Context</code> object. This test class in <code>test</code> folder not in <code>androidTest</code> folder. I want to separate this function and other functions that gonna come in the future and test in this class.</p>

<p>Here are my dependencies</p>

<pre><code>//Testing
testImplementation 'junit:junit:4.12'
testImplementation ""org.mockito:mockito-core:2.21.0""
testImplementation 'android.arch.core:core-testing:1.1.1'
testImplementation 'androidx.test:core:1.2.0'
testImplementation 'org.koin:koin-test:2.0.1'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
</code></pre>

<p>My dependency injection class.</p>

<pre><code>val applicationModule = module {
    single { AppDatabase.getDatabaseInstance(androidContext().applicationContext) }
}

val activityModule = module {

    scope(named&lt;MainActivity&gt;()) {
        scoped { (activity: MainActivity) -&gt;
            Navigation
                .findNavController(activity, R.id.hostFragment)
        }
    }
}
</code></pre>

<p>I'm new to testing. If the way I have grasped the concept of unit testing please point it out. Otherwise 
Point out the problem with this code. Thanks.</p>
",https://stackoverflow.com/questions/59799156/how-to-get-context-in-unit-test-to-create-room-database-in-memory-database-objec,"['android', 'unit-testing', 'kotlin', 'koin']",6725,True,10,1
How do i unit test an exception that&#39;s being thrown by an &quot;update user&quot; endpoint?,"<p>I'm currently unit testing the endpoints of a <strong>Spring Boot CRUD RESTful API</strong> and i have the following <em>&quot;Update user by its id&quot;</em> endpoint that's composed of a <strong>controller</strong> and a <strong>service</strong> to implement its logic :</p>
<p><strong>Update controller</strong> (it's mainly calling the logic of the service and defining some guidelines) :</p>
<pre><code>@RestController
@RequestMapping(&quot;/users/{id}&quot;)
public class UpdateUserController {

    @Autowired
    UpdateUserService service;

    @PutMapping
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity&lt;User&gt; updateUser_whenPutUser(@RequestBody User user, @PathVariable Long id) {
        return ResponseEntity.ok().body(service.updateUser(id, user));
    }
}
</code></pre>
<p><strong>Update service</strong> :</p>
<pre><code>@Service
public class UpdateUserService {

    @Autowired
    UserRepository repository;

    public User updateUser(Long id, User user) {

        repository.findById(id)
                .orElseThrow(() -&gt; new UserNotFoundException(id));

        user.setId(id);
        return repository.save(user);
    }
}
</code></pre>
<p>While everything seems to be working fine until now, i'd appreciate if someone could tell me what i could improve in the code above. Anyways, my controllers throw exception unit test is the problem i can't seem to solve :</p>
<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(UpdateUserController.class)
public class UpdateUserControllerTest {
    @Autowired
    private MockMvc mvc;

    @MockBean
    private UpdateUserService updateUserService;

    @Test
    public void updateUser_whenPutUser() throws Exception {

        User user = new User();
        user.setName(&quot;Test Name&quot;);
        user.setId(89L);

        given(updateUserService.updateUser(user.getId(), user)).willReturn(user);

        ObjectMapper mapper = new ObjectMapper();

        mvc.perform(put(&quot;/users/&quot; + user.getId().toString())
                .content(mapper.writeValueAsString(user))
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;name&quot;, is(user.getName())));
    }

    @Test
    public void should_throw_exception_when_user_doesnt_exist() throws Exception {
        User user = new User();
        user.setId(89L);
        user.setName(&quot;Test Name&quot;);

        Mockito.doThrow(new UserNotFoundException(user.getId())).when(updateUserService).updateUser(user.getId(), user);

        mvc.perform(put(&quot;/users/&quot; + user.getId().toString())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isNotFound());
    }
}
</code></pre>
<p>Although the <em>updateUser_whenPutUser</em> is passing, the exceptions unit test is resulting in :</p>
<pre><code>java.lang.AssertionError: Status expected:&lt;404&gt; but was:&lt;400&gt;
Expected :404
Actual   :400
</code></pre>
<p>Which means it's getting a <strong>400</strong> response status instead of the expected <strong>404</strong> thrown by the exception.</p>
<p>Curiously, if i change my <em>@WebMvcTest(UpdateUserController.class)</em> to <em>@WebMvcTest(UpdateUserService.class)</em> it passes, but then my controllers main unit test fails. No idea why.</p>
<p>Would appreciate if someone could help with this one.</p>
",https://stackoverflow.com/questions/62515912/how-do-i-unit-test-an-exception-thats-being-thrown-by-an-update-user-endpoint,"['java', 'spring', 'api', 'unit-testing', 'junit']",1032,False,1,2
Test exceptions in private delegate method,"<p>I'm designing a WPF application in MVVM manner and I have an issue how to test that exception was thrown when message was sent by another viewmodel. I'm using nUnit for unit testing.</p>

<p>I try to test that delegate throws an exception when object sent via messenger is null.</p>

<p>Please find simple code below
<br><strong>CTOR</strong> (all dependencies are injected using Autofac)</p>

<pre class=""lang-cs prettyprint-override""><code>    public ManagerViewModel (IMessenger messenger)
    {
       messenger.Register&lt;Person&gt; (this, OnPersonSent)
    }
</code></pre>

<p><strong>Delegate</strong></p>

<pre class=""lang-cs prettyprint-override""><code>    private void OnPersonSent()
    {
       if(Person is null) throw new ArgumentNullException();
    }
</code></pre>

<p><br> <strong>Unit test</strong>
<br>When I try to assert as below it doesn't catch the exceptions. The situation is that when messenger sends message the OnPersonSent method should throws an exception - but how to catch it using Assert.Throws if this assertion catches only the exception throws by a method passed in lambda expression (if I'm wrong please correct me). Test case below:</p>

<pre class=""lang-cs prettyprint-override""><code>    [SetUp]
    public void SetUp()
    {
      messenger = new Messenger() // MVVMLight messenger
      sut = new ManagerViewModel(messenger)
    }
</code></pre>

<p>Below in lambda expression I'm sending null object in order to throw an exception by a delegate which is pointed above</p>

<pre class=""lang-cs prettyprint-override""><code>    [Test] 
    public void OnPersonSent_WhenNull_ThrowsException()
    {    
           Assert.Throws&lt;ArgumentNullException&gt;(()=&gt;messenger.Send((Person)null));
    }
</code></pre>

<p>Thank you very much for your help.</p>

<p>PS. Of course this case is simplified in order to clearly show the issue</p>
",https://stackoverflow.com/questions/60590317/test-exceptions-in-private-delegate-method,"['c#', 'wpf', 'unit-testing', 'exception', 'mvvm']",317,True,1,1
Moq and multiple method setup,"<p>I am trying to learn MOQ as well as unit testing with xUnit at the same time.</p>

<p>I have an Authentication logic class with a few methods. They all make use of an AuthenticationDataAccessor. I am trying to mock out that accessor to retain unit test isolation to the logic only.</p>

<p>I am trying to unit test the logic of two methods within my logic class.</p>

<p>RegisterAsync and AuthenticateAsync</p>

<pre><code>private void SetupMocks()
        {
            // Mock the data accessor.
            var _mockedDataAccessor = new Mock&lt;IAuthenticationData&gt;();

            // Moke the call that will go to the mocked data accessor.
            var _mockedAuthenticationRequest = new AuthenticationRequest { Username = It.IsAny&lt;string&gt;(), Password = It.IsAny&lt;string&gt;() };
            var _mockedRegistrationRequest = new RegistrationRequest { Email = It.IsAny&lt;string&gt;(), Password = It.IsAny&lt;string&gt;(), Firstname = It.IsAny&lt;string&gt;(), Surname = It.IsAny&lt;string&gt;()  };

            // Setup the accessor.
            _mockedDataAccessor
                .Setup(x =&gt; x
                .AuthenticateAsync(_mockedAuthenticationRequest))
                .ReturnsAsync(
                    new SharedLib.Responses.UserResponse
                    {
                        ResponseState = new SharedLib.Responses.ResponseState
                        {
                            Description = ""Moq description"",
                            IsSuccess = true,
                            ResponseCode = ResponseCode.OK,
                            SystemError = false
                        }
                    });


            _mockedDataAccessor
                .Setup(x =&gt; x
                .RegisterAsync(_mockedRegistrationRequest))
                .ReturnsAsync(
                    new SharedLib.Responses.RegistrationResponse
                    {
                        ResponseState = new SharedLib.Responses.ResponseState
                        {
                            Description = ""Moq description"",
                            IsSuccess = true,
                            ResponseCode = ResponseCode.OK,
                            SystemError = false
                        }
                    });


            // Create the logic reference based on the mocked data accessor
            _logic = new AuthenticationLogic(_mockedDataAccessor.Object);

        }
</code></pre>

<p>So, I have two setup calls. One for data accessor method I am mocking out.</p>

<p>However, when I execute my unit test:</p>

<pre><code>[Fact]
public async void RegisterWithValidDetailsReturnsSuccess()
{
    SetupMocks();

    var result = await _logic.RegisterAsync(new RegistrationRequest
    {
        Email = ""a.valid@email.com"",
        Firstname = ""ValidFirstname"",
        Password = ""AString@Password123"",
        Surname = ""AValid Surname"",
        TimezoneId = 1
    });

    Assert.Equal(ResponseCode.OK, result.ResponseState.ResponseCode);
}
</code></pre>

<p><code>result</code> is always null. I'd expect it to bewhat ever I set in my setup above.</p>

<p>Note that a test that uses my Authenticate mock, works. It seems the 2nd mock fails.</p>

<pre><code>[Fact]
        public async void BlankUsernameReturnsError()
        {
            SetupMocks();

            var result = await _logic.AuthenticateAsync(new AuthenticationRequest
            {
                Password = ""AFantastic123Password@"",
                Username = """",
            });

            Assert.Equal(ResponseCode.LoginInvalidCredentials, result.ResponseState.ResponseCode);
        }
</code></pre>

<p>That works.
Maybe you can't have two 'setup' on the same mocked class? And I need to have a specific setup per test? Maybe the <code>private void Setup()</code> is a problem/bad idea?</p>
",https://stackoverflow.com/questions/60360633/moq-and-multiple-method-setup,"['c#', 'unit-testing', 'moq', 'xunit']",7817,True,1,1
vue-test-utils - how to handle $refs?,"<p><strong>THE SITUATION</strong></p>

<p>I am trying to <code>shallowMount</code> a component, unsuccessfully. </p>

<p>The component makes use of <code>$refs</code> to read the height of a <code>div</code>. That value is read inside a computed property. Then in the <code>mounted</code> lifecycle I save that value in the store.</p>

<p>The logic itself is simple and works fine. But <strong>in the test suite, the mounting of the component breaks, because the <code>$refs</code> key is <code>undefined</code>.</strong></p>

<p>To be clear: I don't intend to test the <code>$refs</code>, I just need to mount the component and move on doing actual unit-testing.</p>

<p><strong>THE COMPONENT</strong></p>

<p>This is the markup:</p>

<pre><code>&lt;div ref=""tgmp""&gt;
</code></pre>

<p>I save the height of the div in a computed property:</p>

<pre><code>computed: {
  barH() {
    return this.$refs.tgmp.clientHeight
  }
}
</code></pre>

<p>And then, in the mounted lifecycle, I commit the value in the store:</p>

<pre><code>this.$store.commit('setBarHeight', this.barH)
</code></pre>

<p><strong>THE TEST</strong></p>

<p>This is the test. I have omitted irrelevant stuff, like installing the store in the localVue.</p>

<pre><code>beforeEach(() =&gt; {
  wrapper = shallowMount(Bar, {
    store,
  })
})

test('is a Vue instance', () =&gt; {
  expect(wrapper.isVueInstance()).toBeTruthy()
})
</code></pre>

<p><strong>THE ERROR</strong></p>

<pre><code>Error in mounted hook: ""TypeError: Cannot read property 'clientHeight' of undefined""
</code></pre>

<p><a href=""https://i.stack.imgur.com/BcoPQ.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/BcoPQ.png"" alt=""TypeError: Cannot read property &#39;clientHeight&#39; of undefined""></a></p>

<p><strong>ATTEMPT</strong></p>

<p>I have been trying searching anywhere for a solution, but couldn't find it.
I have tried to mock the $refs, but without success:</p>

<pre><code>wrapper = shallowMount(ThePlayerBar, {
  store,
  mocks: {
    $refs: {
      tgmp: {
        clientHeight: 600
      }
    }
  }
})
</code></pre>

<p><strong>THE QUESTION</strong></p>

<p>How can I mount a component that makes us of <code>$refs</code> in the <code>mounted</code> lifecycle?</p>
",https://stackoverflow.com/questions/61223992/vue-test-utils-how-to-handle-refs,"['javascript', 'unit-testing', 'vue.js', 'jestjs', 'vue-test-utils']",16121,True,9,1
How to apply Continuous Integration for Google Pay,"<p>Background: we actually implemented a google subscription within our mobile-app, plus an API call to regularly check the status of payments as well for Real Time later on.</p>

<p>We have a server side cron-job that will analyze the subscription information and expires them in our database as not PREMIUM anymore if the info was changed. </p>

<p>Fyi: Basically we have a mobile and web app that has central database. This thing is a backend side concern.</p>

<p>In our code we have a mock data for unit testing only, as well we have a huge functional testing with payment modules we have. Our problem right now, there is no way to trigger a one-time/subscription purchase via API in Google Pay API, such endpoint does not exist based on their api docs.</p>

<p>How do you guys handle this kind of scenario, and we want this thing to be part of our CI/CD to avoid breaking changes in the future.</p>
",https://stackoverflow.com/questions/61400880/how-to-apply-continuous-integration-for-google-pay,"['continuous-integration', 'backend', 'google-play-developer-api', 'google-pay']",49,False,1,0
Comparing HashMap in JUnitTesting,"<p>I Have To: </p>

<ol>
<li>Write a function that accepts an array/list of strings, counts the occurrence of each string, and then returns a data structure with each unique string and the number of times it occurred. For example, given an input that contains:</li>
</ol>

<p>[“apple”, “bat”, “apple”, “car”]</p>

<p>the function should return a data structure that has a count of 2 for “apple”, 1 for “bat” and 1 for “car”.</p>

<ol start=""2"">
<li>Write the unit test coverage for my solution. Cover the permutations that ensure positive/negative functionality is correct. As well, cover meaningful edge cases to ensure both correct functionality and to ensure no errors with code execution.</li>
</ol>

<p>Now, i have done the task one, here is the code:</p>

<pre><code>package Testing;
import java.util.*;
class CountString{
public static void main(String []args){
    List strings = Arrays.asList(""appLe"",""b at"",""APPle"",""car!"");
    Map&lt;String,Integer&gt; datastructure = countStrings(strings);
    for (Map.Entry&lt;String, Integer&gt; entry : datastructure.entrySet()) {
        System.out.println(entry.getKey() + "" : "" + entry.getValue());
    }
}

public static Map&lt;String,Integer&gt;countStrings(List&lt;String&gt; words){
    Map&lt;String,Integer&gt; map = new HashMap&lt;&gt;();
    List&lt;String&gt;newList = new ArrayList&lt;&gt;();
    String regex = ""abcdefghijklmnopqrstuvwxyz"";
    regex+=regex.toUpperCase();
    String w;
    for(String s:words){
        w="""";
        for(int i=0;i&lt;s.length();i++){
            if(regex.contains(s.charAt(i)+"""")){
                w+=s.charAt(i)+"""";
            }
        }
        newList.add(w.toLowerCase());
    }
    String countedWords = """";
    int count;
    for(int i=0;i&lt;newList.size();i++){
        count=1;
        if(!countedWords.contains(newList.get(i))){
            for(int j=i+1;j&lt;newList.size();j++){
                if(newList.get(i).equals(newList.get(j))){
                    count++;
                }
            }
            countedWords+=newList.get(i)+"""";
            map.put(newList.get(i),count);
        }

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

<p>Now i have to design the unit testing of this but i am little confuse in comparing hashmap, kindly help me in that,</p>

<p>Here is a little try which i have done:</p>

<pre><code>package Testing;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;

class JUnitTest {

@Test
void test() {
    CountString test = new CountString();
    List strings = Arrays.asList(""appLe"",""b at"",""APPle"",""car!"");
    Map&lt;String,Integer&gt; output = test.countStrings(strings);

    for(Map.Entry&lt;String, Integer&gt; entry : output.entrySet()) {
        assertEquals(expecteds, output);


        }
    }
}
</code></pre>

<p>I cannot find out how assertEqual function works in Map.</p>
",https://stackoverflow.com/questions/59751570/comparing-hashmap-in-junittesting,"['java', 'unit-testing', 'hashmap', 'junit5']",1219,True,1,1
What is the use-case for a nested function pattern in Python?,"<p>While there is a lot of discussion around construction and use of nested functions, there is very little info on <em>when</em> to use them. What I'm trying to find out is: when is it idiomatic to use a nested function? When should you use <code>lambda x: &lt;function&gt;</code> over a nested function? </p>

<p>Python is a language that lets you do a lot of things you <em>shouldn't</em> (ie: using globals). Is this a feature that, while you can use it, you should not? </p>

<p>A scenario I envisioned for using one is in unit testing. Let's say you a method defined like this:</p>

<pre class=""lang-py prettyprint-override""><code>def FunctionOne(varone: int, vartwo: object) -&gt; None:
  assert varone == vartwo() 
</code></pre>

<p>vartwo is a function that is passed into the function. Now we want to unittest this. So we write a (partial) unit test that looks like this:</p>

<pre class=""lang-py prettyprint-override""><code>def unittest() -&gt; None:
  def test_function() -&gt; int:
    return 1
  FuncitonOne(1, test_function)
</code></pre>

<p>The specifics here are:</p>

<ol>
<li>The function is only needed in the scope of the unit test function.</li>
<li>The function is never called elsewhere.</li>
</ol>

<p>Therefore, to summarize: when should you (if ever) use a nested function with Python?</p>
",https://stackoverflow.com/questions/61666001/what-is-the-use-case-for-a-nested-function-pattern-in-python,"['python', 'lambda', 'inner-classes', 'pep8']",302,True,1,1
How do i mock the behavior of a void method when unit testing my delete service?,"<p>I'm currently unit testing the endpoints of a Spring Boot CRUD RESTful API and i have the following <strong>""Delete user by its id""</strong> endpoint that's composed of a <strong>controller</strong> and a <strong>service</strong> to implement its logic :</p>

<p>Delete controller (it's mainly calling the logic of the service and defining some guidelines) :</p>

<pre><code> @RestController
    @RequestMapping(""/users/{id}"")
    public class DeleteUserController {

        @Autowired
        DeleteUserService service;

        @DeleteMapping
        @ResponseStatus(HttpStatus.NO_CONTENT)
        public void deleteUser_whenDeleteUser(@PathVariable Long id) {
            service.deleteUser(id);
        }
    }
</code></pre>

<p>Delete service :</p>

<pre><code>@Service
public class DeleteUserService {

    @Autowired
    UserRepository repository;

    public void deleteUser(Long id) {

        repository.findById(id)
                .orElseThrow(() -&gt; new UserNotFoundException(id));

        repository.deleteById(id);
    }
}
</code></pre>

<p>While everything seems to be working fine until now, i'd be grateful if someone could tell me what i could improve in the code above. Anyways, My controllers unit test is the problem i can't seem to solve :</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(DeleteUserService.class)
public class DeleteUserControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private DeleteUserService deleteUserService;

    @Test
    public void removeUserById_whenDeleteMethod() throws Exception {
        User user = new User();
        user.setName(""Test Name"");
        user.setId(89L);

        doNothing().when(deleteUserService).deleteUser(user.getId());

        mvc.perform(delete(""/users/"" + user.getId().toString())
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isNoContent());
    }
</code></pre>

<p>I'm getting a <strong><em>java.lang.AssertionError: Status</em></strong> because while the code is expecting to get a <em>204 No content</em> response status, it's receiving a <em>404 Not found</em> which means it's throwing the exception that's supposed to throw when the user doesn't exist.</p>

<p>I think the answer is in the way i need to mock the behavior of my services logic, but i have no idea how. Would appreciate if someone could help me with this one.</p>
",https://stackoverflow.com/questions/62474281/how-do-i-mock-the-behavior-of-a-void-method-when-unit-testing-my-delete-service,"['java', 'spring', 'unit-testing', 'junit', 'mocking']",1005,True,1,1
Accessing class instance in XCTest using SwiftUI and @EnvironmentObject,"<p>I have a SwiftUI View hierarchy with an instance of a custom class injected using .environment() similar to the following:</p>

<pre><code>struct ContentView: View {

  // Pointer to the AppStateController passed in .environment()
  @EnvironmentObject var appStateController: AppStateController

  var body: some View {
    VStack(spacing: 0) {
      TitleView()
        .modifier(TitleStyle())
        .environmentObject(appStateController)
      Spacer()
    }
  }

}


struct TitleView: View {

  @EnvironmentObject var appStateController: AppStateController

  var body: some View {

    Button(action: {
      self.appStateController.isPlaying.toggle()
    }, label: {
      if self.appStateController.isPlaying {
        Image(systemName: ""stop.circle"")
          .opacity(self.appStateController.isPlayable ? 1.0 : 0.5)
          .accessibility(label: Text(""stop""))
      }
      else {
        Image(systemName: ""play.circle"")
          .opacity(self.appStateController.isPlayable ? 1.0 : 0.5)
          .accessibility(label: Text(""play""))
      }
    })
  }

}
</code></pre>

<p>On the TitleView there are a bunch of buttons whose actions change @Published values in the appStateController. The buttons also change their label (icon) when tapped.</p>

<p>I am just getting started with UI unit testing and I've got as far as testing a button tap changes the icon (by searching for the button and inspecting it's accessibility label) and that works fine, but I'd also like to assert that the action actually does something by checking the appStateController.isPlaying boolean - effectively testing that my action: {} closure does what I need it to.</p>

<p>I can't seem to locate any documentation that tells me how, given a running app, I can find a reference, through the view hierarchy, to the injected appStateController and inspect the attributes therein. Is this possible and if so, does anyone know where I can find some documentation/blog articles on doing this?</p>
",https://stackoverflow.com/questions/61286844/accessing-class-instance-in-xctest-using-swiftui-and-environmentobject,"['swift', 'swiftui', 'xctest', 'xctestcase']",560,False,1,1
Unit Testing with the material-ui/picker,"<p>I am utilizing the material-ui/picker in my application and would like to have full unit test coverage.  I am using both the KeyboardDatePicker and KeyboardTimePicker to give the users the option to type the date and time in if they do not like using the pickers.</p>

<p>Where should I be declaring a 'data-testid' in order to be able to either do a fireEvent.change or a userEvent.type (or something else if there is a different recommended way of triggering this type of event)?</p>

<p>I have tried adding the data-testid as part of the props on the pickers themselves, as part of the inputProps, and as part of the InputAdornmentProps but then when I try running either:</p>

<p><code>fireEvent.change(getByTestId('keyboardtimepicker-testid'), { target: { value: '12:00' } })</code></p>

<p>and</p>

<p><code>await userEvent.type(getByTestId('keyboardtimepicker-testid'), '12:00')</code></p>

<p>both throw an error.</p>

<p>If I put the data-testid in the KeyboardButtonProps, I don't see an error but the onChange function is not getting triggered.</p>

<p>How should I be unit testing with components from material-ui/picker?</p>
",https://stackoverflow.com/questions/60396075/unit-testing-with-the-material-ui-picker,"['unit-testing', 'testing', 'jestjs', 'material-ui']",2733,True,1,2
CppUTest override header file,"<p>I am learning unit testing. I can compile simply programs with Eclipse and CppUTEST. It works. Howover I have problem to understaned how to override/stub headers files. I came up with a test scenario,</p>

<p>My files:</p>

<pre><code>/src:
---------- src.c src.h //native compilator, for example stm-gcc
/test:
---------- AllTests.cpp Test_src.cpp //test compilator, for example gcc
/mocks:
---------- fsrc.h fsrc.c //fake file, should override src.h 
</code></pre>

<p>Theoretically, in file ""src.h"" are stored settings for native compiller (stm-gcc). My test compiler (gcc) cannot use these dependencies, so I should override/stub this header file. That is why I create /mocks/fsrc.h file. fsrc.h should override/stub src.h file.</p>

<p>Example files code:</p>

<p>AllTests:</p>

<pre><code>#include ""CppUTest/CommandLineTestRunner.h""
#include ""CppUTestExt/MockSupport.h""

#include &lt;src/src.h&gt; // -&gt; should read the ""fsrc"" file instead ""src""

int main(int ac, char** av) { return CommandLineTestRunner::RunAllTests(ac, av); }
</code></pre>

<p>Test_src.cpp</p>

<pre><code>#include ""CppUTest/TestHarness.h""
#include &lt;src.h&gt;

class ClassName { int a; };

TEST_GROUP(ClassName)
{
  ClassName* className;

  void setup() { className = new ClassName(); }
  void teardown() { delete className; }
};

TEST(ClassName, Create)
{
  CHECK(0 != className);
  STRCMP_EQUAL(myString, ""my_string_from_mock_header""); // --&gt; myString macro should be read from ""mocks/fsrc"" not from ""src/src.h""   
}
</code></pre>

<p>mocks/fsrc.h</p>

<pre><code>#ifndef SRC_SRC_H_
#define SRC_SRC_H_

#define myString ""mocks/Header""
int fun();

#endif /* SRC_SRC_H_ */
</code></pre>

<p>mocks/fsrc.c</p>

<pre><code>#include ""fsrc.h""    
int fun() { return 999; }
</code></pre>

<p>src/src.h</p>

<pre><code>#ifndef SRC_SRC_H_
#define SRC_SRC_H_

#define myString ""src/Header""
int fun();

#endif /* SRC_SRC_H_ */
</code></pre>

<p>src/src.c</p>

<pre><code>#include ""src.h""  
int fun() { return 1; }
</code></pre>

<p>Eclipse erorr:</p>

<p>'g++ -I""C:\cygwin64\home\karb\cpputest\include"" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF""AllTests.d"" -MT""AllTests.o"" -o ""AllTests.o"" ""../AllTests.cpp""
../AllTests.cpp:5:10: fatal error: src/src.h: No such file or directory'</p>

<p>When i change: </p>

<pre><code>include &lt;src/src.h&gt; to include ""src/src.h""
</code></pre>

<p>compilation works, but then overwriting header files does not work. What am I doing wrong that I can't overwrite the main header file?</p>
",https://stackoverflow.com/questions/62084288/cpputest-override-header-file,"['c++', 'c', 'unit-testing', 'cpputest']",527,False,1,0
Flask UnitTests accessing wrong URI,"<p>I have written some unit tests/integration tests for flask using python unittest. I am broadly using the example code written out here: <a href=""https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-unit-testing-legacy"" rel=""nofollow noreferrer"">https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-unit-testing-legacy</a></p>
<p>These tests used to run perfectly but now I have just tried to run them again and am running up against an error:</p>
<pre><code>sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, &quot;Can't connect to MySQL server on 'cloud-sql' ([Errno -2] Name or service not known)&quot;)
</code></pre>
<p>(Background on this error at: <a href=""http://sqlalche.me/e/e3q8"" rel=""nofollow noreferrer"">http://sqlalche.me/e/e3q8</a>)</p>
<p>Obviously this is telling me that it's trying to connect to cloud-sql and can't (this is the correct DNS name after deployment). However I have configured a different URI for testing.</p>
<p>This is what my test_web_api.py looks like:</p>
<pre><code>import os
import unittest
import json
from flask import url_for
from requests.auth import _basic_auth_str
from app import app, db
from app.models import User, UserToken, UserRoles, RolesList, BandwidthResults

TEST_DB = 'test.db'


class API_Tests(unittest.TestCase):

    ############################
    #### setup and teardown ####
    ############################
    test_admin_password = 'testpass'
    test_admin_user = 'admin'
    api_token = None
    # executed prior to each test

    def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False
        app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {}
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
            os.path.join(app.config['BASEDIR'], TEST_DB)
        app.config['SERVER_NAME'] = '127.0.0.1 localhost.dev'
        self.client = app.test_client(use_cookies=True)
        self.app_context = app.app_context()
        self.app_context.push()
        
        db.drop_all()
        db.create_all()

        # # Create admin user
        user = User(username=self.test_admin_user, email='test@example.com')
        user.set_password(self.test_admin_password)
        db.session.add(user)
        # Give admin user admin roles
        admin_role = RolesList(name='admin')
        db.session.add(admin_role)
        db.session.commit()
        user_role = UserRoles(role=RolesList.query.first().id,
                              user_id=User.query.filter_by(username=self.test_admin_user).first().id)
        db.session.add(user_role)
        # Generate an API token
        db.session.commit()
        response = self.client.get(url_for('api.token_token_api'), headers={
                                   &quot;Authorization&quot;: _basic_auth_str(self.test_admin_user, self.test_admin_password)},
                                   query_string={'expiry': 300})
        self.api_token = json.loads(response.data)['token']

    # executed after each test
    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()
        pass

###########################
#### tests-integration ####
###########################

    def test_01_api_token_get_auth(self):
        response = self.client.get(url_for('api.token_token_api'), headers={
                                   &quot;Authorization&quot;: _basic_auth_str(self.test_admin_user, self.test_admin_password)})
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(json.loads(response.data)['token'])

if __name__ == &quot;__main__&quot;:
    unittest.main()

</code></pre>
<p>This is what my <code>__init__.py</code> looks like for 'app'</p>
<pre><code>from flask import Flask

from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_socketio import SocketIO
from flask_marshmallow import Marshmallow
from flask_principal import Principal
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration

app = Flask(__name__)

from app.tasks.init import make_celery  # noqa: E402

app.config.from_object(Config)

sentry_sdk.init(
    dsn=&quot;&quot;,
    integrations=[FlaskIntegration()],
    environment=app.config['SENTRY_ENV'],
    release=app.config['SENTRY_RELEASE'],

)

db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
socketio = SocketIO(app, message_queue=app.config['CELERY_BROKER_URL'], async_mode='gevent', cors_allowed_origins=&quot;&quot;)
ma = Marshmallow(app)
celery = make_celery(app)
root_path = app.root_path
principal = Principal(app)

from app import routes, models  # noqa: E402,F401
from app.apis import blueprint as api  # noqa: E402

app.register_blueprint(api, url_prefix='/api/1')
</code></pre>
<p>I am at a loss to why. There have been no changes to the code base, everything runs in a docker image, with a pinned version, all the packages have pinned versions in requirements.txt. Grateful for any hints.</p>
",https://stackoverflow.com/questions/63937749/flask-unittests-accessing-wrong-uri,"['python', 'flask']",129,True,1,1
CUDA negative array index test,"<p>As it's possible in C to index a negative array location and go out of the array bounds this code compiles and ""works"".</p>

<pre><code>__global__ void do_something_bad(int * in_a){
   in_a[-1] = 666; // assign a value to an out of bounds memory location
}
</code></pre>

<p>My assumption is the above code is doing the following (please let me know if this assumption is wrong):</p>

<pre><code>GPU memory before:
[0x00 = usually unused memory][0x01= Start of in_a][0x02 = in_a] ....
GPU memory after:
[0x00 = 666][0x01= Start of in_a][0x02 = in_a] ....
</code></pre>

<p>In summary the memory before the the in_a array is being set the value. This memory before in_a could contain other important data but when I'm testing it containing nothing important and thus gives me no error or failing test.</p>

<p>FYI: I'm using pycuda and am unit testing my code as a go.</p>

<p>I'm trying to avoid creating silent unpredictable errors as a result of the above. Of course in the real world example -1 would have been calculated and I've simplified the code to just the problem I want to solve.</p>

<p>How do I identify this error and force a detectable problem that my unit tests can pick up?</p>
",https://stackoverflow.com/questions/61192664/cuda-negative-array-index-test,"['cuda', 'pycuda']",289,True,1,1
"In order to test a function with unit testing, does it need to have a return value?","<p>I am new to python and am trying to learn about unit testing. I am using pytest to run some unit tests on my code. Something very similar to this example:</p>

<pre><code>def test_calc_total():
    total = mathlib.calc_total(4,5)
    assert total == 9
</code></pre>

<p>I may be incorrect here, but I am learning that in order for your function be testable, it will have to return a value. Is this true for all unit tests?</p>

<p>I am finding that the majority of my functions are not able to be tested, since they don't have a return value. I am creating a ticket tracking system and storing the ticket information in a dataframe. Here is a portion of <em>TicketDF</em> class:</p>

<pre><code>class TicketDF():
    cwd = os.getcwd()
    df = pd.DataFrame()

    def __init__(self, configParser):
        self.populateFilePaths(configParser)
        self.populateAttributes(configParser)
        self.populateTable()

    def populateTable(self):
        if self.doesFileExistAndNotEmpty(self.ticketCSVFilePath):
            self.df = pd.read_csv(self.ticketCSVFilePath, converters={'Comments':literal_eval}) #, 'Attachments':literal_eval})
            self.df.set_index('Ticket ID', inplace=True)

    def populateAttributes(self, configParser):
        self.ticketAttributes =  configParser.getTicketAttributes()

    def populateFilePaths(self, configParser):
        self.ticketCSVFilePath = configParser.getTicketsCSVPath()

    def doesFileExistAndNotEmpty(self, filepath):
        if os.path.exists(filepath) and os.path.getsize(filepath) &gt; 0:
            return True
        else:
            return False

    def getTicketDF(self):
        return self.df

    def addTicketToDF(self, data):
        df = pd.DataFrame (data, columns = self.ticketAttributes)
        df.set_index('Ticket ID', inplace=True)
        self.df = self.df.append(df)
        self.saveDFToCSV()
</code></pre>

<p>As you can see, the majority of the functions, even the ones not shown, do not have return values. Is it best practice to write code so that all functions have a return value? Or is there another way to test functions without a return value?</p>
",https://stackoverflow.com/questions/62201897/in-order-to-test-a-function-with-unit-testing-does-it-need-to-have-a-return-val,"['python', 'unit-testing', 'pytest']",1094,True,1,2
Publishing Static Code Metric reports in Jenkins using declarative pipeline(Jenkinsfile),"<p>I am building a simple CI pipeline for my python code in Jenkins using Jenkinsfile, which basically does the following things:</p>

<blockquote>
  <ol>
  <li>Creating test environment and installing dependencies.</li>
  <li>Running static code metrics:
  
  <ul>
  <li>various raw metrics : SLOC, comment lines, blank lines, Cyclomatic Complexity, the Maintainability Index etc.</li>
  <li>tests coverage reports using coverage</li>
  <li>errors and style check using pylint</li>
  </ul></li>
  <li>Testing pulled source code (Unit testing)</li>
  </ol>
</blockquote>

<p>So lets say i have this stage for example, for ""Static code metrics"":</p>

<pre><code>...
        stage('Static code metrics') {
            steps {
                echo ""Raw metrics""
                sh  ''' radon raw --json my_python_repo/ &gt; raw_report.json
                        radon cc --json my_python_repo/ &gt; cc_report.json
                        radon mi --json my_python_repo/ &gt; mi_report.json
                        //TODO: add conversion and HTML publisher step
                    '''
            }
        }

...
</code></pre>

<p>As you see above, the reports are saved in .json format. <strong>I need to figure out a way to publish these reports in a pretty visual way on Jenkins dashboard.</strong>
One of the steps is to convert the .json files to HTML and then use HTML publisher plugin to publish reports but i don't know what tool to use.
If there is way to solve this or any other way to publish these reports on jenkins dashboard, please provide the solution.</p>

<blockquote>
  <p>Lets say content of <strong>mi_report.json</strong> is:</p>
</blockquote>

<pre><code> {""my_python_repo/code.py"": {""mi"": 16.42950884051172, ""rank"": ""B""}, ""my_python_repo/test.py"": {""mi"": 33.532817596089814, ""rank"": ""A""}}
</code></pre>
",https://stackoverflow.com/questions/60112570/publishing-static-code-metric-reports-in-jenkins-using-declarative-pipelinejenk,"['jenkins', 'continuous-integration', 'jenkins-pipeline', 'jenkins-plugins', 'devops']",665,True,1,1
How to unit-test for assert() failing?,"<p>I want to unit-test some code which uses <code>assert()</code> occasionally. Specifically, I want to make sure that certain commands do indeed trigger an assert. But - I don't actually want the program to be aborted. (If that happened I would need both to ensure program abortion from outside the program and have a different program for each such testcase.)</p>

<p>I also know that <code>assert()</code> is a macro, so if the code I'm testing is header-only, I could theoretically write some kind of replacement macro to trigger a failure using my unit-testing library (<a href=""https://github.com/onqtam/doctest/"" rel=""nofollow noreferrer"">doctest</a>).</p>

<p>My question:</p>

<ul>
<li>Perhaps doctest already has some facility for this kind of testing?</li>
<li>If not, is there some idiomatic way of implementing assert-firing-tests? Perhaps with other testing frameworks/libraries, which I could adapt?</li>
</ul>

<p>Note: I've noticed <a href=""https://stackoverflow.com/a/1116045/1593077"">here on SO</a> that Google Test has some kind of related facility, <a href=""https://github.com/google/googletest/blob/8b4817e3df3746a20502a84580f661ac448821be/googletest/docs/advanced.md"" rel=""nofollow noreferrer"">ASSERT_DEATH</a>, but it's not clear to me that it does what I want to do.</p>
",https://stackoverflow.com/questions/59794305/how-to-unit-test-for-assert-failing,"['c++', 'unit-testing', 'assert', 'idioms', 'doctest']",732,True,1,1
How to implement IHttpFactoryClient in examples of Typed HttpClient?,"<p>In every example I've seen, including the Microsoft ones <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#typed-clients"" rel=""nofollow noreferrer"">here</a> and <a href=""https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests"" rel=""nofollow noreferrer"">here</a>, the author's explain the improvements made by <code>IHttpClientFactory</code> over <code>HttpClient</code> and give examples of how to use it simply out-of-the-box or in Named form. But then they all seem to mention that utilizing the Typed form really is best for its structure, usability, and more. The reasons make sense for our use case.</p>
<p>Though like the links provided above, there isn't a single line of code instantiating, injecting, or using <code>IHttpClientFactory</code> in the involvement of creating a Typed <code>HttpClient</code> (or Service as a Client). You create the Typed Client:</p>
<pre><code>public class GitHubService
{
    public HttpClient Client { get; }

    public GitHubService(HttpClient client)
    {
</code></pre>
<p>and then you consume it in some model or controller:</p>
<pre><code>public TypedClientModel(GitHubService gitHubService)
{
    _gitHubService = gitHubService;
}

public async Task OnGet()
{
    try
    {
        LatestIssues = await _gitHubService.GetAspNetDocsIssues();
    }
</code></pre>
<p>I'm extremely confused. My team was originally hitting roadblocks trying to mock (with Moq) Typed clients for unit testing, and the conclusion that we came to after many great resources was that mocking was exponentially easier with <code>IHttpClientFactory</code>. But I haven't found a single example that explicitly uses <code>IHttpClientFactory</code> with Typed clients.</p>
",https://stackoverflow.com/questions/64761646/how-to-implement-ihttpfactoryclient-in-examples-of-typed-httpclient,"['c#', '.net', 'rest', 'httpclient', 'httpclientfactory']",1129,True,1,2
"Django unit tests - API calls slowing down testing greatly, optimize or rewrite?","<p>I have an application that calls to OpenWeatherMap API and I decided to write a test for the purpose of verifying that the cities are listed on the url page context.</p>
<p>I used the setUpTestData class method to populate the test DB, but when I run the tests the time taken goes from 0.0XX seconds without the test DB to like 5.7XX seconds with the test DB.</p>
<p>I believe its the API calls to populate the DB that is causing the slow down (Which I assume also counts against my limit for calls per hour on the API key) and I am wondering what the proper way would be to test something like this? I.E something that relies on API data to work properly.</p>
<p>Do I need to optimize my code, or is my approach wrong? I am relatively new to unit testing, so I appreciate any tips or advice you may have.</p>
<p>views.py</p>
<pre><code>class WeatherHomeView(TemplateView):
    template_name='weather/home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        url = 'API URL'
        cities = City.objects.all()

        weather_data = []

        for city in cities:
            city_weather = requests.get(url.format(city)).json()

            weather = {
                'city' : city,
                'temperature' : city_weather['main']['temp'],
                'description' : city_weather['weather'][0]['description'],
                'icon' : city_weather['weather'][0]['icon'],
            }

            weather_data.append(weather)

        context = {'weather_data' : weather_data}

        return context
</code></pre>
<p>test_views.py</p>
<pre><code>class WeatherViewTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        City.objects.create(
            name='denver'
        )
        City.objects.create(
            name='honolulu'
        )
        City.objects.create(
            name='tokyo'
        )
...
    
    def test_home_shows_all_cities(self):
        '''Tests to verify all cities in the DB (3) are listed in the home view.'''
        cities = City.objects.all()
        response = self.client.get(reverse('weather:weather-home'))
        self.assertTrue(len(response.context['weather_data']) == 3)
</code></pre>
",https://stackoverflow.com/questions/64130307/django-unit-tests-api-calls-slowing-down-testing-greatly-optimize-or-rewrite,"['django', 'api', 'unit-testing']",217,False,1,1
First test per class is running far slower than every other test,"<p>I am using VS 2019 with a unit testing project. I have about 80 tests in total, split across several test classes.
I have noticed that when a class has several methods, that the first test takes 30ms or so to run and the others are 1ms or so. These are very cheap tests, hitting no database. And this is very consistent - of my 10 or so test classes, they all exhibit one test method taking substantially longer than others to run.</p>

<p>I've reproduced this with an extremely basic test:</p>

<pre><code>Imports Xunit

Public Class TestTestsCopy

    Property x As Integer

    Public Sub New()
        x += 1
    End Sub

    &lt;Fact()&gt;
    Public Sub TestOne()       
        x += 1

        Assert.Equal(2, x)
    End Sub

    &lt;Fact()&gt;
    Public Sub TestTwo()       
        x += 2

        Assert.Equal(3, x)
    End Sub

    &lt;Fact()&gt;
    Public Sub TestThree()   
        x += 3

        Assert.Equal(4, x)
    End Sub

    &lt;Fact()&gt;
    Public Sub TestFour()     
        x += 4

        Assert.Equal(5, x)
    End Sub
End Class
</code></pre>

<p>I also copy/pasted this test and renamed the class - both test classes show the first method taking 33-36ms, and every other test is 1ms.</p>

<p>I know that these timings aren't crazy long but it just looks really odd.</p>

<p>To rule out anything about my projects, I created a brand new 'console app' project with only references to xunit/xunit VS runner, and copied the same test classes as above - exact same behaviour.</p>

<p><a href=""https://i.stack.imgur.com/uYy85.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/uYy85.png"" alt=""VS &#39;test explorer&#39; showing test timings""></a></p>
",https://stackoverflow.com/questions/60283170/first-test-per-class-is-running-far-slower-than-every-other-test,"['.net', 'visual-studio', 'xunit', 'xunit.net']",129,False,1,0
Problem saving downloaded file on ASP.Net Core via download button on UI,"<p>Any help with this would be much appreciated. I've got a datagrid and a download button on my UI. When the user selects a row in the grid and clicks download, it should pass the int id as parameter to my Download method on my controller, which processes the download. </p>

<p>I have used Ajax/JQuery for this, which I am quite new to. From debugging it appears that it is sending two GET requests, one with my correct ID and one without, which is causing an empty file to be saved in the download. If i type the full URL with ID on the browser it downloads correctly, and my download method also works in my Unit testing, so I'm doing something wrong in the Ajax/JQuery I think. </p>

<p>Please see relevant code below:  </p>

<p>//html </p>

<pre><code>            &lt;form asp-controller=""Home"" asp-action=""Download"" method=""get""&gt;
                &lt;div id=""downloadButton""&gt;&lt;/div&gt;
            &lt;/form&gt;
</code></pre>

<p>//JQuery datagrid on my view, which calls the getLoadId method when user selects data row: </p>

<pre><code>    $(""#gridContainer2"").dxDataGrid({
        dataSource: DevExpress.data.AspNet.createStore({
            loadUrl: url + ""/GetLoadHistory"",
            key: ""loadId""

        }),
        selection: {
            mode: ""single""
        },
        hoverStateEnabled: true,
        paging: {
            pageSize: 10
        },

        editing: {
            mode: 'row',

        },
        onSelectionChanged: getLoadId
    });
</code></pre>

<p>//JQuery functions with Ajax which passes selected loadId to controller: </p>

<pre><code>function getLoadId() {
    var dataGrid = $(""#gridContainer2"").dxDataGrid(""instance"");
    var loadIds = dataGrid.getSelectedRowKeys();
    var loadId = loadIds[0];

    if (loadId &gt; 0)
    {
        console.log(""Load ID: "" + loadId);
        download(loadId);

    }
}

function download(loadId) {
    $(""#downloadButton"").dxButton({
        text: ""Download Selected"",
        type: ""default"",
        icon: ""/favicon.ico"",
        contentType: ""application/json; charset=utf-8"",
        dataType: ""json"",
        useSubmitBehavior: true,
        onClick: function(e) {
            $.ajax({
                url: 'https://localhost:44346/home/Download/',
                type: 'GET',
                data: {
                    loadId: loadId
                }
            }).done(function() {
                DevExpress.ui.notify(""Downloading results for Load ID: "" + loadId, ""info"", 1500);
            });
        }
    });

    console.log(""Load ID: "" + loadId + "" download processed"");

};
</code></pre>

<p>//download methods on home controller: </p>

<pre><code>    [HttpGet]
    public async Task&lt;IActionResult&gt; Download(int loadId)
    {

        Console.WriteLine(""Attempting to download Load ID: "" + loadId + "" from UI"");

        var outputFolder = Directory.GetCurrentDirectory() + ""\\wwwroot\\output\\"";
        var name = GetFileName(loadId, outputFolder);
        var path = Path.Combine(outputFolder, name);

        var memory = new MemoryStream();

        try
        {
            using (var stream = new FileStream(path, FileMode.Open))
            { 
                await stream.CopyToAsync(memory);
            }

            memory.Position = 0;
        }

        catch (Exception e)
        {
            Log.Error($""Unable to copy load {loadId} to memory for download: "" + e);
        }

        Log.Info($""Results for file load: "" + loadId + "" download triggered successfully"");

        return File(memory, ""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"", ""Downloaded.xlsx"");
    }


    public string GetFileName(int loadId, string outputFolder)
    {

        Log.Info($""Locating results for load {loadId} on web server"");

        var resultsName = @""Results_Load_"" + loadId + ""_*"";
        var results = """";
        var d = new DirectoryInfo(outputFolder);

        try
        {
            foreach (var file in d.GetFiles(resultsName))
            {
                Log.Info($""Results for load {loadId} located for download"");
                results = file.Name;
            }
        }

        catch (Exception e)
        {
            Log.Error($""Results for load {loadId} not found on server: "" + e);
            return null; 
        }

        return results; 

    }
</code></pre>
",https://stackoverflow.com/questions/61075863/problem-saving-downloaded-file-on-asp-net-core-via-download-button-on-ui,"['c#', 'jquery', '.net', 'ajax', 'asp.net-core']",246,False,0,0
How do I validate that a Pandas method has been called?,"<p>I am trying to use unit testing to confirm that I have called a Pandas method. I have one simple line of code in a Jupyter notebook code cell, and I would like to test it and validate that it has been executed. I can do this visually of course, but I want to do it automatically using code. I have played with variations of <strong>mock</strong>, <strong>patch</strong> and <strong>assert</strong>, but I can't seem to get it to work. The name of my DataFrame is ""cars"". The code works well and I'm getting what I expect, I just need a way to validate that the method call was executed, <em>and</em> I'd like to verify that it was called with the DataFrame called ""cars"".</p>

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

<p><strong>cars.info()</strong></p>

<p>Is there a simple way to validate that (1) this method was called and (2) that it used the ""cars"" DataFrame? I appreciate any help, thanks!</p>
",https://stackoverflow.com/questions/61916853/how-do-i-validate-that-a-pandas-method-has-been-called,"['python', 'pandas', 'unit-testing', 'dataframe', 'mocking']",49,False,0,0
ASP.NET (Core)&#39;s zombie virus of &#39;public&#39;: can controllers be internal?,"<p>The context is ASP.NET Core.</p>
<p>Please consider the following minimal setup.</p>
<pre><code>public class ExampleController : ControllerBase
{
   public ExampleController(IExempleService exampleService)
   {

(...)

public interface IExampleService
{
   ExampleStruct Foo();
}

public readonly struct ExampleStruct (...)
</code></pre>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped&lt;IInverterService, InverterService&gt;();
</code></pre>
<p>There is a chain of publicity here.</p>
<ol>
<li>The controller must be public; to be discoverable. <em>Fair.</em></li>
<li>The controller's constructor must be public; for the framework to instantiate it. <em>That's life.</em></li>
<li>The service interface must be public because the controller's constructor is public. <em>Sadness.</em></li>
<li>The service types (e.g. ExampleStruct) must be <code>public</code> because the interface is public. <em>I feel sick.</em></li>
</ol>
<p>There are practical consequences of this:</p>
<ul>
<li>Documentation, I'm documenting practically internal but technically public classes with senseless comments that will become outdated.</li>
<li>Public types have more responsibilities. For example, an internal struct needs not to provide equality, but when it's public it should.</li>
</ul>
<p>I suppose there are two questions here:</p>
<ul>
<li>Would there eventually be a structural solution for this zombie virus of public access?</li>
<li>Am I doing it wrong and there is an OK solution now?</li>
</ul>
<hr />
<p>Unit testing and <code>internal</code> go together with <a href=""https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute?view=net-5.0"" rel=""nofollow noreferrer"">InternalsVisibleToAttribute </a>.</p>
",https://stackoverflow.com/questions/64165215/asp-net-cores-zombie-virus-of-public-can-controllers-be-internal,"['c#', '.net', 'asp.net-core', 'dependency-injection', 'scope']",364,True,0,2
Sequential function names using preprocessor,"<p>I'm writing a simple unit-testing library in C to run some tests on code, and am curious if it is possible to make the process more efficient using macros/the preprocessor. Yes, I realize that I probably shouldn't be writing my own, but I would still like to know if this is possible.</p>
<p>Here's how I currently do it:</p>
<pre class=""lang-c prettyprint-override""><code>#include &lt;stdio.h&gt;

/* Each test exits with status 1 if fail */
void test_00() { ... }     
void test_01() { ... }
...
void test_09() { ... }

#define NUM_TESTS 10
void (*TESTS[NUM_TESTS])() = {test_00, test_01, ..., test_09};

/* Only want to run the test number passed in on the command line */
int main(int argc, char *argv) {
  int test_num = atoi(argv[1]);    // Error checking in actual code
  TESTS[test_num]();
}
</code></pre>
<p>In particular, I am interested in getting rid of the <code>TESTS</code> array where I have to manually add in every new test that is made. Ideally, have it be automatically generated using <code>NUM_TESTS</code> since it's honestly always repetitive.</p>
<p>It doesn't have to be particularly general, I won't have more than 100 tests cases so 2 digits for the test number is fine, and all the tests are named in exactly the same way.</p>
<hr />
<p>Sorry if this question doesn't follow some guidelines. I have no reasonable attempt to show, and am at a loss for what exactly to even look for.</p>
",https://stackoverflow.com/questions/63113764/sequential-function-names-using-preprocessor,"['c', 'c-preprocessor']",68,True,0,2
Writing proper unit tests,"<p>I am brand new to creating unit tests, and attempting to create tests for a project I did not create.  The app I'm working with uses python/flask as a web container and loads various data stored from js files into the UI. I'm using pytest to run my tests, and I've created a few very simple tests so far, but I'm not sure if what I'm doing is even relevant.</p>
<p>Basically I've created something extremely simple to check if the needed files are available for the app to run properly.  I have some functions put together that look for critical files, below are 2 examples:</p>
<pre><code>import pytest
import requests as req

def test_check_jsitems
    url = 'https://private_app_url/DB-exports_check_file.js'
    r = req.get(url)
    print(r.status_code)
    assert r.status_code == req.codes.ok    

def test_analysis_html
    url = 'https://private_app_url/example_page.html'
    r = req.get(url)
    print(r.status_code)
    assert r.status_code == req.codes.ok
</code></pre>
<p>My tests do work - if I remove one of the files and the page doesn't load properly - my basic tests will  show what file is missing.  Does it matter that the app must be running for the tests to execute properly?  This is my first attempt at unit testing, so kindly cut me some slack</p>
",https://stackoverflow.com/questions/62778415/writing-proper-unit-tests,"['javascript', 'python', 'unit-testing', 'flask']",52,True,0,1
jest/enzyme test failing although feature working,"<p>i'm learning unit testing for react with jest and enzyme. for the purpose of practice i built a simple to-do app and wrote tests for the different components.
the app and all it's features are working as intended without any bugs, but two out of seven of my tests for my app component (stateful) are failing. the two tests are for calling component methods.</p>

<p>here is the app component:</p>

<pre><code>import React from 'react';
import InputField from '../components/InputField';
import Display from '../components/Display';
import ControlPanel from '../components/ControlPanel';

class App extends React.Component {
   constructor() {
      super()

      this.state = {
         newTask: '',
         allTasks: [],
         showAll: true,
      }
   }


   clearDisplay = () =&gt; {
      this.setState({
         newTask: '', 
         allTasks: [], 
         showAll: true,
      })
   }

   handleInputChange = (e) =&gt; {
      this.setState({newTask: e.target.value})
   }

   addTask = () =&gt; {
      if(this.state.newTask){
         let newTasksArray = [...this.state.allTasks, {text: this.state.newTask, status: true}];
         this.setState({
            allTasks: newTasksArray, 
            newTask: ''
         })
      }
   }

   toggleShow = (boolean) =&gt; {
      this.setState({showAll: boolean})
   }

   toggleTaskStatus = (index) =&gt; {
      let newTasksArray = [...this.state.allTasks];
      let changedTask = {...this.state.allTasks[index]};
      changedTask.status === true ?
         changedTask.status = false
         :
         changedTask.status = true;
      newTasksArray[index] = changedTask;

      this.setState({allTasks: newTasksArray})
   }

   deleteTask = (index) =&gt; {
      let newTasksArray = [...this.state.allTasks];
      newTasksArray.splice(index, 1);
      this.setState({allTasks: newTasksArray})
   }

   render() {
      return (
         &lt;div className='bg-gray-800 text-white min-h-screen'&gt;
            &lt;div className='mx-auto w-1/3'&gt;
               &lt;h1 className='uppercase text-2xl block font-bold py-6 text-gray-400 tracking-widest text-center'&gt;
                  Todo List
               &lt;/h1&gt;
               &lt;InputField 
                  addTask={this.addTask} 
                  handleInputChange={this.handleInputChange}
                  inputValue={this.state.newTask}
               /&gt;
               &lt;Display 
                  toggleTaskStatus={this.toggleTaskStatus} 
                  showAll={this.state.showAll} 
                  tasks={this.state.allTasks}
                  deleteTask={this.deleteTask}
               /&gt;
               &lt;ControlPanel clearDisplay={this.clearDisplay} showAll={this.state.showAll} toggleShow={this.toggleShow}/&gt;
            &lt;/div&gt;
         &lt;/div&gt;
      );   
   }
}

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

<p>the tests (for the sake of readability i removed all the passing tests):</p>

<pre><code>import { shallow } from ""enzyme"";
import React from ""react"";
import App from ""../containers/App.js"";

describe('App component', () =&gt; {

    it('addTask', () =&gt; {
        const mockState = {
            newTask: 'test',
            allTasks: [],
            showAll: true
        }

        const wrapper = shallow(&lt;App {...mockState} /&gt;)
        const instance = wrapper.instance()

        instance.addTask()

        expect(wrapper.state().allTasks).toEqual([{status: true, text: 'test'}])
    })

    it('toggleTaskStatus', () =&gt; {
        const mockState = {
            newTask: '',
            allTasks: [{status:true, text:'test'}],
            showAll: true
        }

        const wrapper = shallow(&lt;App {...mockState}/&gt;)
        const instance = wrapper.instance()

        instance.toggleTaskStatus(0);
        expect(wrapper.state().allTasks[0].status).toBe(false)
    })

})
</code></pre>

<p>i assumed the issue comes from enzyme's abilty to deep compare, so i tried to write the expect logic in different ways, at first comparing the expected and recieved tests and later the arrays/objects themselves within the state, but so far with no success.</p>

<p>my question is how can (or should) i write the tests in order for them to pass and what am i doing wrong/missing here?</p>
",https://stackoverflow.com/questions/61752396/jest-enzyme-test-failing-although-feature-working,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",115,False,0,0
Not able to read the values from ‘App.config’ file in the Unit testing project (Nunit),"<p>I have created one ‘nunit’ project in a visual studio which contains a simple one test. There is no default ‘App.config’ file available, so I have created one ‘App.config’ file. I have marked this file ‘Copy always’ from its ‘properties’ option.</p>
<p>I have tried to read the values from 'config' file is two ways 'ConfigurationManager.AppSettings' and 'system.configuration.configurationmanager.AppSettings'. but, It is showing empty values (null values)</p>
<p>Please see my code.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Text;
using log4net;
using NUnit.Framework;
using NUnitTestProject1.Config;
using NUnitTestProject1.Helper;

namespace NUnitTestProject1.AutomationTest
{
   [TestFixture, Order(3)]
    public class ReadDataThoughExcel
    {

        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

       [Test, Order(1)]
        public void IsUserReadDataThroughExcel() {

    string data1 = ConfigurationManager.AppSettings[&quot;name&quot;];
    Console.Write(&quot;Print data &quot;+data1);
    string data2 = system.configuration.configurationmanager.AppSettings[&quot;name&quot;];
    Console.Write(&quot;Print data &quot;+data2);
  }
 }
}

like so
</code></pre>
<p>Config file code is below:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;configuration&gt;
    &lt;ApplicationSettings&gt;
        &lt;add key=&quot;name&quot; value=&quot;Configuration Example Project&quot;/&gt;
    &lt;/ApplicationSettings&gt;
&lt;/configuration&gt;

like so
</code></pre>
<p><strong>Configuration details of my project:</strong></p>
<ol>
<li><strong>Dot.Net Framework:</strong> Microsoft.NET Framework version 4.7.0</li>
<li><strong>OS:</strong> window 10</li>
<li><strong>IDE:</strong> Visual studio 2019</li>
<li>Use <strong>Nunit framework</strong> for unit testing</li>
<li><strong>NUnit3TestAdapter</strong> (Version) 3.17.0</li>
<li><strong>Microsoft.NET.Test.Sdk</strong> (Version) 16.5.0</li>
<li><strong>System.Configuration.ConfigurationManager</strong> (Version) 4.7.0</li>
<li><strong>Selenium.Support</strong> (Version) 3.141.0</li>
</ol>
<p><strong>Note:</strong> Also, I have tried to add the reference of the ‘system.configuration’ to my project by right clicking on the 'Dependency' option (showing inside the project name in visual studio), however I am not able to see the option ‘system.configuration’ in the 'Type Libraries' option.</p>
",https://stackoverflow.com/questions/64609415/not-able-to-read-the-values-from-app-config-file-in-the-unit-testing-project,"['c#', 'selenium', 'frameworks', 'dependencies', 'nunit']",1938,True,0,1
Using Jenkins with Eclipse and C - Lack of Examples,"<p>I'm trying to use Jenkins as a CI/CB system (unit testing included) using headless Eclipse/TrueStudio for embedded C. There doesn't seem to be many examples for this, and even the Jenkins site itself doesn't have an example Jenkins file. I've used a CI like CircleCI before, but that was a terrible experience as they were transitioning from CircleCI 1.0 to 2.0 and the specific setup i was using was largely devoid of material. I spent over 100 commits linking Android Studio, Git, and Firebase together. Anyone have a C/C++ based example Jenkinsfile I can look at?</p>

<p>So far I've got this as a <code>Jenkinsfile</code>:</p>

<pre><code>pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                echo 'Building..'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing..'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
            }
        }
    }
}
</code></pre>

<p>I'm using one machine for this as the project is small in size. The code is stored in a git repo on the same machine. We're using TrueStudio which is modified Eclipse, and has a headless mode bat file. 
One example from comments in bat file:</p>

<pre><code>Example usage: 
REM   1. Performs a rebuild on build configuration ""config"" for project ""proj"" in workspace ""MyWorkspace"".
REM      Command: headless.bat -data C:\MyWorkspace -build proj/config
</code></pre>

<p>I'm currently working on syncing up the git repo and Jenkins. </p>
",https://stackoverflow.com/questions/61005041/using-jenkins-with-eclipse-and-c-lack-of-examples,"['c', 'git', 'jenkins', 'truestudio']",123,False,0,0
RxJS TestScheduler accumulating frames,"<p>I'm unit testing rxjs with jest and I have come to a situation where two different tests inside their own <code>testScheduler.run</code> seem to share their total count of frames (unless something else is happening).</p>

<p>Here's my test:</p>

<pre><code>import { map } from ""rxjs/operators"";
import { TestScheduler } from ""rxjs/testing"";
import { timer, race } from ""rxjs"";

const testScheduler = new TestScheduler((actual, expected) =&gt; {
  expect(actual).toEqual(expected);
});

describe(""Testing race conditions"", () =&gt; {
  it(""obs1 should complete first"", () =&gt; {
    testScheduler.run(helpers =&gt; {
      const { cold, expectObservable } = helpers;
      const obs1$ = cold(""--a"");
      const obs2$ = timer(5000).pipe(map(x =&gt; x.toString()));
      const output$ = race(obs1$, obs2$);
      const expected = ""--a"";
      expectObservable(output$).toBe(expected);
    });
  });
  it(""obs2 should complete first"", () =&gt; {
    testScheduler.run(helpers =&gt; {
      const { cold, expectObservable } = helpers;
      const obs1$ = cold(""5m --a"");
      const obs2$ = timer(5000).pipe(map(x =&gt; x.toString()));
      const output$ = race(obs1$, obs2$);
      const expected = ""5s (0|)"";
      expectObservable(output$).toBe(expected);
    });
  });
});
</code></pre>

<p>And this are the results:</p>

<p><a href=""https://i.stack.imgur.com/DcZhn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/DcZhn.png"" alt=""Results original order of tests""></a></p>

<p>If I remove the first test, the second one passes and if I invert them, the second one passes and the first fails with these results:</p>

<p><a href=""https://i.stack.imgur.com/ZCklg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZCklg.png"" alt=""Results of inverted order of test""></a></p>

<p>Notice how in the first case, the 2 frames from the first successful test are added to the 5 seconds that elapse in the second, making 5002 and failing due to those 2 additional frames. In the second case, the 5 seconds are accumalted for a total of 5002 again, in contrast with 2 that are expected. </p>

<p>I finally solved it by making local <code>testScheduler</code> declarations inside the <code>it</code> function, which seems odd too me because in the <a href=""https://rxjs-dev.firebaseapp.com/guide/testing/marble-testing"" rel=""nofollow noreferrer"">docs</a> it's declared outside, like this:</p>

<pre><code>import { TestScheduler } from 'rxjs/testing';

const testScheduler = new TestScheduler((actual, expected) =&gt; {
  // asserting the two objects are equal
  // e.g. using chai.
  expect(actual).deep.equal(expected);
});

// This test will actually run *synchronously*
it('generate the stream correctly', () =&gt; {
  testScheduler.run(helpers =&gt; {
    const { cold, expectObservable, expectSubscriptions } = helpers;
    const e1 =  cold('-a--b--c---|');
    const subs =     '^----------!';
    const expected = '-a-----c---|';

    expectObservable(e1.pipe(throttleTime(3, testScheduler))).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(subs);
  });
});
</code></pre>

<p>So I wanted to know, is this behaviour normal or intentional? Or am I missing something?</p>
",https://stackoverflow.com/questions/61691199/rxjs-testscheduler-accumulating-frames,"['javascript', 'rxjs']",465,False,0,0
Mock dutchcoders/goftp for unit testing,"<p>I'm using <a href=""https://github.com/dutchcoders/goftp"" rel=""nofollow noreferrer"">dutchcoders/goftp</a> in my code, and for unit testing purpose, I need to mock it.</p>

<p>Thing is this component doesn't have interface, nor avaible mocks, so I tried to create some:</p>

<p>in <code>goftp/ftp.go</code>, </p>

<p>I added interface:</p>

<pre><code>type FTPIface interface {
    Close() error
    Walk(path string, walkFn WalkFunc) (err error)
    Rename(from string, to string) (err error)
    Login(username string, password string) (err error)
}
</code></pre>

<p>Now I can mock all the methods I use but <code>Connect()</code>, because connect has no receiver.</p>

<p>You use like like that:</p>

<pre><code>if client, err = goftp.Connect(Host); err != nil {
        return nil, err
    }
</code></pre>

<p>So I tried to change it to be able to mock it:</p>

<pre><code>func NewMyFTP(ftpIface goftp.FTPIface, host, user, password, name string) (*MyFTP, error) 
{ 
    if Client, err = ftpIface.Connect(Host); err != nil {
        return nil, err
    }
    if err = Client.Login(user, password); err != nil {
        return nil, err
    }
}
</code></pre>

<p>and added <code>Connect()</code> to interface definition</p>

<pre><code>Connect(addr string) (*FTP, error)
</code></pre>

<p>Thing is I can mock connect, but it will return a FTP object, and I will not be able to mock <code>Login()</code></p>

<p>So, what should I do ?</p>

<ol>
<li>Change go client ? I wouldn't like to do that, as I have implemented it in all my code.</li>
<li>Implement a dev ftp server: Can be a good and simple idea, but I will mix Unit test and functional test, keeping an external dependency.</li>
<li>Finding a technical solution to my problem and mock it ?</li>
</ol>
",https://stackoverflow.com/questions/61059717/mock-dutchcoders-goftp-for-unit-testing,"['unit-testing', 'go', 'ftp', 'mocking']",346,False,0,0
kotlin in intellij unresolved reference testng or junit when adding unit tests,"<p>I am trying to add unit testing to my project. What I did:</p>
<ul>
<li>Created a function that returns what it is given.</li>
<li>Right clicked → Generate … → Test …</li>
<li>Selected TestNG (I tried after with Junit5, and got same result).</li>
<li>Selected functions to test</li>
<li>TestNG Library not found in the module: click fix, selected first one (org.testng.testng:6.14.3), clicked OK</li>
<li>Clicked OK</li>
</ul>
<p>Test code was generated, but there is error message: <code>Unresolved reference: testng</code>. There is a similar message for JUnit5. In source code the (first) error is in <code>import org.testng.Assert</code> on the word <code>testng</code>.</p>
<p>The project window now shows External Libraries → testng → testng-6.14.3.jar → org.testng → Assert (there are other branches).</p>
<h1>A hack that worked</h1>
<ul>
<li>File → Project structure → Libraries</li>
<li><code>+</code> → Java</li>
<li><code>/usr/share/java/testng.jar</code></li>
<li>Do you really want to replace old library 'testng'? : click yes</li>
</ul>
<p>What is happening?: Why is library not found?</p>
<hr />
<ul>
<li>IntelliJ Idea community addition 2020.2 from snap on Debian Gnu/Linux.</li>
<li>I am new to kotlin, did some Java in the 1990, and experienced in other languages.</li>
</ul>
",https://stackoverflow.com/questions/63400668/kotlin-in-intellij-unresolved-reference-testng-or-junit-when-adding-unit-tests,"['kotlin', 'intellij-idea']",467,False,0,0
what is the pythonic way to test dataframe processing pipelines,"<p>What is the best way to go about testing a pandas dataframe processing chain?  I stubbed out the script file and the test file below so you can see what I mean.</p>
<p>I am getting confused on best practice, my only guiding intuition is to make the tests so they can run in any order, limit how many times the csv is loaded from disk, while also making sure each point in the chain does not modify the fixture.  Each step in the process is dependent on the previous steps so unit testing each node is like testing the accumulation of processing to that point in the pipeline.  So far I am accomplishing the mission but it seems like a lot of code duplication is happening because I am incrementally building the pipeline in each test.</p>
<p>What is the way to test this kind of python script?</p>
<p>This is the data processing file stubbed out:</p>
<pre class=""lang-py prettyprint-override""><code>#main_script.py

def calc_allocation_methodology(df_row):
    print('calculating allocation methodoloyg')
    return 'simple'

def flag_data_for_the_allocation_methodology(df):       
    allocation_methodology = df.apply(calc_allocation_methodology, axis=1)
    df.assign(allocation_methodology=allocation_methodology)
    print('flagging each row for the allocation methodoloyg')
    return df

def convert_repeating_values_to_nan(df):
    'keep one value and nan the rest of the values'
    print('convert repeating values to nan')
    return df

def melt_and_drop_accounting_columns(df):
    print('melt and drop accounting columns')
    print(f'colums remaining: {df.shape[0]}')
    return df
    
def melt_and_drop_engineering_columns(df):
    print('melt and drop engineering columns')
    print(f'colums remaining: {df.shape[0]}')
    return df
    
    
def process_csv_to_tiny_format(df):
    print('process the entire pipeline')
    return (df
        .pipe(flag_data_for_the_allocation_methodology)
        .pipe(convert_repeating_values_to_nan)
        .pipe(melt_and_drop_accounting_columns)
        .pipe(melt_and_drop_engineering_columns)
        )
</code></pre>
<p>This is the test file stubbed out</p>
<pre class=""lang-py prettyprint-override""><code>

#test_main.py


from pytest import fixture
import main_script as main
import pandas as pd

@fixture(scope='session')
def df_from_csv()
    return pd.load_csv('database_dump.csv')

@fixture
def df_copy(df_from_csv):
    df = df_from_csv.copy()
    return df

    
    
def test_expected_flag_data_for_the_allocation_methodology(df_copy)
    df = df_copy
    node_to_test = df.pipe(main.flag_data_for_the_allocation_methodology)
    assert True

def test_convert_repeating_values_to_nan(df_copy)
    df = df_copy
    node_to_test = df.pipe(main.flag_data_for_the_allocation_methodology).pipe(main.convert_repeating_values_to_nan)
    assert True     
        
def test_melt_and_drop_accounting_columns(df_copy)
    df = df_copy
    node_to_test = (df
        .pipe(main.flag_data_for_the_allocation_methodology)
        .pipe(main.convert_repeating_values_to_nan)
        .pipe(main.melt_and_drop_accounting_columns))
    assert True         
    
def test_melt_and_drop_engineering_columns(df_copy)
    df = df_copy
    node_to_test = (df
        .pipe(main.flag_data_for_the_allocation_methodology)
        .pipe(main.convert_repeating_values_to_nan)
        .pipe(main.melt_and_drop_accounting_columns)
        .pipe(main.melt_and_drop_engineering_columns))
    assert True     

def test_process_csv_to_tiny_format(df_from_csv):
    df = df_from_csv.copy()
    tiny_data = main.process_csv_to_tiny_format(df)
    assert True 
</code></pre>
",https://stackoverflow.com/questions/65411340/what-is-the-pythonic-way-to-test-dataframe-processing-pipelines,"['python', 'pandas', 'pytest']",273,False,0,0
Spock unit testing to test the RestTemplate.postForEntity,"<p>I am new to Spock unit testing framework. I am able to write unit test cases using Spock for simple logics. Now, I am writing the same for a Rest API.</p>

<p>I am using Spring's RestTemplate to hit the GET and POST requests. I have seen number of example in google for GET request(like WireMock). But, there is no enough information to give clarification on how to write test cases for POST requests. </p>

<p>Here is my sample code which is written in Junit. I have to convert the same to Spock (I can do).</p>

<pre><code>import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;

import com.github.tomakehurst.wiremock.junit.WireMockRule;

@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
@ActiveProfiles(value = ""integration"")
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class LocalControllerTest {

  @Rule
  public WireMockRule wireMockRule = new WireMockRule(9999);

  @Before
  public void setUp() {
    mockRemoteService();
  }

  @Test
  public void testLocalServiceWithMockedRemoteService() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity&lt;String&gt; response = restTemplate.getForEntity(""http://localhost:8080/localService"", String.class);
    org.junit.Assert.assertEquals(""Input : request from client endpoint, Message : mocked remote service response"", response.getBody());
  }

  private void mockRemoteService() {
    stubFor(get(urlEqualTo(""/remote""))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader(""Content-Type"", ""application/json"")
            .withBodyFile(""remoteServiceResponse.json"")));
  }

}
</code></pre>

<p>Main issue is, even though I wrote the test cases, the call is actually happening to the service (Which is at my localhost) which I am not expecting to happen it. Is there any way to Mock up the data locally and make the call to dummy endpoint for POST request using Spock framework? I don't know much about to mock a dummy endpoint.</p>

<p>Your help is highly appreciated.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/60819973/spock-unit-testing-to-test-the-resttemplate-postforentity,"['groovy', 'spock']",739,False,0,0
Angular Unit Test (w/ Jest) a service that imports and uses an esm module;,"<h1>Explination</h1>

<p>I have a unit testing question using Angular (v 9), Jest (24.9.0), and an ECMAScript Module (dialog-polyfill (v 0.5.1) ). This polyfill adds support for the <code>HTMLDialogElement</code>. The issue is, it has a method <code>registerDialog</code> that needs to be called when the dialog is in the DOM. It takes the dialog element as it's only parameter. This service that I've created, registers the dialog and adds it to an array. Everything works perfectly with the implementation, but the tests fail because it doesn't know what the polyfill is. I keep getting the following error:</p>

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

<ul>
<li>Note: I am quite new to testing in Angular and my implementation might not be correct; if so, please let me know.</li>
<li>Second Note: I'm note sure if there is a better way to create a Dialog Element besides calling <code>createElement</code> on the document within the Jest test.</li>
</ul>

<h2>Dialog Service</h2>

<pre><code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

import dialogPolyfill from 'dialog-polyfill';

@Injectable({
  providedIn: 'root'
})
export class DialogService {
  public dialogs$: BehaviorSubject&lt;HTMLDialogElement[]&gt; = new BehaviorSubject&lt;
    HTMLDialogElement[]
  &gt;([]);

  private dialogs: [] = [];

  constructor() {}

  register(dialog: HTMLDialogElement) {
    dialogPolyfill.registerDialog(dialog);
    this.dialogs$.next([...this.dialogs, dialog]);
  }
}
</code></pre>

<h2>Dialog Service Spec</h2>

<pre><code>import { TestBed } from '@angular/core/testing';

import { DialogService } from './dialog.service';

describe('DialogService', () =&gt; {
  let service: DialogService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({});
    service = TestBed.inject(DialogService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

  it('should register a dialog', () =&gt; {
    expect(service.dialogs$.getValue().length).toBe(0);
    service.register(document.createElement('dialog'));
    expect(service.dialogs$.getValue().length).toBe(1);
  });
});

</code></pre>

<h3>References</h3>

<ul>
<li><a href=""https://github.com/GoogleChrome/dialog-polyfill/tree/8b458a4b7629eef5d1919dbb4393ee758d202d92"" rel=""nofollow noreferrer"">Dialog Polyfill</a></li>
<li><a href=""https://angular.io"" rel=""nofollow noreferrer"">Angular</a></li>
<li><a href=""https://jestjs.io"" rel=""nofollow noreferrer"">Jest JS</a></li>
</ul>
",https://stackoverflow.com/questions/61398619/angular-unit-test-w-jest-a-service-that-imports-and-uses-an-esm-module,"['javascript', 'angular', 'jestjs']",1436,True,0,1
Performing automated test for R shiny dashboard,"<p>Good day all,</p>
<p>I have spent quite some time looking into ways to perform unit test on my UI, specifically on my valuebox, progressbar, barcharts, etc. Firstly I am not exactly sure if &quot;unit test&quot; is the right term in this context so please kindly correct me if I am wrong. What I intend to do is to ensure that for example that the valuebox appears as intended (if I want 10 to appear on it, it should appear as 10 and not other number), the progressbar will progress accordingly to a reactive data.</p>
<p>I have looked into an R package called <a href=""https://rstudio.github.io/shinytest/articles/shinytest.html"" rel=""nofollow noreferrer"">shinytest</a> and they seem to have a snapshot approach which may not be feasible if we intend to extract data from a reactive database. I then tried out an <a href=""https://shiny.rstudio.com/articles/integration-testing.html"" rel=""nofollow noreferrer"">article</a> from R with regards to unit testing and was wondering if that is the right path for me.</p>
<p>Can I kindly get advice from experts that incorporate testing into their dashboard?</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/63719549/performing-automated-test-for-r-shiny-dashboard,"['r', 'unit-testing', 'testing', 'shiny', 'dashboard']",125,False,0,0
Unit testing base and derived class,"<p>So I have 2 classes. <code>ItemWithAttributes</code> and <code>ItemWithNameAndAttributes</code> (derives from 1st).</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Helpers;

namespace Objects.Base
{
    public class ItemWithAttributes
    {
        public IEnumerable&lt;string&gt; Attributes { get; }

        public ItemWithAttributes(IEnumerable&lt;string&gt; attributes)
        {
            if (attributes == null)
                throw new ArgumentNullException(nameof(attributes), ""Parameter can not be mull."");

            Attributes = attributes.ToArray();
        }

        public virtual string AttributesToParenthesesString(bool prependSpace)
        {
            return $""{Attributes.ToParenthesesString(prependSpace)}"";
        }

        public override string ToString()
        {
            return AttributesToParenthesesString(false);
        }
    }
}
</code></pre>

<pre><code>using System;
using System.Collections.Generic;

namespace Objects.Base
{
    public class ItemWithNameAndAttributes : ItemWithAttributes
    {
        public string Name { get; }

        public ItemWithNameAndAttributes(string name, IEnumerable&lt;string&gt; attributes) : base(attributes)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name), ""Parameter can not be null."");

            if (name.Length == 0)
                throw new ArgumentException(""Parameter can not be empty."", nameof(name));

            Name = name;
        }

        public override string ToString()
        {
            return $""{Name}{AttributesToParenthesesString(true)}"";
        }
    }
}
</code></pre>

<p>I want to get into unit testing so this is what I got so far for both my classes. I did some reading on naming convention for test method naming but I feel kind of stuck now.</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Objects.Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests.Objects.Base
{
    [TestClass]
    public class ItemWithAttributesTests
    {
        [TestMethod]
        public void Constructor_AttributesWithElements_PropertyEqualToInput()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            CollectionAssert.AreEqual(attributes, itemWithAttributes.Attributes.ToList());
        }

        [TestMethod]
        public void Constructor_AttributesWithoutElements_PropertyEqualToInput()
        {
            var attributes = new List&lt;string&gt;() { };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            CollectionAssert.AreEqual(attributes, itemWithAttributes.Attributes.ToList());
        }

        [TestMethod]
        public void Constructor_AttributesNull_ThrowArgumentNullException()
        {
            Assert.ThrowsException&lt;ArgumentNullException&gt;(() =&gt; new ItemWithAttributes(null));
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependFalse_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual(""(Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependTrue_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("" (Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependFalse_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() {  };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependTrue_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() {  };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void ToString_AttributesWithElements_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.ToString();

            Assert.AreEqual(""(Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void ToString_AttributesWithoutElements_ReturnsEqualString()
        {
            var attributes = new List&lt;string&gt;() { };
            var itemWithAttributes = new ItemWithAttributes(attributes);

            var result = itemWithAttributes.ToString();

            Assert.AreEqual("""", result);
        }
    }
}
</code></pre>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Objects.Base;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests.Objects.Base
{
    [TestClass]
    public class ItemWithNameAndAttributesTests
    {
        [TestMethod]
        public void Constructor_NameAndAttributesWithElements_PropertiesAreEqualToInput()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            Assert.AreEqual(name, itemWithNameAndAttributes.Name);
            CollectionAssert.AreEqual(attributes, itemWithNameAndAttributes.Attributes.ToList());
        }

        [TestMethod]
        public void Constructor_NameAndAttributesWithoutElements_PropertiesAreEqualToInput()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            Assert.AreEqual(name, itemWithNameAndAttributes.Name);
            CollectionAssert.AreEqual(attributes, itemWithNameAndAttributes.Attributes.ToList());
        }


        [TestMethod]
        public void Constructor_NameEmpty_ThrowArgumentException()
        {
            var name = string.Empty;
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            Assert.ThrowsException&lt;ArgumentException&gt;(() =&gt; new ItemWithNameAndAttributes(name, attributes));
        }

        [TestMethod]
        public void Constructor_NameNull_ThrowArgumentNullException()
        {
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            Assert.ThrowsException&lt;ArgumentNullException&gt;(() =&gt; new ItemWithNameAndAttributes(null, attributes));
        }

        [TestMethod]
        public void Constructor_AttributesNull_ThrowArgumentNullException()
        {
            var name = ""Name"";
            Assert.ThrowsException&lt;ArgumentNullException&gt;(() =&gt; new ItemWithNameAndAttributes(name, null));
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependFalse_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual(""(Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithElementsAndPrependTrue_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("" (Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependFalse_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(false);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void AttributesToParenthesesString_AttributesWithoutElementsAndPrependTrue_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.AttributesToParenthesesString(true);

            Assert.AreEqual("""", result);
        }

        [TestMethod]
        public void ToString_AttributesArgumentIsListWithElements_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { ""Item 1"", ""Item 2"", ""Item 3"", ""Item 4"", ""Item 5"" };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.ToString();

            Assert.AreEqual(""Name (Item 1) (Item 2) (Item 3) (Item 4) (Item 5)"", result);
        }

        [TestMethod]
        public void ToString_AttributesArgumentIsListWithoutElements_ReturnsEqualString()
        {
            var name = ""Name"";
            var attributes = new List&lt;string&gt;() { };
            var itemWithNameAndAttributes = new ItemWithNameAndAttributes(name, attributes);

            var result = itemWithNameAndAttributes.ToString();

            Assert.AreEqual(""Name"", result);
        }
    }
}
</code></pre>

<p>What I notice is that the unit tests for my derived class <code>ItemWithNameAndAttributes</code> are almost the same as for my base class <code>ItemWithAttributes</code> but just a little more and different because I also need to validate for the name argument. I'm not sure if this is the correct way to go or if there is some method to reuse the tests from my base class in my derived class. If I keep this current pattern up, when I derive from <code>ItemWithNameAndAttributes</code> I would have even more tests that are the same and retest the base classes. I got the feeling it got very complex very quickly for the small classes I have.</p>
",https://stackoverflow.com/questions/60128329/unit-testing-base-and-derived-class,"['c#', 'unit-testing']",114,True,0,1
How to prevent &quot;‘amplify-authenticator’ is not a known element&quot; error in unit tests when using Amplify UI Components,"<p>I am using the <a href=""https://docs.amplify.aws/ui/q/framework/angular"" rel=""nofollow noreferrer"">Amplify UI Components</a> for <a href=""https://angular.io"" rel=""nofollow noreferrer"">Angular</a> V 10. When unit-testing my application, I receive the following error:</p>
<pre><code>ERROR: ‘amplify-authenticator’ is not a known element
</code></pre>
<p>In order to prevent this error, I'm importing the AmplifyUIAngularModule in the testing configuration of the component:</p>
<pre><code>import { AmplifyUIAngularModule } from '@aws-amplify/ui-angular';

beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [
        AmplifyUIAngularModule
      ]
    })
})
</code></pre>
<p>This resolves the first error, but triggers another one:</p>
<pre><code>Error: Amplify has not been configured correctly.
The configuration object is missing required auth properties.
Did you run amplify push after adding auth via amplify add auth?
See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information
</code></pre>
<p>So obviously it’s telling me that the AmplifyUIAngularModule can’t be initialized without a config. I tried to add it, although it feels wrong, as the component should not connect in a unit test, but be mocked:</p>
<pre><code>Amplify.configure({
    Auth: {
      ....
    },
  });
</code></pre>
<p>This indeed resolves the error, but when karma/jasmine tries to connect to headless chrome for testing, there is a timeout. I suspect the <a href=""https://aws.amazon.com/amplify/"" rel=""nofollow noreferrer"">amplify</a> stuff is trying to connect indeed, which can’t be the way to go in a unit test.</p>
<p>There are various threads on SO about how to mock a AWS/Amplify call, but I can't find anything about how to prevent the missing amplify-authenticator dependency.</p>
",https://stackoverflow.com/questions/65017279/how-to-prevent-amplify-authenticator-is-not-a-known-element-error-in-unit-te,"['angular', 'karma-jasmine', 'aws-amplify']",532,True,0,1
Programmatically redef functions,"<p>I'm currently in the start of making a tool that should modify all the functions in another namespace, and the run the ""main"" function in that (other) namespace. Almost like mocking in unit-testing, but for another purpose. The first step to this is to redefine functions from another namespace. The first listing shows code that works, where I explicitly name the function to be replaced.</p>

<pre><code>(ns one)
(defn a-fun []
  (println ""original""))

(defn caller []
  (a-fun))

(ns two)

(with-redefs [one/a-fun #(println ""replaced"")]
  (one/caller))
;; replaced
;; nil
</code></pre>

<p>The next step is getting the functions programmatically from the other namespace. This is where I have run into a wall. I've experimented much with <code>ns-publics</code>, but so far no luck. So I try to break the problem down. And the problem is that the replacement of the function is not working. The output should print ""replaced"" not ""original"".</p>

<pre><code>(ns two)
(def target (ns-resolve 'one (symbol ""a-fun"")))
(def caller (ns-resolve 'one (symbol ""caller"")))
(with-redefs [target #(println ""replaced"")]
  (caller))
;; original
;; nil
</code></pre>

<p>Now, the <code>#'two/target</code> shows <code>#'one/a-fun</code> when I evaluate it in the repl. I can call <code>one/a-fun</code> by entering <code>((ns-resolve 'one (symbol ""a-fun"")))</code> in the repl, so I don't understand what part is not working.</p>

<p>I've been through a lot of documentation today, and I'm not really getting any closer.</p>
",https://stackoverflow.com/questions/59914645/programmatically-redef-functions,['clojure'],274,True,0,1
Testing that a generated batch of names are legally possible,"<p>I'm trying to get into the habit of unit testing my code. I am playing around trying to get a better grasp of what it can do. By default my method generates a random list of 30 product names.</p>

<p>The names are randomly chosen from two list:</p>

<blockquote>
<pre><code>_adjectives = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved', 'Giant',
               'Rocket-Powered', 'Super', 'Exploding', 'Invisible']

_nouns = ['Anvil', 'Catapult' 'Disguise' 'Mousetrap', 'Hitch-Hiker Thumb',
          'Roller Skates', 'Roller Skis', 'Packing Machine', 'Leg Muscle Vitamins',
          'Camouflage', 'Golf Balls', 'Toaster', 'Grenade', 'Aspirin',
          'Matches', 'Street Cleaner Wagons', 'Nitroglycerin', 'Bird Seeds',
          'Glue', 'Smoke Bomb', 'Grease']
</code></pre>
</blockquote>

<p>the resulting names looks like : [""Awesome Anvil"", ""Super Disguise"", ""Invisible Hitch-Hiker Thumb"",..., ""Exploding Golf Balls""]</p>

<p>I'm trying to write a unit test that checks that the generated names for a default batch of products are all valid possible names to generate (adjective, space, noun, from the lists of possible words)</p>

<p>My current thought is to use string processing to strip out each word using string processing then use <code>assertIn</code> from <code>unittest</code> to get the excepted answer but I'm honestly just stumped and only get half of what I expect. I'm trying to see a few examples on how this could be done I can weave into other examples  in the future.</p>
",https://stackoverflow.com/questions/61923970/testing-that-a-generated-batch-of-names-are-legally-possible,"['python', 'unit-testing']",21,False,0,0
Java mocking class methods and injected services,"<p>I need to unit test this class. I have some control over the source, but am limited in what I can do to it (it's much more complex than this, of course, and I can't do a wholesale rewrite)</p>

<pre><code>public class MyService {
   @Inject
   private AnotherService anotherService;

   public ReturnObject MainMethod(..arguments..) {
      anotherService.someFunction(..arguments..);
      localFunction(..arguments..)
   }

   protected void localFunction(..arguments..) {
      ..code..
   }
}
</code></pre>

<p>I have access to Mockito and PowerMock. The ""someFunction"" in anotherService is an instance method, not static. I've tried using overrides as thus:</p>

<pre><code>@Test
public void shouldWork() {
  MyService myService = new testMyService();
  myService.MainMethod(..arguments..);
  ..test some stuff..
}
class testMyService extends MyService {
  testAnotherService anotherService = new testAnotherService();
  @Override
  protected void localFunction(..arguments..) {}
}
class testAnotherService extends AnotherService {
  @override
  public void someFunction(..arguments..) {}
}
</code></pre>

<p>When I run this, anotherService is null. I tried both creating an actual instance of testAnotherService inside of testMyService, and injecting it with @Inject (that latter wouldn't compile). </p>

<p>What I seek to do is, by the tenets of ""good unit testing on previously badly designed code with no tests"", test all of the functionality within MainMethod, but stub/mock both the localFunctions (there are more than just the one) and the injected services, so that the only actual code under test is the code in MainMethod. </p>

<p>Please be gentle, long time reader, first (or nearly first) time asking!</p>
",https://stackoverflow.com/questions/61841664/java-mocking-class-methods-and-injected-services,"['java', 'unit-testing', 'mocking', 'mockito', 'powermock']",275,False,0,0
How to perform Google Add-on automated deployment/publishing?,"<p>My team is trying to apply modern software engineer techniques in developing an editor add-on for Google Spreadsheet.</p>
<p>With clasp, typescript, jest, git, GCP and CircleCI we were able to achieve:</p>
<ul>
<li>local development with our preferred source code management;</li>
<li>unit testing/tdd on our domain rules;</li>
<li>manage add-on versions by clasp;</li>
<li>observability with Stackdriver on GCP;</li>
<li>with CircleCi, we create a pipeline that executes unit-tests, makes clasp push and versions the add-on with the commit hash as a description.</li>
</ul>
<p>In addition, through Google Marketplace SDK, the add-on has been distributed privately in our domain, therefore it doesn't need Google approval.</p>
<p><strong><em>The point is:</em> we're looking for a way to add a step in our pipeline to, programmatically, update and manage our published add-on.</strong></p>
<p>e.g.: after the generation of a new version with clasp, how to put it in the App Configuration on GCP?</p>
<p><a href=""https://i.stack.imgur.com/kpiF9.png"" rel=""nofollow noreferrer"">gcp app configuration page</a></p>
<p>In the <a href=""https://developers.google.com/gsuite/add-ons/how-tos/update-published-add-on"" rel=""nofollow noreferrer"">documentation</a> there are only manual steps.</p>
<p>Thank you all =)</p>
",https://stackoverflow.com/questions/63938657/how-to-perform-google-add-on-automated-deployment-publishing,"['google-apps-script', 'google-cloud-platform']",154,True,0,1
Trying to get cypress react unit testing working within a ReactBoilerplate repo,"<p>So i've been slamming my head against a wall for the last 5 hours or so trying to work out how to get this all working.</p>
<p>I've then replicated an internal project's structure and deps, and made it into a public repo in an effort to try and get some help. I know it's going to be some kind of bad configuration problem, but I just cant figure out where.</p>
<p>Could someone please help me understand what i need to do to get cypress react unit testing going within a webpack typescript react project?</p>
<p><a href=""https://github.com/glomotion/test-cypress-typescript-react"" rel=""nofollow noreferrer"">https://github.com/glomotion/test-cypress-typescript-react</a></p>
<p>When trying to run</p>
<pre><code>yarn run cypress open
</code></pre>
<p>and then running the single test that appears from the UI...</p>
<p>I always seem to get some kind of webpack/typescript related build errors from cypress:<a href=""https://i.stack.imgur.com/kgNPJ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/kgNPJ.png"" alt=""enter image description here"" /></a></p>
<p>incasse it helps... here is some extra debug info from the console while trying to run with extra webpack debug info:</p>
<pre><code>cypress:webpack stats had error(s) +8s
  cypress:webpack errored bundling /Users/timpaul/Library/Application Support/Cypress/cy/production/projects/test-cypress-typescript-react-ffdf18db96b66e8934f9c769081501f9/bundles/src/components/vertical-space/vertical-space.cypress.test.tsx.js Webpack Compilation Error
./src/components/vertical-space/vertical-space.cypress.test.tsx
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for /Users/timpaul/Desktop/GIT-Repos/test-cypress-typescript-react/src/components/vertical-space/vertical-space.cypress.test.tsx. +8ms
  cypress:webpack - compile finished for /Users/timpaul/Desktop/GIT-Repos/test-cypress-typescript-react/src/components/vertical-space/vertical-space.cypress.test.tsx, initial? true +93ms
Webpack Compilation Error
./src/components/vertical-space/vertical-space.cypress.test.tsx
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for /Users/timpaul/Desktop/GIT-Repos/test-cypress-typescript-react/src/components/vertical-space/vertical-space.cypress.test.tsx.
GET /__cypress/tests?p=src/components/vertical-space/vertical-space.cypress.test.tsx 200 8680.292 ms - 431
  cypress:webpack finished bundling /Users/timpaul/Library/Application Support/Cypress/cy/production/projects/test-cypress-typescript-react-ffdf18db96b66e8934f9c769081501f9/bundles/cypress/support/index.js +432ms
  cypress:webpack - compile finished for /Users/timpaul/Desktop/GIT-Repos/test-cypress-typescript-react/cypress/support/index.js, initial? true +7ms
</code></pre>
<p>package dependency versions:</p>
<pre><code>// package.json:
...
 &quot;engines&quot;: {
   &quot;npm&quot;: &quot;&gt;=6.14.8&quot;,
   &quot;node&quot;: &quot;&gt;=12.18.4&quot;
 },
...
&quot;cypress-react-unit-test&quot;: &quot;^4.16.0&quot;,
&quot;@cypress/webpack-preprocessor&quot;: &quot;^5.4.7&quot;,
&quot;cypress&quot;: &quot;^5.3.0&quot;,
&quot;typescript&quot;: &quot;^4.0.3&quot;,
&quot;webpack&quot;: &quot;^4.44.2&quot;,
...
</code></pre>
",https://stackoverflow.com/questions/64351765/trying-to-get-cypress-react-unit-testing-working-within-a-reactboilerplate-repo,"['reactjs', 'typescript', 'unit-testing', 'cypress']",601,True,0,1
Issue testing if inner function is called using Jest/Enzyme,"<p>The function I'm trying to test is below. We are using a builder like approach for assembling our complicated URL structures to help with navigating around our web application.</p>

<pre class=""lang-js prettyprint-override""><code>import { useNavigation } from '../../../blah';

useNavigation().goBack();
</code></pre>

<p>The full-function I'm trying to check was called is below</p>

<pre class=""lang-js prettyprint-override""><code>export const useNavigation = (path) =&gt; {
  const { view } = store.getState();

  const withQueryParams = (params = {}) =&gt; {
    const paramString = addQueryStringParameters(params);
    return useNavigation(`${path}${paramString}`);
  };

  const tlo = (id) =&gt; useNavigation(`/${id}/${id}${path}`);

  const site = (id) =&gt; useNavigation(`/${view.activeTLO.id}/${id}${path}`);

  const current = () =&gt; useNavigation(`/${view.activeTLO.id}/${view.activeSite.id}${path}`);

  const navigate = () =&gt; history.push(path);

  const goBack = () =&gt; history.goBack();

  return {
    withQueryParams,
    tlo,
    site,
    current,
    navigate,
    path,
    goBack,
  };
};
</code></pre>

<p>In jest, I'm trying to mock the internal goBack function so that we can check if it's called at a certain point in the code, but I'm having no luck so far.</p>

<p>I'm importing and mocking the function like so</p>

<pre class=""lang-js prettyprint-override""><code>import * as navigateTo from '../../../lib/navigateTo';

navigateTo.useNavigation = jest.fn(() =&gt; ({
  goBack: jest.fn(),
}));
</code></pre>

<p>When trying to do the expect on the goBack function, to check if it was called things get a little odd.</p>

<p>The below expect does work as it can see that navigateTo.useNavigation has been called but with every effort, I cannot check if the navigateTo.useNavigation.goBack has been called as its always undefined.</p>

<pre class=""lang-js prettyprint-override""><code>it('renders the navigate to the orders page', () =&gt; {
  const actions = availableOrderActions(settings).find((action) =&gt; action.label === 'Supplier Orders');
  actions.clickHandler();

  expect(navigateTo.useNavigation).toHaveBeenCalled();
});
</code></pre>

<p>Any help with this would be great as its real issues quite a few of us have been facing when it comes to the unit testing side of things.</p>

<p>Thanks in advance,
Chris</p>
",https://stackoverflow.com/questions/60626153/issue-testing-if-inner-function-is-called-using-jest-enzyme,"['reactjs', 'unit-testing', 'mocking', 'jestjs', 'enzyme']",381,False,0,1
Adding unit-tests to Clojure CLI tools and deps.edn,"<p>I'm used to using Clojure with Leiningen.</p>

<p>But I have a new project that I booted into existence with LightMod. And it uses CLI tools and deps.</p>

<p>This works but I now want to add some unit testing to it.</p>

<p>So here's (a slightly simplified version of) my deps.edn file :</p>

<pre><code>{:paths [""src"" ""resources""],
 :aliases
 {
  :dev
  {:extra-deps
   {orchestra #:mvn{:version ""2018.12.06-2""},
    expound #:mvn{:version ""0.7.2""},
    nightlight #:mvn{:version ""RELEASE""},
    com.bhauman/figwheel-main #:mvn{:version ""0.2.0""}},
   :main-opts [""dev.clj""]},

  :test
  {:extra-paths [""test""]
   :extra-deps {com.cognitect/test-runner {:git/url ""https://github.com/cognitect-labs/test-runner.git""                                           :sha ""209b64504cb3bd3b99ecfec7937b358a879f55c1""}}
   :main-opts [""-m"" ""cognitect.test-runner""]}

  :prod
  {:extra-deps
   {leiningen #:mvn{:version ""2.9.0""},
    org.clojure/clojurescript #:mvn{:version ""1.10.439""}},
   :main-opts [""prod.clj""]},

  :app
  {:extra-deps
   {
    markdown-clj {:mvn/version ""1.10.1""}
    instaparse {
                :mvn/version""1.4.10""
                }
    ... MORE ...
}}}}
</code></pre>

<p>Now this file has worked OK with both :dev and :prod compilation.</p>

<p>But now I've just added the :test alias. </p>

<p>And put my tests into test/myns/core_tests.clj</p>

<p>However, when I try to run tests, I get this </p>

<pre><code>Could not locate markdown/core__init.class, markdown/core.clj or markdown/core.cljc on classpath
</code></pre>

<p>So my interpretation. While the :dev and the :prod branches are successfully pulling in all the dependencies in the :app branch. The :test branch is not pulling in markdown. (And probably none of the other dependencies declared in :app</p>

<p>So why should this be? And how can I explicitly tell my :test clause that it needs to use all the same dependencies that are used in :dev and :prod?</p>
",https://stackoverflow.com/questions/60999293/adding-unit-tests-to-clojure-cli-tools-and-deps-edn,"['unit-testing', 'clojure']",967,True,0,1
error while loading shared libraries: libgmock.so: cannot open shared object file: No such file or directory,"<p>I am currently facing an issue with a project of mine foudn while configuring CI.</p>

<p><strong>Resume</strong></p>

<p>The problem faced is the following:
<code>error while loading shared libraries: libgmock.so: cannot open shared object file: No such file or directory</code>.</p>

<p>For the problem above I am not installing the google test/google mock framework but <strong>I am compiling it</strong>. Although it says it didn't foudn I have printed the LD_LIBRARY_PATH variable with the following results:</p>

<pre><code>[root@f2cf44f0b794 st]# echo $LD_LIBRARY_PATH
/st/staging_dir/x86_64-linux-gnu/lib:/st/staging_dir/x86_64-linux-gnu/lib64
</code></pre>

<p>To check if the file didn't really exists I have used find and checked <strong>it did exists</strong>:</p>

<pre><code>[root@f2cf44f0b794 st]# find . -name libgmock.so*
./build_dir/x86_64-linux-gnu/googletest/googlemock/libgmock.so
./staging_dir/x86_64-linux-gnu/lib64/libgmock.so
</code></pre>

<p>I have also ls the dir to double check this:</p>

<pre><code>[root@f2cf44f0b794 st]# ls /st/staging_dir/x86_64-linux-gnu/lib64/
cmake        libcrypto.so      libgmock.so       libgtest.so       libprotobuf-lite.so          libprotobuf.so          libprotoc.so          libssh.so    libssh.so.4.8.1  libssl.so      pkgconfig
libcrypto.a  libcrypto.so.1.1  libgmock_main.so  libgtest_main.so  libprotobuf-lite.so.3.8.0.0  libprotobuf.so.3.8.0.0  libprotoc.so.3.8.0.0  libssh.so.4  libssl.a         libssl.so.1.1
</code></pre>

<p><strong>Background</strong></p>

<p>All the code is being built for both <strong>Ubuntu 14.04.5</strong> and <strong>centos7</strong>. For this, two builds are run on two Docker containers with the distributions above. The funny thing is that, for the Ubuntu container, the build doesn't fail but for CentOS container the build fails with the error above. Although the error above is just for unit testing and I could easily disable them for CentOS build, I really wanted to understand why this issue is happening.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/60465611/error-while-loading-shared-libraries-libgmock-so-cannot-open-shared-object-fil,"['c++', 'linux', 'makefile', 'compilation', 'centos7']",1174,True,0,1
"unit testing custom hook for getting data, redux useSelector and dispatch","<p>I have been testing a custom hook for getting data from redux state and all is working nice within the app but I am having some issues with testing coverage, namely with unit testing my custom hook. here is my testing code:</p>
<p>useGetHomes custom hook:</p>
<pre><code>import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { getHomes } from '../pages/Homes/actions';

const useGetHomes = () =&gt; {

   const dispatch = useDispatch();
   const homes = useSelector(state =&gt; state.homes);

   useEffect(() =&gt; {

       dispatch(getHomes()); 

   }, [dispatch]);

   //TO DO - extend more

   return {
      homes
   };

};

export default useGetHomes;
</code></pre>
<p>current test file:</p>
<pre><code>import React from 'react';
import { mount } from 'enzyme';

import useGetHomes from '../useGetHomes';

//for testing
const TestHook = ({callback}) =&gt; {

    callback();
    return null;

};

const testHook = callback =&gt; {
  mount(&lt;TestHook callback={callback}/&gt;);
};
//end for testing

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

    let homes;

    beforeEach(() =&gt; {
        testHook(() =&gt; {
            homes = useGetHomes();
        });
    });

    it('should do first test', () =&gt; {

        console.log('first test')
        console.log(homes)  

    });

});
</code></pre>
<p>my current test gives me the following error:</p>
<blockquote>
<p>could not find react-redux context value; please ensure the component is wrapped in a Provider</p>
</blockquote>
<p>I tried wrapping it in a Provider as error is clear but I get the following error:</p>
<blockquote>
<p>Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.</p>
</blockquote>
<p>I guess this is also clear as custom hook returns an object, so is there anything I could do to unit test my custom hook ? On the other hand my integration tests on the components that use the hook are good and working properly.</p>
",https://stackoverflow.com/questions/64748900/unit-testing-custom-hook-for-getting-data-redux-useselector-and-dispatch,"['reactjs', 'unit-testing', 'testing', 'redux', 'react-hooks']",1744,True,0,1
Restoring specific version of spreadsheet using the Google API,"<p>Just like the title says, I'm trying to find a way to restore a spreadsheet to a specific version using the Google Sheets API v4 (or Google Drive API v3). </p>

<p>This is needed because of unit testing - I need one test to perform some actions (let's say delete a row) on a spreadsheet, assert the results and then reset the spreadsheet to its initial state so the next test can execute on the original spreadsheet.</p>

<p>So far I noticed that there isn't an option to do something similar in the Google Sheets API. As far as using the Google Drive API goes, I tried using <a href=""https://developers.google.com/drive/api/v3/reference/revisions"" rel=""nofollow noreferrer"">revisions</a> (getting a list of all revisions and deleting all revisions after the desired one), but to no avail. </p>

<p>I also tried capturing the request after clicking on the <strong>Restore this version</strong> button and found out there is a <code>revisions/revert</code> endpoint. </p>

<pre><code>&gt; Example:
&gt; https://docs.google.com/spreadsheets/d/**spreadsheetId**/revisions/revert?includes_info_params=false
</code></pre>

<p>I actually managed to revert the version this way, but using Postman and using hardcoded values - which is bad.</p>

<p>Any advice on how to approach this?</p>
",https://stackoverflow.com/questions/60149716/restoring-specific-version-of-spreadsheet-using-the-google-api,"['c#', 'google-drive-api', 'google-sheets-api']",1479,True,4,1
How can I prevent top-level code from running on import?,"<p>I want to test a Python module, which in turn depends on another Python module, which in turn is badly behaved: it doesn't check for <code>__name__</code> but always runs some code. This code accesses the file system and hence gets in the way of unit testing. </p>

<p>Here is a simplified version of the problem that just prints something:</p>

<p>test.py:</p>

<pre><code>from unittest import TestCase
import tested

class MyTest(TestCase):
    def test_one(self, mocked_dep):
        self.assertEqual(1, tested.one())

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

<p>The code under test, tested.py:</p>

<pre><code>import dep

def one():
    return 1
</code></pre>

<p>The badly behaved dependency, dep.py:</p>

<pre><code>def do_stuff():
    # access file system, open network connection, go to database
    print(""I got called!"")

do_stuff()
</code></pre>

<p>When I run this, I see the printed message.</p>

<pre class=""lang-none prettyprint-override""><code>I got called!
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
</code></pre>

<p>How can I prevent <code>do_stuff</code> from running?</p>

<p>I tried mocking it, but by the time my <code>@patch</code> is evaluated with the <code>import tested</code> in the beginning of test.py, the module probably has already been loaded and <code>do_stuff</code> has been called.</p>

<p>I also tried to <code>import tested</code> after the <code>@patch</code> inside the test (removing the <code>import tested</code> on line 3), but that still called <code>do_stuff</code> and printed its output.</p>

<pre><code>from unittest import TestCase
from mock import patch

class MyTest(TestCase):
    @patch(""tested.dep.do_stuff"")     # &lt;-- too late? still prints
    def test_one(self, mocked_dep):
        import tested                 # &lt;-- moving the import here did not help either
        self.assertEqual(1, tested.one())
</code></pre>

<p>I cannot change the behavior of <code>dep.py</code> as too much other code may depend on it.</p>

<p>How can I prevent <code>do_stuff</code> from getting called? Or is my only option to mock the functions I don't want <code>do_stuff</code> to call, in this case <code>print</code>?</p>
",https://stackoverflow.com/questions/60066632/how-can-i-prevent-top-level-code-from-running-on-import,"['python', 'mocking', 'python-import']",274,False,3,0
Creating stub functions for express middleware in ES6 node.js project unit tests,"<p>I am trying to stub authentication middleware in my unit tests, as is done <a href=""https://stackoverflow.com/questions/41995464/how-to-mock-middleware-in-express-to-skip-authentication-for-unit-test"">here</a>. My issue is that the module that I am trying to stub is an ES6 module. As a note, I am not using Babel but instead the <code>&quot;type&quot;: &quot;module&quot;</code> in my package.json.</p>
<p>The function that I am trying to stub is called <code>checkAuthentication</code>, and it is inside the authentication module. I am using Mocha for unit testing.</p>
<p>Using Sinon I created the following solution.</p>
<pre><code>import chai from 'chai';
import sinon from 'sinon';
import chaiHttp from 'chai-http';
import authentication from '../middleware/authentication.js';

chai.use(chaiHttp);
const expect = chai.expect;

sinon.stub(authentication, 'checkAuthentication').callsFake(function(req, res, next) {
  return next();
});

import server from '../app.js'

it('Expect a status of 200', async () =&gt; {
    const res = await chai.request(server)
      .post('/endpoint')
      .set('content-type', 'application/json')
      .send({data: &quot;apple&quot;})
  
    expect(res).to.have.status(200);
});
</code></pre>
<p>Unfortunately, this does not seem to work, as the server is created and does not use the stub function but rather the regular function, and the test does not bypass the authentication middleware. Furthermore, it seems impossible to put this stub function replacement in a <code>beforeEach</code>, as is recommended, because of the necessity to import the server after the stub function is created.</p>
<p>I have also looked at using proxyquire, however, I receive the error &quot;Must use import to load ES Module&quot;.</p>
<p>Is there another solution to this issue? I have no attachment to Mocha and would be completely happy utilizing a different tool.</p>
",https://stackoverflow.com/questions/65479202/creating-stub-functions-for-express-middleware-in-es6-node-js-project-unit-tests,"['node.js', 'unit-testing', 'express', 'ecmascript-6', 'sinon']",233,False,3,0
Running tests for .NET Core in Docker during local dev,"<p>I understand that we can build our Dockerfile with a stage to execute <code>dotnet test</code> and run our unit tests during the docker build.</p>
<p>My question is regarding whether or not we would want those tests to run during local dev (e.g. with Visual Studio).</p>
<p>If we run (F5) a .NET Core app that is set up to build into a Docker image, and then use the VS tools for Docker to debug, etc., are we going to also be running our unit tests at that point EVERYTIME we run/debug locally?</p>
<p>What if I already use the test runner built-into Visual Studio (or even the Live Unit Testing feature) during dev/debug time? Am I still forced to run those same unit tests during the docker build that is triggered from the IDE's Run/F5 command if I define a stage in the Dockerfile for running tests?</p>
<p>If not, what is the recommended approach to running tests in Docker but only execute that stage during a CI build and not during a local dev build?</p>
",https://stackoverflow.com/questions/63181856/running-tests-for-net-core-in-docker-during-local-dev,"['visual-studio', 'docker', 'unit-testing', '.net-core', 'automated-tests']",3186,True,3,1
How can I use MockWebServer for Junit test cases of webclient?,"<p>I have a spring-boot application which calls some third party URL (let's say <code>http://example.com/someUri</code>) using webclient(I have used application-dev.properties for injecting this url in my application to achieve loose coupling) and consumes the response and use it in my application.</p>
<p>It's my first time when I am going to write test cases for webclient. and there I used @SprintBootTest.
I found that there are two ways where I can test my webclient with third party Api call by mocking the api call and make it call to my local url(which will be using url(http://localhost:{portNumber}/someUri) from my testing properties file: src/test/resources/application.properties) where It will be giving some mockedResponse in return to my real client:</p>
<ol>
<li>Using <strong>wiremock</strong></li>
<li>Using <strong>MockWebServer</strong></li>
</ol>
<p>consider above code for better understanding:</p>
<pre class=""lang-java prettyprint-override""><code>@Service
Class SampleService{
    
@Value(&quot;${sample.url}&quot;)
private String sampleUrl;

public String dummyClient() {
    String sample =webClient.get()
            .uri(sampleUrl)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .retrieve()
            .bodyToMono(String.class)
            .block();
    return sample;

    }
 }
</code></pre>
<p>application-dev.properties:</p>
<pre><code>sample.url:http://example.com/someUri
</code></pre>
<p>src/test/resouces/application.properties:</p>
<pre><code>http://localhost:8090/someUri
</code></pre>
<p>Testing class:</p>
<pre class=""lang-java prettyprint-override""><code>@SpringBootTest
public class sampleTestingClass {

@Autowired
private SampleService sampleService;

@Value(&quot;${sample.url}&quot;)
private String sampleUrl;

    public static MockWebServer mockWebServer = new MockWebServer();

    @BeforeAll
    static void setUp() throws IOException {
        mockWebServer.start(8090);
    }

    @AfterAll
    static void tearUp() throws IOException {
        mockWebServer.close();
    }

 HttpUrl url = mockWebServer.url(&quot;/someUri&quot;);
       
        mockWebServer
                .enqueue(
                new MockResponse()
                .setResponseCode(200)
                .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .setBody(&quot;Sample Successful&quot;)); 

      
        String sample = sampleService.dummyClient();
        assertEquals(sample ,matches(&quot;Sample Successful&quot;));
    } 
}
</code></pre>
<p>but this code isn't working. it's giving me above error:</p>
<pre><code>java.lang.NullPointerException 
</code></pre>
<p>It will be really helpful if anybody knows how this can be fixed to achieve my unit testing using mocked Url? Thanks in advance!</p>
",https://stackoverflow.com/questions/62506206/how-can-i-use-mockwebserver-for-junit-test-cases-of-webclient,"['unit-testing', 'junit', 'webclient', 'spring-boot-test', 'mockwebserver']",11397,True,3,1
Jest unit testing a function throwing error,"<p>I was trying to unit test a function in node which throws an error regardless of any condition. Here is my node function definition.</p>

<pre><code>public testFunction() {
    throw new Error('Test Error');
}
</code></pre>

<p>As you can see this function always throws an error whenever it has been called. I tried to execute unit testing to this function using jest <a href=""https://jestjs.io/docs/en/expect#tothrowerror"" rel=""nofollow noreferrer"">.toThrow(error?)</a> method. I was not able to unit test the function as expected.</p>

<p>The below mentioned are the test cases that I wrote and have attached the screenshot of the errors that I faced while executing the same.</p>

<p><strong>Test Case #1</strong></p>

<pre><code>it('Should throw test error', (done) =&gt; {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction()).toThrow();
});
</code></pre>

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

<p><strong>Test Case #2</strong></p>

<pre><code>it('Should throw test error', (done) =&gt; {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction).toThrow();
});
</code></pre>

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

<p><strong>Test Case #3</strong></p>

<p>From <a href=""http://eloquentcode.com/expect-a-function-to-throw-an-exception-in-jest"" rel=""nofollow noreferrer"">this</a> blog, it was mentioned that</p>

<blockquote>
  <p>If we want to expect a function to throw an exception for certain
  input parameters, the key point is that we must pass in a function
  definition and not call our function inside the expect.</p>
</blockquote>

<p>So I updated my test case as</p>

<pre><code>it('Should throw test error', (done) =&gt; {
    const testClass = TestClassService.getInstance();
    expect(() =&gt; testClass.testFunction()).toThrow();
});
</code></pre>

<p>But it was throwing error like</p>

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

<p>What is the issue with my implementation? What is the correct method to unit test a function which throws an error object back?</p>
",https://stackoverflow.com/questions/61285655/jest-unit-testing-a-function-throwing-error,"['javascript', 'node.js', 'unit-testing', 'jestjs']",7508,True,3,1
Unit testing With Jest in Node.js,"<p>I'm very new to unit testing and very excited about it. But I've uncertainty whether I should add defensive programming style or not to my production code. So, please see the following codes.</p>
<p>calclateFinalYearGPA.js (production code)</p>
<pre class=""lang-js prettyprint-override""><code>const _ = require('lodash');
const getGPAPoint = require('./getGPAPoint');

module.exports = function (gradings) {
  let totalPoint = 0;

  gradings.forEach((grading) =&gt; {
    const grade = grading.grading.grade.name;
    const point = getGPAPoint(grade);
    totalPoint += point;
  });

  const finalYearGPA = _.round(totalPoint / gradings.length, 1);

  return finalYearGPA;
};
</code></pre>
<p>The <code>gradings</code> is an array of objects which is pulled from the db, with the following structure.</p>
<pre><code>&quot;gradings&quot;: [
    {
        &quot;grading&quot;: {
            &quot;gradeId&quot;: 3,
            &quot;grade&quot;: {
                &quot;gradeId&quot;: 3,
                &quot;name&quot;: &quot;A-&quot;
            }
        }
    },
    ...
]
</code></pre>
<p>In my <code>calculateFinalYearGPA.js</code>, I loop through that array and extract <code>grading.grade.name</code> which is <code>A-</code> in the above structure, and pass it to <code>getGPAPoint</code>. It will return the decimal number.</p>
<p>So, now in my <code>calculateFinalYearGPA.test.js</code> test, I've add the following code which is test whether it fails when <code>gradings</code> is not an array.</p>
<pre class=""lang-js prettyprint-override""><code>const calculateFinalYearGPA = require('../../../utils/calculateFinalYearGPA');

describe('calculateFinalYearGPA', () =&gt; {
  it('should throw an exception if input is not an array', () =&gt; {
    const inputs = [1, 'a', null, undefined, {}];
    inputs.forEach((i) =&gt; {
      expect(() =&gt; {
        calculateFinalYearGPA(i);
      }).toThrow();
    });
  });
});

</code></pre>
<p>So, now I need to add some defensive programming code to my production code.</p>
<pre class=""lang-js prettyprint-override""><code>if (gradings.constructor !== Array)
    throw new Error(`Expected to get an array, got ${typeof gradings}.`);
</code></pre>
<p>The way I'm doing is correct? Should I test the <code>gradings</code> array has the proper structure as well? If so, I need to add some code that nothing with business logic is done but check the <code>gradings</code> array's structure. My production code will populate with that kind of code. Is it supposed to be?</p>
<p>What is the proper ways to test my <code>calculateFinalYearGPA.js</code>?</p>
",https://stackoverflow.com/questions/63643941/unit-testing-with-jest-in-node-js,"['javascript', 'node.js', 'unit-testing', 'jestjs']",426,True,3,1
What to do when your commit fails GitHub checks?,"<p>Okay, I just learned about unit testing, GitHub checks with CircleCI and pull requests all in a day. I ran into a question as I was trying to test my understanding of everything:</p>
<ol>
<li>I've got a repository locally and it is set to push changes to my
repo on GitHub.</li>
<li>I've got some basic tests written that pass <code>pytest</code> test runner locally.</li>
<li>I make some simple change to test everything, commit and push the change.</li>
<li>I go to GitHub and see that I did not pass my tests defined in my CircleCI YAML file because I don't have flake8 installed in my virtual environment (I accidentally installed it globally).</li>
<li>I return to PyCharm and install flake8 in my venv.</li>
<li>I update my <code>requirements.txt</code> to reflect the install.</li>
<li><strong>???</strong></li>
</ol>
<p>Now, my question is this: When a check fails, what is the best practice for 'updating' the pull request after fixing the issue. Do I just make a new commit that fixes it and start a new pull request? Or, do I find a way to revert the old commit to include the new version that works?</p>
",https://stackoverflow.com/questions/63295363/what-to-do-when-your-commit-fails-github-checks,"['git', 'github', 'continuous-integration', 'circleci']",1678,True,2,1
Use Jest to mock &quot;import *&quot;,"<p>I have a TypeScript source file that has the following import:</p>

<pre><code>// myCode.ts
import * as x from 'dep';
... 
export class myClass {
   ...
}
</code></pre>

<p>where <code>dep</code> is a Node package that's included as part of the npm install.  <code>myCode.ts</code> is a simple class that just has three methods.  I would like to mock the entire <code>myClass</code> from inside a Jest test script that is written to test another class, <code>myMainClass</code>.</p>

<p>The problem I'm having is that the <code>dep</code> code is running some initialization that I can't seem to bypass.  The initialization code fails outside the ""real"" environment so I simply want to bypass this for test purposes.  No matter what I try I get an error that looks something like this:</p>

<pre><code>  Test suite failed to run

    Dynamic Linking Error: ... error text ...

      5 | // myCode.js
    &gt; 6 | import * as x from 'dep';
        | ^
</code></pre>

<p>Again, the error is expected since I don't have these libraries locally (and don't want them for  unit testing).</p>

<p>I was hoping I could add a simple mock statement (e.g., <code>jest.mock('myClass')</code>, or something similar, that would bypass anything to do with <code>myClass</code>.  That way the code causing the link error would not be executed.</p>

<p>I'm fairly new to using Jest.  Hopefully, this is a simple ask and I'm just missing the obvious.  Thanks for the help.</p>
",https://stackoverflow.com/questions/62349952/use-jest-to-mock-import,"['jestjs', 'ts-jest']",212,False,2,0
Is there a way to mock only part of an object in Dart with Mockito?,"<p>I am currently trying to develop test-driven with Flutter and Dart.
I have an object that has two methods of which the first one does an http call and the second one calls the first method. 
In order to test the first function I mock the dependencies of the that function (namely the http call).</p>

<p>Now I want to test the second method, but I was not able to find a way to mock only the first function while keeping the rest of the object intact. As a result I can only mock the dependencies of the first method <em>again</em> which results in the entire function being executed all over. This goes against the whole purpose of unit testing.</p>

<p>It seems like there is only an all or nothing approach when it comes to mocking objects. I wonder how one is to go about a case where some object is reliant on methods on the same object. 
Using <code>Fake</code> and <code>Mock</code> does not allow me to call the original method. <code>spy</code> is deprecated and assigning a mock function to one of the functions does not work since Dart does not allow me to reassign a method.</p>
",https://stackoverflow.com/questions/62047134/is-there-a-way-to-mock-only-part-of-an-object-in-dart-with-mockito,"['unit-testing', 'flutter', 'testing', 'dart', 'mockito']",2402,True,10,1
Best practices for React project structure?,"<p>I have been doing quite a bit of research into the best way to organize files/ folders for large React applications (using things like custom Hooks, Redux, GraphQl, unit testing, styled-components, etc). I see most people are doing it in slightly different ways. Colocation of files seems like a good idea to me. </p>

<p>But I came across a kind of tradeoff between colocation vs. function-centric organization. If we simply locate all relevant files within a component folder, other developers can easily overlook potentially reusable code and simply rewrite the logic. This is especially a problem when developers are given full responsibility for a particular component/ feature and are not familiar with the entire codebase. It limits the potential for reusability. In such a case it would make sense to have some global folders (e.g. for API interaction logic, utilities, etc.) but this goes towards a more function-centric folder organization. </p>

<p>Has anyone encountered this problem and if so could you share your best practices for a React folder structure?  </p>
",https://stackoverflow.com/questions/60703378/best-practices-for-react-project-structure,['reactjs'],1246,False,2,1
Jest - test jquery fadeIn/fadeOut on specific elements,"<p>I'm trying to write some test for a web app I'm building using jquery. I have some functions that fade some elements in an out, and would like to ensure this elements are being displayed as expected. I'm using jest for testing, but I have not figured out how to see if <code>$(...).fadeIn()</code> or <code>$(...).fadeOut()</code> are being called on specific elements. Here's an example</p>

<p>Let's say this is the dom</p>

<pre class=""lang-html prettyprint-override""><code>&lt;div&gt;
 &lt;span id=""show-this"" style=""display: none""&gt;&lt;/span&gt;
 &lt;span id=""hide-this""&gt;&lt;/span&gt;
&lt;/div&gt;
</code></pre>

<p>and this is the function I want to test</p>

<pre class=""lang-js prettyprint-override""><code>function showAndHide() {
  $('#show-this').fadeIn();
  $('#hide-this').fadeOut();
}
</code></pre>

<p>currently the best test I've been able to do is spy on <code>fadeIn</code> and <code>fadeOut</code> and see if they're been called. </p>

<pre class=""lang-js prettyprint-override""><code>it('should display the element', () =&gt; {
  const spyFadeIn = jest.spyOn($.fn, 'fadeIn');
  showAndHide();
  expect(spyFadeIn).toHaveBeenCalled();
});

it('should hide the element', () =&gt; {
  const spyFadeOut = jest.spyOn($.fn, 'fadeOut');
  showAndHide();
  expect(spyFadeOut).toHaveBeenCalled();
});
</code></pre>

<p>This is a good workaround, but in situations like this wont work, because the tests would pass if I fadeOut the <code>#show-this</code> and fadeIn the <code>#hide-this</code>, which I wish to cause a test fail. I tried checking the arguments of the function, since I know under the scene this functions receive the element as an argument, but jest is not seeing that. Any thoughts? I got stuck on my unit testing because of this.</p>
",https://stackoverflow.com/questions/61295452/jest-test-jquery-fadein-fadeout-on-specific-elements,"['jquery', 'unit-testing', 'jestjs', 'fadein', 'fadeout']",372,False,2,1
"Jpa is getting inconsistent data, from MySQL database","<p>I am using Jpa in order to communicate with database, but the data I am taking in inconsistent. I have a user class that has a OneToOne relationship with a Teacher class.</p>

<pre><code>@OneToOne(mappedBy=""user"")
private Teacher teacher; // From user class

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name=""user_id"", referencedColumnName=""id"")
private User user;  // from the teacher class
</code></pre>

<p>I am saving a teacher in the following way:</p>

<pre><code>public Teacher save(Teacher teacher, Long id)
{
    User user;
    Optional&lt;User&gt; ifUser = userRepo.findById(id);
    if(ifUser.isPresent()) {
        user= ifUser.get();
        user.setTeacher(teacher);
        user.setCompletedInfo(1);
        teacher.setUser(user);
        return teacherRepo.save(teacher);
    }else {
        System.out.println(""Couldn't find any user here..."");
        return null;
    }
}
</code></pre>

<p>Where userRepo and teacherRepo are interfaces that extend from JpaRepository. Until now it works pretty cool. The information gets updated in the database. But when I get the info from the database, it shows me that</p>

<pre><code> user.getCompletedInfo()
</code></pre>

<p>is null. Meanwhile I can see in the database that that value:</p>

<pre><code>user.getCompletedInfo() =1;
</code></pre>

<p>The database is MySql, and a possible approach to the problem I would think is that I am getting some info from a new User Object that is being created somewhere.
For more the project is in Github: <a href=""https://github.com/shpendpalushi/JavaWeb/tree/For_Project"" rel=""nofollow noreferrer"">https://github.com/shpendpalushi/JavaWeb/tree/For_Project</a></p>

<p>Edit:
From some Unit testing I was able to find that in the teacher service setUser wasn't  doing it's job properly. When I tried to getUser it returned me a null;
Am I doing something wrong in the save method?</p>
",https://stackoverflow.com/questions/59605707/jpa-is-getting-inconsistent-data-from-mysql-database,"['java', 'mysql', 'hibernate', 'spring-boot', 'jpa']",235,True,2,1
How do I write SQLAlchemy test fixtures for FastAPI applications,"<p>I am writing a <a href=""https://fastapi.tiangolo.com/"" rel=""noreferrer"">FastAPI</a> application that uses a SQLAlchemy database. I have copied the <a href=""https://fastapi.tiangolo.com/tutorial/sql-databases/"" rel=""noreferrer"">example from the FastAPI documentation</a>, simplifying the database schema for concisions' sake. The complete source is at the bottom of this post.</p>
<p>This works. I can run it with <code>uvicorn sql_app.main:app</code> and interact with the database via the Swagger docs. When it runs it creates a <code>test.db</code> in the working directory.</p>
<p>Now I want to add a unit test. Something like this.</p>
<pre class=""lang-py prettyprint-override""><code>from fastapi import status
from fastapi.testclient import TestClient
from pytest import fixture

from main import app


@fixture
def client() -&gt; TestClient:
    return TestClient(app)


def test_fast_sql(client: TestClient):
    response = client.get(&quot;/users/&quot;)
    assert response.status_code == status.HTTP_200_OK
    assert response.json() == []
</code></pre>
<p>Using the source code below, this takes the <code>test.db</code> in the working directory as the database. Instead I want to create a new database for every unit test that is deleted at the end of the test.</p>
<p>I could put the global <code>database.engine</code> and <code>database.SessionLocal</code> inside an object that is created at runtime, like so:</p>
<pre class=""lang-py prettyprint-override""><code>    class UserDatabase:
        def __init__(self, directory: Path):
            directory.mkdir(exist_ok=True, parents=True)
            sqlalchemy_database_url = f&quot;sqlite:///{directory}/store.db&quot;
            self.engine = create_engine(
                sqlalchemy_database_url, connect_args={&quot;check_same_thread&quot;: False}
            )
            self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
            models.Base.metadata.create_all(bind=self.engine)
</code></pre>
<p>but I don't know how to make that work with <code>main.get_db</code>, since the <code>Depends(get_db)</code> logic ultimately assumes <code>database.engine</code> and <code>database.SessionLocal</code> are available globally.</p>
<p>I'm used to working with Flask, whose unit testing facilities handle all this for you. I don't know how to write it myself. Can someone show me the minimal changes I'd have to make in order to generate a new database for each unit test in this framework?</p>
<hr />
<p>The complete source of the simplified FastAPI/SQLAlchemy app is as follows.</p>
<p><strong>database.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = &quot;sqlite:///./test.db&quot;

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={&quot;check_same_thread&quot;: False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
</code></pre>
<p><strong>models.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>from sqlalchemy import Column, Integer, String

from database import Base


class User(Base):
    __tablename__ = &quot;users&quot;

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    age = Column(Integer)
</code></pre>
<p><strong>schemas.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>from pydantic import BaseModel


class UserBase(BaseModel):
    name: str
    age: int


class UserCreate(UserBase):
    pass


class User(UserBase):
    id: int

    class Config:
        orm_mode = True
</code></pre>
<p><strong>crud.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>from sqlalchemy.orm import Session

import schemas
import models


def get_user(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.id == user_id).first()


def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()


def create_user(db: Session, user: schemas.UserCreate):
    db_user = models.User(name=user.name, age=user.age)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
</code></pre>
<p><strong>main.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>from typing import List

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session

import schemas
import models
import crud
from database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()


# Dependency
def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()


@app.post(&quot;/users/&quot;, response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    return crud.create_user(db=db, user=user)


@app.get(&quot;/users/&quot;, response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_users(db, skip=skip, limit=limit)
    return users


@app.get(&quot;/users/{user_id}&quot;, response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail=&quot;User not found&quot;)
    return db_user
</code></pre>
",https://stackoverflow.com/questions/60711576/how-do-i-write-sqlalchemy-test-fixtures-for-fastapi-applications,"['sqlalchemy', 'fastapi', 'test-fixture']",10237,True,17,1
Advice on testing Angular $localize (Angular 9),"<p><strong>Example repo</strong></p>

<p>The repo can be found <a href=""https://github.com/ross-moug/ng9-i18n-unit-test"" rel=""nofollow noreferrer"">here</a>.</p>

<p>Please note that this isn't a complete example, it is merely there to show issues around testing <code>$localize</code>.</p>

<p>There are 2 branches:
 1. <code>master</code>
 1. <code>enable-localize-unit-tests</code> - this changes the <code>test.ts</code> and <code>polyfills.ts</code> to prevent the <code>@angular/localize/init</code> from being imported, the <code>$localize</code> global function is also spied</p>

<p><strong>Overview</strong></p>

<p>I have upgraded a project from Angular 8 to 9 (following the <a href=""https://update.angular.io/"" rel=""nofollow noreferrer"">Angular update guide</a>), replacing any usage the <a href=""https://github.com/ngx-translate/i18n-polyfill/blob/master/lib/src/i18n-polyfill.ts#L37"" rel=""nofollow noreferrer""><code>I18n</code></a> service (from the ngx-translation/i18n-polyfill) with Angular's new <code>$localize</code> function (documentation on this is pretty limited, <a href=""https://blog.ninja-squad.com/2019/12/10/angular-localize/"" rel=""nofollow noreferrer"">here</a> is the best I could find). I can run localised builds and serve the application in a particular locale again. However, I've hit a bit of a roadblock when it comes to unit testing.</p>

<p>Previously, when using the <code>i18n-polyfill</code>, the <code>I18n</code> service could be injected into components, etc. as follows (see <a href=""https://github.com/ross-moug/ng9-i18n-unit-test/tree/master/src/app/i18n-polyfill"" rel=""nofollow noreferrer""><code>I18nPolyfillComponent</code></a>):</p>

<pre class=""lang-js prettyprint-override""><code>@Component({
  selector: ""app-i18-polyfill"",
  template: `&lt;h4&gt;{{ title }}&lt;/h4&gt;
})
export class I18nPolyfillComponent {
  readonly title: string = this.i18n({
    id: ""title"",
    value: ""Hello World!""
  });

  constructor(private i18n: I18n) {}
}
</code></pre>

<p>This could easily tested by injecting a spy into the component:</p>

<pre class=""lang-js prettyprint-override""><code>describe(""I18nPolyfillComponent"", () =&gt; {
 let component: I18nPolyfillComponent;
 let fixture: ComponentFixture&lt;I18nPolyfillComponent&gt;;

  let mockI18n: Spy;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ I18nPolyfillComponent ],
      providers: [
        {
          provide: I18n,
          useValue: jasmine.createSpy(""I18n""),
        },
      ],
    })
      .compileComponents().then(() =&gt; {
        mockI18n = TestBed.inject(I18n) as Spy;
    });
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(I18nPolyfillComponent);
    component = fixture.componentInstance;

    mockI18n.and.callFake((def: I18nDef) =&gt; def.value);
  });

  it(""should call i18n once"", () =&gt; {
    expect(mockI18n).toHaveBeenCalledTimes(1);
  });
});
</code></pre>

<p>However, I am unsure if similar unit tests could be written to test the usage of <code>$localize</code> as it is a global function rather than an injectable service.</p>

<p>For completeness the component would look like this using <code>$localize</code> (see <a href=""https://github.com/ross-moug/ng9-i18n-unit-test/tree/master/src/app/i18n-localize"" rel=""nofollow noreferrer""><code>I18nLocalizeComponent</code></a>):</p>

<pre class=""lang-js prettyprint-override""><code>@Component({
  selector: ""app-i18n-localize"",
  template: `&lt;h4&gt;{{ title }}&lt;/h4&gt;
})
export class I18nLocalizeComponent {
  readonly title: string = $localize `:@@title:Hello World!`;
}
</code></pre>

<p><strong>Testing rationale</strong></p>

<p>I would like to ensure that my applications are interacting with <code>I18n</code>/<code>$localize</code> appropriately (called the correct number of times, with correct parameters, etc.). This just prevent silly errors if someone accidentally changes a trans-unit ID or the base translations value.</p>

<p><strong>What I've tried</strong></p>

<p>I have tried to replace the global <code>$localize</code> function with a spy in <code>test.ts</code> and avoiding importing <code>@angular/localize/init</code>:</p>

<pre class=""lang-js prettyprint-override""><code>import Spy = jasmine.Spy;
import createSpy = jasmine.createSpy;

const _global: any = typeof global !== ""undefined"" &amp;&amp; global;

_global.$localize = createSpy(""$localize"");

declare global {
  const $localize: Spy;
}
</code></pre>

<p>And then using the spied <code>$localize</code> in the tests (see :</p>

<pre class=""lang-js prettyprint-override""><code>describe(""I18nLocalizeComponent"", () =&gt; {
 let component: I18nLocalizeComponent;
 let fixture: ComponentFixture&lt;I18nLocalizeComponent&gt;;

  let mockI18n: Spy;

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

  beforeEach(() =&gt; {
    $localize.calls.reset();
    $localize.and.returnValue(""Hello World!);

    fixture = TestBed.createComponent(I18nLocalizeComponent);
    component = fixture.componentInstance;
  });

  it(""should call $localize once"", () =&gt; {
    expect($localize).toHaveBeenCalledTimes(1);
  });
});

</code></pre>

<p>The spy does work but tests will fail if the component, or another component, uses the <code>i18n</code> directives in it's template, for example (<a href=""https://github.com/ross-moug/ng9-i18n-unit-test/tree/master/src/app/i18n-localize-template"" rel=""nofollow noreferrer""><code>I18nLocalizeTemplateComponent</code></a>):</p>

<pre class=""lang-html prettyprint-override""><code>&lt;p i18n&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean consequat.&lt;/p&gt;
</code></pre>

<p>This will fail with the following error:</p>

<pre><code>TypeError: Cannot read property 'substr' of undefined
        at &lt;Jasmine&gt;
        at removeInnerTemplateTranslation (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:34560:1)
        at getTranslationForTemplate (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:34582:1)
        at i18nStartFirstPass (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:34771:1)
        at ɵɵi18nStart (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:34718:1)
        at ɵɵi18n (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:35450:1)
        at I18nLocalizeTemplateComponent_Template (ng:///I18nLocalizeTemplateComponent.js:15:9)
        at executeTemplate (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11949:1)
        at renderView (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11735:1)
        at renderComponent (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:13244:1)
        at renderChildComponents (http://localhost:9877/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11538:1)
    Error: Expected undefined to be truthy.
        at &lt;Jasmine&gt;
        at UserContext.&lt;anonymous&gt; (http://localhost:9877/_karma_webpack_/src/app/i18n-localize-template/i18n-localize-template.component.spec.ts:23:23)
        at ZoneDelegate.invoke (http://localhost:9877/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
        at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9877/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292:1)
</code></pre>

<p>Does anyone have any advice on how to handle this use case or is it currently not supported? I haven't seen any documentation, tutorials or articles which help with this so any assistance would be greatly appreciated.</p>

<p>To recreate the issue above in the example repo you'd have to:</p>

<ol>
<li>Uncomment code in <code>test.ts</code></li>
<li>Comment out import from <code>@angular/localize/init</code> in <code>polyfills.ts</code></li>
<li>Run tests for <code>I18nLocalizeTemplateComponent</code></li>
</ol>

<p>The tests could be executed by using <code>npm run test -- --include src/app/i18n-localize-template/i18n-localize-template.component.spec.ts</code></p>

<p>Alternatively, use <a href=""https://github.com/ross-moug/ng9-i18n-unit-test/tree/enable-localize-unit-tests"" rel=""nofollow noreferrer""><code>enable-localize-unit-tests</code></a> branch then follow step 3.</p>

<p><strong>Notes</strong></p>

<ol>
<li>The following has been added to <code>polyfills.ts</code> for the project as per Angular upgrade guide:

<pre class=""lang-js prettyprint-override""><code>import ""@angular/localize/init"";
</code></pre></li>
<li>I'm currently using Karma (<code>4.4.1</code>) and Jasmine (<code>3.5.9</code>) for unit testing</li>
</ol>

<p><strong>Environment details</strong></p>

<pre><code>     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 9.0.6
Node: 13.2.0
OS: darwin x64

Angular: 9.0.6
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, localize, platform-browser
... platform-browser-dynamic, router
Ivy Workspace: Yes

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.900.6
@angular-devkit/build-angular      0.900.6
@angular-devkit/build-ng-packagr   0.900.6
@angular-devkit/build-optimizer    0.900.6
@angular-devkit/build-webpack      0.900.6
@angular-devkit/core               9.0.6
@angular-devkit/schematics         9.0.6
@angular/cdk                       9.1.3
@ngtools/webpack                   9.0.6
@schematics/angular                9.0.6
@schematics/update                 0.900.6
ng-packagr                         9.0.3
rxjs                               6.5.4
typescript                         3.7.5
webpack                            4.41.2
</code></pre>
",https://stackoverflow.com/questions/60847354/advice-on-testing-angular-localize-angular-9,"['angular', 'unit-testing', 'angular-i18n']",3770,True,2,4
Difference between Firebase service account key files from Firebase and from GCloud?,"<p>I am running scripts to interact with Firestore (e.g. creating a doc). I've provided a service account key file to do so (tried with key files from Firebase and GCloud) - scripts run the same.</p>

<p>I am aware that Firebase is now built / closely linked to GCloud so I am expecting the key files to be similar.</p>

<p>However, the docs recommend initializing the sdk with a key from Firebase console when <a href=""https://firebase.google.com/docs/admin/setup#initialize-sdk"" rel=""nofollow noreferrer"">adding Firebase admin to your server</a> and from GCloud Console for <a href=""https://firebase.google.com/docs/functions/unit-testing#online-mode"" rel=""nofollow noreferrer"">unit testing</a>. </p>

<p>So here are my questions:</p>

<ul>
<li>Why recommend 2 different ways to generate them? Is one more appropriate than the other?</li>
<li>Do service account key files generated in Firebase (1) and GCloud (2) consoles differ in terms of scope? Do they allow the same operations? Are they granted equivalent permissions?</li>
</ul>

<hr>

<ol>
<li><p>Firebase Console > Project Settings > Service Accounts > Firebase Admin SDK > Create new private key
<a href=""https://console.firebase.google.com/project/[my-project-id]/settings/serviceaccounts/adminsdk"" rel=""nofollow noreferrer"">https://console.firebase.google.com/project/[my-project-id]/settings/serviceaccounts/adminsdk</a></p></li>
<li><p>Google Cloud Console > IAM &amp; Admin > Service Accounts > App Engine default service account > Create key
<a href=""https://console.cloud.google.com/iam-admin/serviceaccounts?project=[my-project-id]"" rel=""nofollow noreferrer"">https://console.cloud.google.com/iam-admin/serviceaccounts?project=[my-project-id]</a></p></li>
</ol>
",https://stackoverflow.com/questions/60366130/difference-between-firebase-service-account-key-files-from-firebase-and-from-gcl,"['firebase', 'google-cloud-platform']",613,True,1,1
Returning 2 different values using using a mock service while unit testing in Angular,"<p>Summary of the issue :</p>

<p><strong>How to call multiple values using the same service inside the same test spec and check to see if it works exactly as in the component?</strong></p>

<p>I am using Angular7+.</p>

<p>Let there be a component ( say A ) with a service injected into it.</p>

<p>Suppose , there is a <strong>getNumber</strong> function in the same <strong>service</strong> with 2 parameters namely <strong>( ""Key"" , ""Value"" )</strong> where ""Key"" can only be either <strong>num1</strong> or <strong>num2</strong> and ""Value"" can be any <strong>integer</strong>.</p>

<p>This function returns an object in this format : <strong>{ ""Key"" : num1 or num2 , ""Value"" : number }</strong> and this object is stored in another object ( say <strong>Total</strong> ) as its elements. Example : </p>

<pre><code>export class A implements OnInit{
 Total={""sum"":[""num1"",""num2""],""amount"":0};

 constructor(private service: SomeService) {}
    ngOnInit(){
        this.loadFunc();
    }

    private loadFunc(){
        this.service.getNumber(""num1"",12).subscribe(res =&gt;{
                Total[res.Key] = res.Value;
        },err=&gt;{
            console.log(err);
        });

        this.service.getNumber(""num2"",13).subscribe(res =&gt;{
                Total[res.Key] = res.Value;
        },err=&gt;{
            console.log(err);
        });

        this.calculate();
    }

    private calculate(){
        //For elements in Total.sum array iterate over them and store the value in any other key say amount.
        for(const keys of Total[""sum""]){
            if(Total[keys]){
                Total[""amount""] += Total[keys];
            }
        }
        console.log(Total[""amount""]);      // Outputs to 25
    }
}

So Total would become : 
Total = { ""num1"":12 , ""num2"":13 ,""sum"":[""num1"",""num2""],""amount"":25};
</code></pre>

<p>Now in <strong>unit testing</strong> the component with the service, i have a mockService stub with a getNumber function and i am doing something like this :</p>

<pre><code>mockServiceStub = jasmine.createSpyObj(['getNumber']); // done before testbed.createComponent()

// Inside Test
mockServiceStub.getNumber.and.returnValue(of({""Key"":""num1"", ""Value"":12}));
fixture.ngOnInit();
console.log(component.Total.amount); // outputs 12

mockServiceStub.getNumber.and.returnValue(of({""Key"":""num2"", ""Value"":13}));
fixture.ngOnInit();
console.log(component.Total.amount); // outputs 13
expect(component.Total.sum).toEqual(25); // throws error 'Expected 13 to equal 25'
</code></pre>

<p>I actually wanted both the values to combine i.e in my test,
i first gave a return value of 12 with "" num1 "" as key and then 13 with "" num2 "" as key, and i expected the output to be 25 ( 12 + 13 ).</p>
",https://stackoverflow.com/questions/61719672/returning-2-different-values-using-using-a-mock-service-while-unit-testing-in-an,"['angular', 'unit-testing', 'observable']",4117,True,1,2
Using Pyspark locally when installed using databricks-connect,"<p>I have databricks-connect 6.6.0 installed, which has a Spark version 2.4.6. I have been using the databricks cluster till now, but I am trying to switch to using a local spark session for unit testing.
However, every time I run it, it still shows up on the cluster Spark UI as well as the local Spark UI on xxxxxx:4040.</p>
<p>I have tried initiating using SparkConf(), SparkContext(), and SQLContext() but they all do the same thing. I have also set the right SPARK_HOME, HADOOP_HOME, and JAVA_HOME, and downloaded winutils.exe separately, and none of these directories have spaces. I have also tried running it from console as well as from terminal using spark-submit.</p>
<p>This is one of the pieces of sample code I tried:</p>
<pre><code>from pyspark.sql import SparkSession

spark = SparkSession.builder.master(&quot;local&quot;).appName(&quot;name&quot;).getOrCreate()
inp = spark.createDataFrame([('Person1',12),('Person2',14)],['person','age'])
op = inp.toPandas()
</code></pre>
<p>I am using:
Windows 10, databricks-connect 6.6.0, Spark 2.4.6, JDK 1.8.0_265, Python 3.7, PyCharm Community 2020.1.1</p>
<p>Do I have to override the default/global spark session to initiate a local one? How would I do that?
I might be missing something - The code itself runs fine, it's just a matter of local vs. cluster.</p>
<p>TIA</p>
",https://stackoverflow.com/questions/64721130/using-pyspark-locally-when-installed-using-databricks-connect,"['python-3.x', 'pyspark', 'databricks', 'databricks-connect']",552,True,1,1
Deprecation errors on GitLab CI when testing F3 request mock using PHPUnit,"<p>I'm attempting to setup unit testing with PHPUnit 9.5 on my GitLab repo. The codebase is PHP 7.3, and I'm using Fat-Free Framework v3.7. Because the web app uses sessions, setting up a test to call <code>$f3-&gt;mock()</code> results in an error about headers already being sent, which makes sense since the session info is communicated via HTTP headers. I'm not aware of a way to get around this without editing the F3 code itself, but if anyone knows of a way, then everything below can probably be ignored.</p>
<p>It seems a fairly common consensus online to run such tests with the <code>@runInSeparateProcess</code> flag, so I've tried adding that. However, now when the test runs in GitLab, I get the following error:</p>
<pre><code>   │ PHPUnit\Framework\Exception: Fatal error: ini_set(): Use of mbstring.internal_encoding is deprecated
   │ [Standard input code:93]
</code></pre>
<p>Just for debugging purposes, I added <code>php --ini</code> to my provisioning script for GitLab CI to find the PHP INI files, which gave me:</p>
<pre><code>+ php --ini
Configuration File (php.ini) Path: /usr/local/etc/php
Loaded Configuration File:         (none)
Scan for additional .ini files in: /usr/local/etc/php/conf.d
Additional .ini files parsed:      /usr/local/etc/php/conf.d/docker-php-ext-pdo_mysql.ini,
/usr/local/etc/php/conf.d/docker-php-ext-sodium.ini,
/usr/local/etc/php/conf.d/docker-php-ext-zip.ini
</code></pre>
<p>So then I added <code>grep -r &quot;mbstring.internal_encoding&quot; /usr/local/etc/php/</code> and got:</p>
<pre><code>+ grep -r mbstring.internal_encoding /usr/local/etc/php/
/usr/local/etc/php/php.ini-production:;mbstring.internal_encoding =
/usr/local/etc/php/php.ini-production:; mbstring.internal_encoding setting. Input chars are
/usr/local/etc/php/php.ini-production:; given by corresponding encode setting. When empty mbstring.internal_encoding
/usr/local/etc/php/php.ini-development:;mbstring.internal_encoding =
/usr/local/etc/php/php.ini-development:; mbstring.internal_encoding setting. Input chars are
/usr/local/etc/php/php.ini-development:; given by corresponding encode setting. When empty mbstring.internal_encoding
</code></pre>
<p>Unless I'm mistaken, all of those look like they're commented out, so now I have no idea where to go to override the use of <code>mbstring.internal_encoding</code>.</p>
<h3>Applicable File Excerpts:</h3>
<p><code>.gitlab-ci.yml</code>:</p>
<pre class=""lang-yaml prettyprint-override""><code>image: php:7.4

before_script:
  - bash tests/docker_install.sh

test:app:
  script:
    - app/vendor/bin/phpunit --bootstrap tests/bootstrap.php --testdox --colors tests
</code></pre>
<p><code>composer.json</code>:</p>
<pre class=""lang-json prettyprint-override""><code>{
    &quot;require&quot;: {
        &quot;bcosca/fatfree&quot;: &quot;^3.7&quot;,
        &quot;phpmailer/phpmailer&quot;: &quot;^6.1&quot;,
        &quot;google/recaptcha&quot;: &quot;^1.2&quot;,
        &quot;firebase/php-jwt&quot;: &quot;^5.2&quot;,
        &quot;google/cloud-iot&quot;: &quot;^1.1&quot;,
        &quot;google/apiclient&quot;: &quot;^2.7&quot;,
        &quot;google/cloud-secret-manager&quot;: &quot;^1.0&quot;
    },
    &quot;require-dev&quot;: {
        &quot;phpunit/phpunit&quot;: &quot;^9&quot;,
        &quot;phpunit/php-code-coverage&quot;: &quot;^9.2&quot;
    }
}
</code></pre>
<p><code>tests/docker_install.sh</code>:</p>
<pre class=""lang-sh prettyprint-override""><code>#!/bin/bash

# we need to install dependencies only for Docker
[[ ! -e /.dockerenv ]] &amp;&amp; exit 0

set -xe

# install required stuff that doesn't come with the image
apt-get update -yqq &gt; /dev/null
apt-get install git libonig-dev zip unzip libzip-dev -yqq &gt; /dev/null

# install php # install php requirements
docker-php-ext-install pdo_mysql zip &gt; /dev/null

# setup and install composer
curl -sS https://getcomposer.org/installer | php
php composer.phar install
</code></pre>
<p><code>tests/bootstrap.php</code>:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php
error_reporting(E_ALL &amp; ~E_USER_DEPRECATED &amp; ~E_NOTICE &amp; ~E_STRICT &amp; ~E_DEPRECATED);

require __DIR__.'/../app/vendor/autoload.php';
require __DIR__.'/../app/App.php';
require __DIR__.'/TestBase.php';

\App\App::instance()-&gt;testingBootstrap();
</code></pre>
<p><code>tests/ExampleTest.php</code>:</p>
<pre><code>&lt;?php
class ExampleTest extends \PHPUnit\Framework\TestCase {
    /**
     * @runInSeparateProcess
     */
    public function testPingResponse() {
        $f3 = \Base::instance();
        $this-&gt;assertNull($f3-&gt;mock('GET /ping'));
        $this-&gt;assertStringContainsString('alive', $f3-&gt;RESPONSE);
    }
}
</code></pre>
",https://stackoverflow.com/questions/65352995/deprecation-errors-on-gitlab-ci-when-testing-f3-request-mock-using-phpunit,"['php', 'phpunit', 'gitlab-ci', 'fat-free-framework']",209,False,1,0
Moq Test - Mocked Service Call Always Returns Null,"<p>I am new to Moq and Mocks/Unit Testing in general. After watching <a href=""https://www.youtube.com/watch?v=DwbYxP-etMY"" rel=""nofollow noreferrer"">a video on Mocking which uses Moq</a>, I thought I had enough understanding to start setting up a few simple tests for a project I am working on.  However, no amount of fiddling with the code helps my first test pass.</p>

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

<p><strong>Interface Being Tested</strong></p>

<pre><code>    public interface IDataInterface
    {
        Task&lt;IList&lt;T&gt;&gt; GetData&lt;T&gt;(string url);
        // Other stuff
    }
</code></pre>

<p><strong>Implementation of Interface Method GetData&lt;T&gt;</strong></p>

<pre><code>        public async Task&lt;IList&lt;T&gt;&gt; GetData&lt;T&gt;(string url)
        {
            try
            {
                var json = await client.GetAsync(url).Result.Content.ReadAsStringAsync();
                var data = (JObject)JsonConvert.DeserializeObject(json);
                JArray arr = (JArray)data[""resource""];
                return arr.ToObject&lt;IList&lt;T&gt;&gt;();
            }
            catch (InvalidCastException icEx)
            {
                throw new InvalidCastException(""An error occurred when retrieving the data"", icEx);
            }
            // Other catches
        }
</code></pre>

<p><strong>Service Calling Implemented Interface GetData&lt;T&gt;</strong></p>

<pre><code>        public async Task&lt;IList&lt;MyObj&gt;&gt; GetActiveObjs()
        {
            var data = await _myImplementedInterface.GetData&lt;MyObj&gt;(ActiveUrl);
            return data;
        }
</code></pre>

<p><strong>My Test</strong></p>

<pre><code>        [Fact]
        public async void MyImplementedInterface_GetActive_ReturnsDataOrEmptyList()
        {
            var _activeUrl = ""http://some.url"";
            using (var mock = AutoMock.GetLoose())
            {
                mock.Mock&lt;IDataInterface&gt;()
                    .Setup(x =&gt; x.GetData&lt;MyObj&gt;(_activeUrl))
                    .Returns(Task.FromResult(_SomeStaticDataRepresentation)));

                var svc = mock.Create&lt;MyService&gt;();

                var expected = _SomeStaticDataRepresentation;
                var actual = await svc.GetActiveObjs();

                Assert.True(actual != null);
                // Other assertions that never matter because of the null value of _actual_ variable
            }
        }

</code></pre>

<p>Early on, I had issues because the project uses Autofac and Moq, but I resolved those specific issues.  However, I cannot seem to get past the null value coming back from the service call.  When running the project, the method returns data, just as expected, so I am flummoxed as to where the issue lies.  Reviewing various posts and the Moq Quickstart did not provide what I needed to solve this myself, so my hope is there is someone here who can tell me what I am doing wrong.  I apologize already as I am certain it is a newbie mistake.</p>
",https://stackoverflow.com/questions/60157166/moq-test-mocked-service-call-always-returns-null,"['c#', 'unit-testing', 'moq']",811,True,1,1
vstest.console.exe does not pick up npm packages (jest and jest-editor-support),"<p>I can run <code>jest</code> tests fine via a <code>.njsproj</code> but with a <code>.csproj</code> project and a <code>node_modules</code> located at <code>\ClientApp</code> <code>vstest.console.exe</code> does not find the packages needed.</p>
<p><a href=""https://stackoverflow.com/a/64064559/3850405"">https://stackoverflow.com/a/64064559/3850405</a></p>
<blockquote>
<p>Failed to find &quot;jest&quot; package. &quot;jest&quot; must be installed in the project
locally. Install &quot;jest&quot; locally using the npm manager via solution
explorer or with &quot;.npm install jest --save-dev&quot; via the Node.js
interactive window. Failed to find &quot;jest-editor-support&quot; package.
&quot;jest-editor-support&quot; must be installed in the project locally.
Install &quot;jest-editor-support&quot; locally using the npm manager via
solution explorer or with &quot;.npm install jest-editor-support
--save-dev&quot; via the Node.js interactive window.</p>
</blockquote>
<p>Command:</p>
<pre><code>vstest.console.exe &quot;C:\Users\Oscar\source\repos\WebApplication1\WebApplication1\WebApplication1.csproj&quot; &quot;/TestAdapterPath:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\Microsoft\NodeJsTools\TestAdapter&quot;
</code></pre>
<p>Is there some way to specify the location of either <code>package.json</code> or the <code>node_modules</code> folder? The project is using <code>.NET Core 3.1</code>.</p>
<p>I have followed this guide:</p>
<p><a href=""https://learn.microsoft.com/en-us/visualstudio/javascript/unit-testing-javascript-with-visual-studio?view=vs-2019"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/javascript/unit-testing-javascript-with-visual-studio?view=vs-2019</a></p>
<p>Added the following values to <code>PropertyGroup</code> in <code>.csproj</code>:</p>
<pre><code>&lt;JavaScriptTestFramework&gt;Jest&lt;/JavaScriptTestFramework&gt;
&lt;JavaScriptTestRoot&gt;ClientApp\src\tests\&lt;/JavaScriptTestRoot&gt;
&lt;GenerateProgramFile&gt;false&lt;/GenerateProgramFile&gt;
&lt;SpaRoot&gt;ClientApp\&lt;/SpaRoot&gt;
&lt;DefaultItemExcludes&gt;$(DefaultItemExcludes);$(SpaRoot)node_modules\**&lt;/DefaultItemExcludes&gt;
</code></pre>
<p>Tested both with and without <code>SpaRoot</code> and <code>DefaultItemExcludes</code>.</p>
<p>I have not specified <code>outdir</code> or <code>outfile</code> option in <code>tsconfig.json</code> and I have installed the NuGet <a href=""https://www.nuget.org/packages/Microsoft.JavaScript.UnitTest/"" rel=""nofollow noreferrer"">Microsoft.JavaScript.UnitTest</a>.</p>
<p>Working test from <code>.njsproj</code> after <code>jest</code> and <code>jest-editor-support</code> was installed.</p>
<p><a href=""https://i.stack.imgur.com/mVX67.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/mVX67.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/64065159/vstest-console-exe-does-not-pick-up-npm-packages-jest-and-jest-editor-support,"['javascript', 'visual-studio', 'jestjs', 'vstest']",232,False,1,0
Why does xUnit Assert.Equal function expect the actual value as second argument,"<p>XUnit is a fantastic tool for unit testing, I use it extensively in every .NET Project.</p>
<p>But, I still don't get why in the Assert.Equal function, the &quot;expected&quot; value is supposed to come first. Not doing it triggers a warning in the code.</p>
<p>Actually, it sounds more natural to say : I want to check <em>this car</em> and it's expected to be <em>red</em>, than the opposite <em>red</em> should bethe color of <em>that car</em>.</p>
<p>Furthermore, if you pass the object as first argument, the autocompletion gives you logical value for the actual parameter : in the example below, <em>cache.APIConnectionStatus</em> is an Enum, and autocomplete triggers a dropdown with all potential Enum values when writing down the assertion, which speeds up considerably the writing process.</p>
<p>Is there any logical reason for having the opposite?</p>
<p>I know this is a detail and there are many ways to disable warnings / write an extension overriding the Equal method, but in the end it looks a bit messy and/or time consuming every time I start a new project.</p>
<p><a href=""https://i.stack.imgur.com/HD5Db.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HD5Db.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/63114709/why-does-xunit-assert-equal-function-expect-the-actual-value-as-second-argument,"['c#', 'unit-testing', 'xunit.net']",1116,False,1,1
Material Table With Parent Form - Input Fields in Footer Result in &quot;No Provider for NgForm&quot; Error When running Unit Test,"<p>I have a number of child components containing a material table with a parent form (templated) defined in a parent component.  They all work fine and they all pass unit testing except for one that has input fields in the table footer.  When running unit tests on this one I get the NullInjectorError: No provider for NgForm! error.</p>

<p>This is the part of the markup containing the controls that Jasmine is having a problem with:</p>

<pre><code>            &lt;ng-container matColumnDef=""saturday""&gt;
            &lt;mat-header-cell *matHeaderCellDef&gt;Saturday&lt;/mat-header-cell&gt;
            &lt;mat-cell *matCellDef=""let exception;let i = index;"" class=""hours""&gt;
                    &lt;mat-form-field&gt;
                        &lt;input min=0  max=23.75 pattern=""^(?!0\d)\d+(?:[.](?:25|5|75|0)0*)?$"" required #today=""ngModel"" matInput [(ngModel)]=""exception.hours['saturday']"" (ngModelChange)=""updateTimesheetEntry($event,today,'saturday')"" (focus)=""focused['saturday'][i]=true"" (focusout)=""focused['saturday'][i]=false"" name=""exception-saturday{{i}}""&gt;
                        &lt;mat-error #total *ngIf=""focused['saturday'][i]""&gt;{{getErrorText(today)}}&lt;/mat-error&gt;
                    &lt;/mat-form-field&gt;
            &lt;/mat-cell&gt;
        &lt;mat-footer-cell *matFooterCellDef class=""hours""&gt;
                &lt;input type=""hidden"" max=23.75 name=""saturdayTotal"" #saturdaytotal=""ngModel"" [ngModel]=""getTotals('saturday')""&gt; 
                &lt;div *ngIf=""saturdaytotal.invalid"" class=""error""&gt;
                        {{totalError}}
                &lt;/div&gt; 
        &lt;/mat-footer-cell&gt;  
        &lt;/ng-container&gt;
</code></pre>

<p>The contents of mat-cell are fine - it's just the input in the footer that causes the test to fail.</p>

<p>Here is the spec file:</p>

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

<p>let component: AttendanceExceptionsComponent;
  let fixture: ComponentFixture;</p>

<p>beforeEach(async(() => {</p>

<pre><code>TestBed.configureTestingModule({
  imports: [AppMaterialModule, FormsModule, ReactiveFormsModule, NoopAnimationsModule],
  declarations: [AttendanceExceptionsComponent],
  providers:[
    {provide : AttendanceService, useValue: { approved : of() } } ,
    {provide : ExceptionService, useValue: { getExceptionTypes : () =&gt; { return of(); } } } ,
    {provide : PanelService, useValue: {}},
    {provide : NotificationService, useValue: {}},
    {provide : StateService, useValue: {}},

  ],
  schemas: [ NO_ERRORS_SCHEMA ]      
}).compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
</code></pre>

<p>});</p>

<p>I've tried adding NgForm to the providers </p>

<pre><code>        {provide : NgForm, useValue: &lt;NgForm&gt;{}},
</code></pre>

<p>But then I get another error: ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
              formGroup's partner directive ""formControlName"" instead. </p>

<p>As I've said, this all works fine when I run ng serve, it's just testing that throws these errors &amp; I have no way of bypassing the tests because it's built into our CI build so I am totally stuck!</p>
",https://stackoverflow.com/questions/59769081/material-table-with-parent-form-input-fields-in-footer-result-in-no-provider,"['jasmine', 'angular-material', 'karma-jasmine', 'angular-forms', 'angular-material-table']",306,True,1,1
TDD: best practices mocking stacks of objects,"<p>I'm trying to get familiar with unit testing in PHP with a small API in Lumen.
Writing the first few tests was pretty nice with the help of some tutorials but now I encountered a point where I have to mock/ stub a dependency.</p>

<p>My controller depends on a specific custom interface type hinted in the constructor.<br>
Of course, I defined this interface/implementation-binding within a ServiceProvider.</p>

<pre class=""lang-php prettyprint-override""><code>    public function __construct(CustomValidatorContract $validator)
    {
        // App\Contracts\CustomValidatorContract
        $this-&gt;validator = $validator;
    }

    public function resize(Request $request)
    {
        // Illuminate\Contracts\Validation\Validator
        $validation = $this-&gt;validator-&gt;validate($request-&gt;all());

        if ($validation-&gt;fails()) {
            $response = array_merge(
                $validation
                -&gt;errors() // Illuminate\Support\MessageBag
                -&gt;toArray(), 
                ['error' =&gt; 'Invalid request data.']
            );

            // response is global helper
            return response()-&gt;json($response, 400, ['Content-Type' =&gt; 'application/json']);
        }
    }
</code></pre>

<p>As you can see, my <code>CustomValidatorContract</code> has a method <code>validate()</code> which returns an instance of <code>Illuminate\Contracts\Validation\Validator</code> (the validation result). This in turn returns an instance of <code>Illuminate\Support\MessageBag</code> when <code>errors()</code> is called. <code>MessageBag</code> then has a <code>toArray()</code>-method.  </p>

<p>Now I want to test the behavior of my controller in case the validation fails.  </p>

<pre class=""lang-php prettyprint-override""><code>    /** @test */
    public function failing_validation_returns_400()
    {
        $EmptyErrorMessageBag = $this-&gt;createMock(MessageBag::class);
        $EmptyErrorMessageBag
            -&gt;expects($this-&gt;any())
            -&gt;method('toArray')
            -&gt;willReturn(array());

        /** @var ValidationResult&amp;\PHPUnit\Framework\MockObject\MockObject $AlwaysFailsTrueValidationResult */
        $AlwaysFailsTrueValidationResult = $this-&gt;createStub(ValidationResult::class);
        $AlwaysFailsTrueValidationResult
            -&gt;expects($this-&gt;atLeastOnce())
            -&gt;method('fails')
            -&gt;willReturn(true);
        $AlwaysFailsTrueValidationResult
            -&gt;expects($this-&gt;atLeastOnce())
            -&gt;method('errors')
            -&gt;willReturn($EmptyErrorMessageBag);

        /** @var Validator&amp;\PHPUnit\Framework\MockObject\MockObject $CustomValidatorAlwaysFailsTrue */
        $CustomValidatorAlwaysFailsTrue = $this-&gt;createStub(Validator::class);
        $CustomValidatorAlwaysFailsTrue
            -&gt;expects($this-&gt;once())
            -&gt;method('validate')
            -&gt;willReturn($AlwaysFailsTrueValidationResult);

        $controller = new ImageResizeController($CustomValidatorAlwaysFailsTrue);
        $response = $controller-&gt;resize(new Request);

        $this-&gt;assertEquals(400, $response-&gt;status());
        $this-&gt;assertEquals(
            'application/json',
            $response-&gt;headers-&gt;get('Content-Type')
        );
        $this-&gt;assertJson($response-&gt;getContent());
        $response = json_decode($response-&gt;getContent(), true);
        $this-&gt;assertArrayHasKey('error', $response);
    }
</code></pre>

<p>This is a test that runs ok - but can someone please tell me if there is a better way to write this? It doesn't feel right. 
Is this big stack of moc-objects needed because of the fact that I'm using a framework in the background? Or is there something wrong with my architecture so that this feels so ""overengineered""?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/61076077/tdd-best-practices-mocking-stacks-of-objects,"['php', 'architecture', 'phpunit', 'tdd', 'lumen']",333,True,1,2
Generic Class for return enumerated results based on Electrical Engineering formula input and condition criteria c#,"<p>I work on a program that needs to do engineering formula checking/validation.
Very similar to Unit Testing but I need something very generic so I don't have to make a ton of classes.</p>

<p><strong>I need to pass an input formula:</strong>
Example: x = input voltage, y = voltage reference to find decibel.
Equation is 20*log10(x/y)</p>

<p><strong>And validate the result for the use-case application</strong></p>

<p>Examples:
If Application can't exceed 60 decibels and value is 72 then result is fail.</p>

<p>I have so many of these to do that it would be nice to have one generic class, pass in the input formula in as a Func&lt;>, then have a Dictionary&lt;[criteria],Enum.ResultType]> (or something) that will return the results for that application.</p>

<p>Here's what I was thinking/needing:</p>

<p><strong>Non-working code, just to illustrate concept</strong></p>

<pre><code>public enum CiteriaCheckResult
    {
        Inconclusive,
        Fail,
        Warning,
        Pass
    }

//T is the return type of the specific engineering formula
public class CriteriaCheck&lt;T&gt; 
        {
            public Dictionary&lt;?, CiteriaCheckResult&gt; Criteria { get; set; } = new Dictionary&lt;?, CiteriaCheckResult&gt;();

            //T1 and T2 are the inputs for a specific engineering formula
            //T is the output value to test against the criteria conditions
            public CiteriaCheckResult Validate&lt;T1, T2&gt;(Func&lt;T1, T2, T&gt; input)
            {
                //nested if's?
                //switch case?
                //Criteria.FirstOrDefault(k =&gt; k.Key == input result == criteria)?

                return CiteriaCheckResult base on dictionary or other user configurable criteria type;
            }
        }
</code></pre>

<p><strong>Desired Usage:</strong></p>

<pre><code>class Program
    {
        static void Main(string[] args)
        {
            var test1 = new CriteriaCheck&lt;double&gt;();
            //add criteria for specific application
            Criteria.Add(""criteria to check against input result"", CiteriaCheckResult.Inconclusive);
            Criteria.Add(""value is &lt; [] &amp;&amp; value is &gt; []"", CiteriaCheckResult.Fail);
            Criteria.Add(""value is &lt;= Room.Value"", CiteriaCheckResult.Pass);
            Criteria.Add(""if value is &gt; -6"", CiteriaCheckResult.Warning);

            double x = 1.23;
            double y = .7549;

            //run func and return enum based on user set conditions
            Console.WriteLine($""Test 1: {test1.Validate&lt;double, double&gt;((x,y) =&gt; 20 * Math.Log10(x/y))}"");



            Console.ReadKey();
        }
    }
</code></pre>

<p>There are obviously a lot of problems with what I'm showing (like not having unique values for dictionary keys) but hopefully the intent of what I'm trying to accomplish is clear and ya'll can think of a clever way to do this.</p>
",https://stackoverflow.com/questions/62234567/generic-class-for-return-enumerated-results-based-on-electrical-engineering-form,['c#'],76,True,1,3
Changing Input properties in Angular after fixture.detectChanges() resulting in strange behaviour,"<p>Suppose there are 2 components : AppComponent and TestComponent. I am calling TestComponent using it's directive in the HTML template of AppComponent. Now TestComponent has an @Input() property ( let it be myTitle ).</p>

<p>I am doing unit testing for TestComponent only. For title, i am passing a random value in the test itself. Here is the code for the same :</p>

<p>app.component.html </p>

<pre><code>&lt;span&gt;&lt;app-test [myTitle]=""title""&gt;&lt;/app-test&gt;&lt;/span&gt;
</code></pre>

<p>app.component.ts</p>

<pre><code>@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent{
    title = {name: 'hello-world'};
}
</code></pre>

<p>test.component.html</p>

<pre><code>&lt;p&gt;test works!!{{myTitle.name}}&lt;/p&gt;
</code></pre>

<p>test.component.ts</p>

<pre><code>@Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit{
    @Input() myTitle;

    constructor(){

    }

    ngOnInit():void{
        this.myTitle.name = ""Hi!!"";
    }
}
</code></pre>

<p>test.component.spec.ts</p>

<pre><code>describe('Test component',() =&gt;{
    let temp;
    let component: TestComponent;
    let fixture: ComponentFixture&lt;TestComponent&gt;;

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

    beforeEach(()=&gt;{
        temp = {name: ""Heloooo""};
       fixture = TestBed.createComponent(TestComponent);
       component = fixture.componentInstance;
    });

    it('should check First',()=&gt;{
       component.myTitle = temp;
       console.log(component.myTitle.name);
       console.log(temp.name);

       fixture.detectChanges();

       console.log(component.myTitle.name);
       console.log(temp.name);
       expect(component.myTitle.name).toEqual(temp.name);
    });

    it('should check Second',()=&gt;{
       component.myTitle = temp;
       console.log(component.myTitle.name);
       console.log(temp.name);

       fixture.detectChanges();

       temp.name = ""Majin Buu"";
       console.log(component.myTitle.name);
       console.log(temp.name);
       expect(component.myTitle.name).toEqual(temp.name);
    });
});
</code></pre>

<p>Both the test passes and I don't know the <strong>reason</strong> why.</p>

<p>Questions: </p>

<ol>
<li><p>Here suppose the input property is a simple string instead of
an object, then the cases fail, which is what i was expecting. But
for objects it is not working.</p></li>
<li><p>The console.log which i wrote gives the following output:</p></li>
</ol>

<p>Test Case 1:</p>

<pre><code>Heloooo          
Heloooo               
Hi!!          
Hi!!      
</code></pre>

<p>Test Case 2:</p>

<pre><code>Heloooo       
Heloooo             
Majin Buu     
Majin Buu     
</code></pre>

<p>How come it is showing latest value for object.name? I thought that the object </p>

<blockquote>
  <p>temp</p>
</blockquote>

<p>is local to this scenario. </p>

<ol start=""3"">
<li>Does fixture.detectChanges() only calls ngOnInit? If no, then how does it work? And how to make sure that the test cases fail for objects too?</li>
</ol>

<p>I am new to this community, so please help me improve the question if there are any fails.</p>
",https://stackoverflow.com/questions/61143954/changing-input-properties-in-angular-after-fixture-detectchanges-resulting-in,"['angular', 'unit-testing']",917,True,1,1
How to mock actors in a cluster sharding test environment?,"<p>I have managed to setup a test environment for event sourced behaviors with akka and scala and can correctly run unit testing on self-contained actors by doing</p>

<pre class=""lang-scala prettyprint-override""><code>class CQRSActorSpec
    extends ScalaTestWithActorTestKit(
      EventSourcedBehaviorTestKit.config.withFallback(CQRSActorSpec.config)
    )
</code></pre>

<p>then creating my testkit</p>

<pre class=""lang-scala prettyprint-override""><code>private val myTestKit = EventSourcedBehaviorTestKit[Command, Event, State](system, MyActor)
</code></pre>

<p>and using it to issue commands</p>

<pre class=""lang-scala prettyprint-override""><code>val result = myTestKit.runCommand[Response](StartJob(parameters, _))
result.reply shouldBe Done
result.event shouldBe Started(parameters)
result.state shouldBe ProcessingJob
</code></pre>

<p>Now I want to unit test an actor that in its lifecycle calls another actor, this is because I'm using the saga pattern, so the actor I'm testing is the supervisor of the saga and must call the involved parties.</p>

<p>So far I managed to do the following:</p>

<pre class=""lang-scala prettyprint-override""><code>val mockParty = Behaviors.receiveMessage[Party.Command] { msg =&gt;
  val reply = msg match {
    case _ =&gt; Done
  }
  msg.replyTo ! reply
  Behaviors.same
}

ClusterSharding(system).init(Entity(Party.Key) { _ =&gt; mockParty })
</code></pre>

<p>this runs ok in the first test, but then when I have to test another, say a failure case, of course the second call will not work because there's already an entity registered in the cluster sharding and I cannot override that behavior. Also, there is no way to reset the cluster sharding.</p>

<p>Has anyone insights on how to solve this problem? Are there other utilities for testing cluster sharding that I'm not aware of? I found the documentation a bit lacking.</p>
",https://stackoverflow.com/questions/61991364/how-to-mock-actors-in-a-cluster-sharding-test-environment,"['scala', 'akka-cluster', 'akka-persistence', 'akka-testkit', 'akka-typed']",851,True,1,1
xUnit Test- all test not running on Azure when using yml configuration,"<p>I have a .NET application using .NET Framework 4.7 that includes the xUnit unit testing framework.
The application and unit test execute as expected from my local dev environment and from Azure using a .net solution build.</p>

<p>I recently added another build based on a yml file to Azure that is building the same code and executing the same unit tests, 
however, the number of unit tests being executed with the yml configuration are vastly different and nearly half of the unit test are not executed when using the yml configuration. The yml file is super simple that is the first place I started my troubleshooting efforts and will be glad to share if needed.</p>

<p>Review of the test results between the solution build versus the yml build indicated the following warning that is only in the yml unit test results:</p>

<pre><code>Warning 5/14/2020 1:46:33 PM    [MSTest][Discovery][d:\a\1\s\src\OTEMS\packages\MSTest.TestAdapter.2.1.0\build\netcoreapp1.0\Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.dll] Unable to load types from the test source 'd:\a\1\s\src\OTEMS\packages\MSTest.TestAdapter.2.1.0\build\netcoreapp1.0\Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.dll'. Some or all of the tests in this source may not be discovered.
Error: System.TypeLoadException: Method 'get_DataRow' in type 'Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.TestContextImplementation' from assembly 'Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' does not have an implementation.
</code></pre>

<p>Note the <code>\netcoreapp1.0\</code> in the path. This warning only occurs with the yml variation but the project is NOT a .net core build, and I can't seem to find where this is being referenced or if it is the actual problem.</p>
",https://stackoverflow.com/questions/61807509/xunit-test-all-test-not-running-on-azure-when-using-yml-configuration,"['c#', 'azure', 'unit-testing', 'xunit']",150,False,0,0
How to correctly implement Vue.js tests?,"<p>I'm confused about testing my Vue.js application.
First of all, I'm not quite comfortable with the different types of tests and what they are supposed to do.</p>

<p>This is what I'm currently doing for a Vue.js SPA that uses different APIs:</p>

<p>On the unit testing side:
I run them using Jest &amp; Vue test-utils. I use createLocalVue to simulate the Vuex store and I mock the API calls.</p>

<p>On the e2e testing side :
I run them using Cypress. The first reflex was to use fixtures to mock the API call responses too, because I want to test the frontend working properly before merging without being dependent on API availability.</p>

<p>But I realize that my unit tests and e2e tests are very similar in the end.</p>

<p>Finally I have a lot of questions...</p>

<p>Ideally, should the e2e tests do the real API calls?</p>

<p>Can my unit tests really be considered as unit tests when I mock certain elements such as the Vuex store ?</p>

<p>What is the difference between e2e testing and integration testing?</p>

<p>Thanks for your help.</p>
",https://stackoverflow.com/questions/60231724/how-to-correctly-implement-vue-js-tests,"['vue.js', 'testing']",36,False,0,0
Writing basic test code for my Postgres objects,"<p>I'd like to build up some test code for various objects in my Postgres 11.5 database, and am wondering if there is a straightforward way to implement simple checks in straight SQL. As an example, I've got a simple domain that accepts any of three values, case-blind. This is just one example I've picked because the test cases are finite and simple.</p>

<pre><code>DROP DOMAIN IF EXISTS domains.test_outcome;

CREATE DOMAIN domains.test_outcome AS
    citext
    NOT NULL
    CONSTRAINT test_outcome_legal_values
        CHECK(
            VALUE IN ('pass','warning','fail')
     );

COMMENT ON DOMAIN domains.test_outcome IS
    'The test_outcome must be pass, warning, or fail, case-insensitive.';
</code></pre>

<p>Below are some simple test statements that exercise good and bad values:</p>

<pre><code>-- Good values
select 'warning'::test_outcome;
select 'fail'::test_outcome;
select 'PASS'::test_outcome;
select 'WARNING'::test_outcome;
select 'FAIL'::test_outcome;

-- Bad values
select NULL::test_outcome;  
select ''::test_outcome;  
select 'foo'::test_outcome;
</code></pre>

<p>What I'd like to do, is get a single line for each case, and not blow up on an error. I've tried using a <code>DO</code> block, and could use a PL/PgSQL function. Here's the <code>DO</code> code I've tried:</p>

<pre><code>DO $TESTS$

BEGIN
-- Good values
    select 'warning'::test_outcome;
    select 'fail'::test_outcome;
    select 'PASS'::test_outcome;
    select 'WARNING'::test_outcome;
    select 'FAIL'::test_outcome;

-- Bad values
    select NULL::test_outcome;  
    select ''::test_outcome;  
    select 'foo'::test_outcome;

EXCEPTION WHEN OTHERS THEN
      RAISE NOTICE 'Error Name:%',  SQLERRM;
      RAISE NOTICE 'Error State:%', SQLSTATE;
END;
$TESTS$
</code></pre>

<p>What I get back are a couple of notices. I can't tie those back to the specific statement, as far as I can tell, and I get nothing for success cases. </p>

<pre><code>NOTICE:  Error Name:query has no destination for result data
NOTICE:  Error State:42601
DO
Command completed successfully. (Line 20)
</code></pre>

<p>I've seen that there are some unit testing frameworks for PG around, using languages we don't use. Is there any way to do simple tests like the ones above in straight SQL or PL/PgSQL? </p>
",https://stackoverflow.com/questions/60235062/writing-basic-test-code-for-my-postgres-objects,"['postgresql', 'testing']",427,True,0,1
How do I make an Angular 8 unit test for a service with Promises and HTTP requests?,"<p>I'm new to unit testing and I'm having trouble testing getting past some of the first steps</p>

<p>I can handle testing basic functions/services that don't have any dependencies and have basic functionality but I run into trouble when functions become more complex with Promises and Observables and HTTP  requests</p>

<p>I'm having a hard time finding examples online of the more complex function testing. 
I've tried using mocks, spies, calling the actual service etc but maybe I've been doing it all wrong? I feel like the answer is simple and I'm missing something small</p>

<p>Here's my service file (at least the part I am working on)</p>

<pre class=""lang-js prettyprint-override""><code>@Injectable({providedIn: 'root'})
export class HelperService {
    constructor(private http: HttpClient, private titleService: Title) {}

    waitUntilProxyReady(url, timesChecked = 0) {
        return new Promise(resolve =&gt; {
            this.http.get(url, { responseType: 'text', observe: 'response' })
                .subscribe(async (response) =&gt; {
                    timesChecked++;
                    if (response.status &gt; 308) {
                        console.log('Detected proxy URL as status:', response.status, '- trying again in a few seconds...');
                        if (timesChecked &gt; 30) { // 2.5 mins
                            resolve(false);
                            return;
                        }
                        await this.sleep(5000);
                        resolve(this.waitUntilProxyReady(url));
                    } else {
                        resolve(true);
                    }
                }, async (error) =&gt; {
                    timesChecked++;
                    if (timesChecked &gt; 30) { // 2.5 mins
                        resolve(false);
                        return;
                    }

                    console.log('Detected proxy URL as status:', error.status, '- trying again in a few seconds...');
                    await this.sleep(5000);
                    resolve(this.waitUntilProxyReady(url));
                }
            );
        });
    }
    sleep(ms) {
        return new Promise(resolve =&gt; setTimeout(resolve, ms));
    }
</code></pre>

<p>What I want to do is test waitUntilProxyReady() if <code>response.status &gt; 308</code>, does timesChecked iterate and does time.sleep() get called. Then if <code>response.status &lt;= 307</code> does the function return <code>true</code></p>

<p>Any help would be appreciated, I've been stuck on this for a while</p>

<p>Edit:</p>

<p>This is what I have on the testing side</p>

<pre><code>import { TestBed, getTestBed, fakeAsync, tick, async } from '@angular/core/testing';
import { HelperService } from './helper';
import { HttpClient, HttpErrorResponse, HttpHandler } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('HelperService', () =&gt; {
    let httpClient: HttpClient;
    let httpTestingController: HttpTestingController;
    let helper: HelperService;
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
          // Import the HttpClient mocking services
          imports: [ HttpClientTestingModule ],
          // Provide the service-under-test and its dependencies
          providers: [
            HelperService,
          ]
        });
            // Inject the http, test controller, and service-under-test
    // as they will be referenced by each test.
        httpClient = TestBed.get(HttpClient);
        httpTestingController = TestBed.get(HttpTestingController);
        helper = TestBed.get(HelperService);
  });
    afterEach(() =&gt; {
        // After every test, assert that there are no more pending requests.
        httpTestingController.verify();
    });
    describe('waitUntilProxyReady', () =&gt; {
        beforeEach(() =&gt; {
            helper = TestBed.get(HelperService);
        })

        it('test', () =&gt; {
            let mockResponse = '123'
            helper.waitUntilProxyReady('google.com').then(response =&gt; {
                expect(response).toBeFalsy()
            })
            const req = httpTestingController.expectOne('google.com');
            expect(req.request.method).toEqual('GET');

            // Respond with the mock response
            req.flush(mockResponse, {status : 309, statusText: 'hi'})
        })
    })
</code></pre>

<p>But the req.flush only sends back a response of this</p>

<pre><code> HttpErrorResponse{headers: HttpHeaders{normalizedNames: Map{}, lazyUpdate: null, headers: Map{}}, status: 309, statusText: 'hi', url: 'https://google.com/', ok: false, name: 'HttpErrorResponse', message: 'Http failure response for /goo
gle.com/: '309 hi'status, error: '123'}
</code></pre>

<p>But I can't get inside the async(response) block</p>
",https://stackoverflow.com/questions/60460099/how-do-i-make-an-angular-8-unit-test-for-a-service-with-promises-and-http-reques,"['angular', 'unit-testing', 'http', 'dependency-injection', 'promise']",365,False,0,0
Problems implementing ToString specialization for unit testing c++,"<p>Right now i'm busy writing an event based queue. I wanted to do some unit testing but i'm running into an error. In Microsoft Visual Studio, when making a unit test project, you have to implement this function for each type you do an assert on:</p>
<pre><code>namespace Microsoft
{
    namespace VisualStudio
    {
        namespace CppUnitTestFramework
        {
            template&lt;&gt; static std::wstring ToString&lt;T&gt;&gt;(const class T&amp; t)
            {
                //code goes here
            }
        }
    }
}
</code></pre>
<p>the problem is that the queue is not changing the object that was passed into it. because of this i wanted to write a unit test that verified that the object pointed to in the queue, was the same address as the object outside of the queue. I wrote the test as follows:</p>
<pre><code>TEST_METHOD(REGISTERED_PROCESSORS_HAVE_ACCURATE_ADDRESSES_IN_QUEUE_MANAGER)
{
    QueueProcessor queue;
    ActionProcessor processor;

    processor.loadFromJson({ {actionProcessorProperties::QUEUE_NAME, &quot;alpha&quot;} });
    
    queue.registerProcessor(&amp;processor);

    Assert::AreEqual(&amp;processor, queue.processors[&quot;alpha&quot;][0]);
}
</code></pre>
<p>i then get this error:</p>
<pre><code>Test writer must define specialization of ToString&lt;Q* q&gt; for your class class std::basic_string&lt;wchar_t,struct std::char_traits&lt;wchar_t&gt;,class std::allocator&lt;wchar_t&gt; &gt; __cdecl Microsoft::VisualStudio::CppUnitTestFramework::ToString&lt;class ActionProcessor&gt;(class ActionProcessor *).
</code></pre>
<p>so how do I implement <code>ToString</code> on a pointer? when I try putting the data type in the compiler complains. Also how do I then display the pointer as a string value?</p>
<p>thanks for the help.</p>
<h3>edit:</h3>
<p>i found the unit test works fine if you convert the pointers to uintptr_t. However the type conversion mid assert kinda messes up the readability of the code. Is there a cleaner solution?</p>
<pre><code>TEST_METHOD(REGISTERED_PROCESSORS_HAVE_ACCURATE_ADDRESSES_IN_QUEUE_MANAGER)
{
    QueueProcessor queue;
    ActionProcessor processor;

    processor.loadFromJson({ {actionProcessorProperties::QUEUE_NAME, &quot;alpha&quot;} });
    
    queue.registerProcessor(&amp;processor);

    Assert::AreEqual(reinterpret_cast&lt;uintptr_t&gt; (&amp;processor),
                     reinterpret_cast&lt;uintptr_t&gt;(queue.processors[&quot;alpha&quot;][0]));
}
</code></pre>
",https://stackoverflow.com/questions/61264252/problems-implementing-tostring-specialization-for-unit-testing-c,"['c++', 'visual-studio', 'unit-testing']",286,True,0,1
How to do user identification in Android?,"<p>I recently started learning Android to port my iOS app to Android.</p>
<p>User registration in my app is optional, hence the user can decide to get started right away without any delay. However I still need a form of identification against fraud and if the user has passed the first week of free trial. Otherwise the user can just keep deleting and reinstalling the app to use it for free, forever.</p>
<p>On iOS I have solved the problem through the keychain.  Any values stored in there remain there even after the app has been uninstalled.</p>
<pre><code>import KeychainAccess

let keychain = Keychain(service: Constants.keychainServiceID).synchronizable(false).accessibility(.alwaysThisDeviceOnly).accessibility(.alwaysThisDeviceOnly)
let deviceId = UUID().uuidString.lowercased()
keychain[&quot;DEVICE_ID&quot;] = deviceId
</code></pre>
<p>I don't seem to find anything like that on Android.</p>
<p>A unique Device ID doesn't seem to be available either based on this <a href=""https://stackoverflow.com/a/59093659/92153"">answer</a></p>
<p>Hence is there a way to achieve this or do I have to make user registration mandatory?</p>
<p>UPDATE:</p>
<p>In iOS when a keyChain value is set, the user can't ever update or delete it. Even after the app is uninstalled. During unit testing I can delete the keychain entry like this:</p>
<pre><code>let keychain = Keychain(service: Constants.keychainServiceID).synchronizable(false).accessibility(.alwaysThisDeviceOnly)
do {
    try keychain.remove(&quot;DEVICE_ID&quot;)
} catch let error {
    print(&quot;error: \(error)&quot;)
}
</code></pre>
<p>Can I do that in Android?</p>
",https://stackoverflow.com/questions/63977019/how-to-do-user-identification-in-android,['android'],100,False,0,1
How to access or create File objects using Mocha (NodeJS)?,"<p>I'm a beginner in JavaScript and am creating my first project. I made a File Upload program which works, and I am now adding unit tests. I am trying to test how my program handles various different types of files (valid and invalid CSV/JSON files). However, my FileUploadHandler is expecting a File object and Mocha, which uses NodeJS, does not have a File class, so I cannot call new File to create File objects to pass in.</p>
<p>I tried to make a bunch of files manually and then pass them into the Mocha unit tests by path but I do not know how to get them to be passed in as File objects. -- I looked it up and it seems that you cannot access File objects by path via JS so if this is the case, what is a way I can do my unit testing?</p>
<p>I hope this was clear but if not, I can further clarify. Please help and thank you so much</p>
<p>** my function that I want to test takes in a File object</p>
<p>Ex.</p>
<pre><code>describe('File testing', function() {
    it('cannot process non csv/jsons', function() {
        let f = new File([&quot;&quot;], &quot;html_file.html&quot;);
        let tester = new FileUploadHandler(f);
        ## expecting error ##
    })
})
</code></pre>
",https://stackoverflow.com/questions/63125424/how-to-access-or-create-file-objects-using-mocha-nodejs,"['javascript', 'node.js', 'mocha.js']",523,False,0,1
GTest CMake multiple definition of main,"<p>I am trying to learn how to use <code>gtest</code> for creating unit testing in c++. I wrote a simple library to test, where I created a factorial function</p>

<p>src/main.cpp</p>

<pre><code>#include &lt;iostream&gt;

int factorial(int n) {
    if (n == 1)
        return 1;
    return n * factorial(n - 1);
}


// Default main function
int main() {
    std::cout &lt;&lt; ""Hello, World!"" &lt;&lt; std::endl;
    return 0;
}
</code></pre>

<p>src/main.h</p>

<pre><code>#ifndef GTEST_LEARN_MAIN_H
#define GTEST_LEARN_MAIN_H

int factorial(int n);

#endif //GTEST_LEARN_MAIN_H
</code></pre>

<p>src/CMakeLists.txt</p>

<pre><code>add_executable(gtest_learn main.cpp main.h)
add_library(factorial_lib STATIC main.cpp main.h)
</code></pre>

<p>Then I created a unit test where I am testing the factorial function</p>

<p>test/main.cpp</p>

<pre><code>#include ""main.h""
#include ""gtest/gtest.h""


TEST(MyTestSuite,MyTest){
    EXPECT_EQ(factorial(4),24);
}


int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&amp;argc, argv);
    return RUN_ALL_TESTS();
}
</code></pre>

<p>I added gtest to my project following the docs on the <a href=""https://github.com/google/googletest/tree/master/googletest"" rel=""nofollow noreferrer"">github</a> page</p>

<p>test/CMakeLists.txt.in</p>

<pre><code>cmake_minimum_required(VERSION 2.8.2)

project(googletest-download NONE)

include(ExternalProject)
ExternalProject_Add(googletest
  GIT_REPOSITORY    https://github.com/google/googletest.git
  GIT_TAG           master
  SOURCE_DIR        ""${CMAKE_CURRENT_BINARY_DIR}/googletest-src""
  BINARY_DIR        ""${CMAKE_CURRENT_BINARY_DIR}/googletest-build""
  CONFIGURE_COMMAND """"
  BUILD_COMMAND     """"
  INSTALL_COMMAND   """"
  TEST_COMMAND      """"
)
</code></pre>

<p>test/CMakeLists.txt</p>

<pre><code>cmake_minimum_required(VERSION 3.15)
project(tests)

# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G ""${CMAKE_GENERATOR}"" .
        RESULT_VARIABLE result
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
    message(FATAL_ERROR ""CMake step for googletest failed: ${result}"")
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
        RESULT_VARIABLE result
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download )
if(result)
    message(FATAL_ERROR ""Build step for googletest failed: ${result}"")
endif()

# Prevent overriding the parent project's compiler/linker
# settings on Windows
set(gtest_force_shared_crt ON CACHE BOOL """" FORCE)

# Add googletest directly to our build. This defines
# the gtest and gtest_main targets.
add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src
        ${CMAKE_CURRENT_BINARY_DIR}/googletest-build
        EXCLUDE_FROM_ALL)

# The gtest/gtest_main targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later. Otherwise we have to add them here ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
    include_directories(""${gtest_SOURCE_DIR}/include"")
endif()

add_executable(tests main.cpp)
target_link_libraries(tests gtest_main)
target_link_libraries(tests factorial_lib)
add_test(NAME example_test COMMAND tests)
</code></pre>

<p>When I am trying to run my test, I get an error saying <code>multiple definition of 'main'</code>. It also says the first definition of main was in <code>test/main.cpp</code>, but before I added the main function in this file, it said that <code>main</code> was first declared in <code>googletest-src/googletest/src/gtest_main.cc</code>, which is the <code>gtest</code> library. For this project I could remove the <code>main</code> from <code>src/main</code> since it serves no purpose, but in a real application that wouldn't be an option. I assume I have to make some CMake config to ignore the gtest main or something like that, but I don't know how. Can anyone help me out? Thanks in advance!</p>

<p>Here is my project-level CMakeLists</p>

<pre><code>cmake_minimum_required(VERSION 3.15)
project(gtest_learn)

set(CMAKE_CXX_STANDARD 14)


include_directories(src)

add_subdirectory(src)
add_subdirectory(test)
</code></pre>
",https://stackoverflow.com/questions/61609265/gtest-cmake-multiple-definition-of-main,"['c++', 'cmake', 'googletest']",4258,True,-1,1
List element (object) not subscriptable,"<p>I want to create a unit test for a function which sorts a list of objects according to some object attribute(s). Here is a code sample:</p>
<pre><code>class Foo:
    &quot;&quot;&quot;Custom data type Foo.&quot;&quot;&quot;

    def __init__(self,
                 a: str,
                 b: int,
                 c: int,
                 d: int,
                 e: int,
                 f: int):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
        self.f = f
        self.g = c * d * e
        self.h = c * d
</code></pre>
<p>This is a part of the unit test function which produces the error:</p>
<pre><code>from random import randint
...
class Test(TestCase):

def test_item_sort_foo(self):
    random_list = [Foo(str(randint(0, 1000)),
                        randint(0, 100),
                        randint(0, 100),
                        randint(0, 100),
                        randint(0, 100),
                        randint(0, 100))
                   for x in range(100)]
...
</code></pre>
<p>The error message is:</p>
<pre><code>TypeError: 'Foo' object is not subscriptable. 
</code></pre>
<p>Despite reading <a href=""https://stackoverflow.com/questions/216972/what-does-it-mean-if-a-python-object-is-subscriptable-or-not"">this question</a>, I cannot understand why Python cares if <code>Foo</code> is subscriptable since <code>random_list</code> already is. I'm trying to generate a list of random <code>Foo</code> items similarly to the answer <a href=""https://stackoverflow.com/questions/348196/creating-a-list-of-objects-in-python"">here</a>. I am puzzled because I already have a (working) class of the kind</p>
<pre><code>from dataclasses import dataclass
from typing import List


@dataclass
class Bar:
    &quot;&quot;&quot;Bar custom data type.&quot;&quot;&quot;
    i: str
    j: List[Foo]
</code></pre>
<p>And I can type, e.g.,</p>
<pre><code>f = Foo(...)
b = Bar(&quot;baz&quot;, [])
b.j.append(f)
</code></pre>
<p>So here are my questions:</p>
<ul>
<li>Do elements of subscriptable objects also have to be subscriptable? Why?</li>
<li>What is the best way to generate random data with the properties from above for testing?</li>
<li>How do I apply this principle for my case?</li>
</ul>
<p>EDIT: This is the complete unit testing function:</p>
<pre><code>def test_item_sort_foo(self):
        random_list = [Foo(str(randint(0, 1000)),
                            randint(0, 100),
                            randint(0, 100),
                            randint(0, 100),
                            randint(0, 100),
                            randint(0, 100))
                       for x in range(100)]
        sorted_list = item_sort_foos(random_list)
        assert eq(sorted_list, sorted(random_list,
                                      key=itemgetter(4, 7),
                                      reverse=True))
</code></pre>
<p>And here is the code of the function which implements the logic:</p>
<pre><code>def item_sort_foos(foos: List[Foo]) -&gt; List[Foo]
    return sorted(foos,
                  key=attrgetter(&quot;e&quot;, &quot;h&quot;),
                  reverse=True)
</code></pre>
<p>EDIT2: The full trace is:</p>
<pre><code>Error
Traceback (most recent call last):
  File &quot;/opt/anaconda3/lib/python3.7/unittest/case.py&quot;, line 59, in testPartExecutor
    yield
  File &quot;/opt/anaconda3/lib/python3.7/unittest/case.py&quot;, line 628, in run
    testMethod()
  File &quot;.../src/project/tests/test_orderings.py&quot;, line 89, in test_item_sort_foos
    reverse=True))
TypeError: 'Foo' object is not subscriptable
</code></pre>
<p>If you need any additional info, please request in the comments.</p>
",https://stackoverflow.com/questions/62488737/list-element-object-not-subscriptable,"['python', 'list', 'object', 'pytest', 'list-comprehension']",2270,True,0,1
How to cover the tests for a function inside a react-hooks component - Enzyme/Jest,"<p>I'm very new to testing.</p>
<p>Consider I have a below component</p>
<pre><code>export default function ResolutionCount({ componentUsedIn }) {
    const dispatch = useDispatch();

    const userID = useSelector(
        (state) =&gt; state.userInfoReducer.userInfo[0][&quot;user_id&quot;]
    );

    useEffect(() =&gt; {

        dispatch({
            type: SET_RESOLUTION_STATUS_COUNT_BAR_CHART_FETCHING_DATA,
            payload: true,
        });
        dispatch(getResolutionStatusCount([]));

        return () =&gt; {
            dispatch({
                type: SET_RESOLUTION_STATUS_COUNT_BAR_CHART,
                payload: {
                    barChartData: [],
                    barChartCategories: [],
                    resolution_status_environment: [],
                },
            });
        };
    }, []);

    const handleSelection = (selectedData) =&gt; {

        dispatch({
            type: SET_RESOLUTION_STATUS_COUNT_SELECTED_ENV,
            payload: selectedData,
        });

        dispatch(
            getResolutionCount(
                [],
                startDate,
                endDate,
                false,
                selectedData
            )
        );
    };

    return (
        &lt;Fragment&gt;
            &lt;Space&gt;
                &lt;DateRangePicker
                    componentUsedIn={componentUsedIn}
                &gt;&lt;/DateRangePicker&gt;
                &lt;Selection
                    options={environment}
                    handleSelection={handleSelection}
                &gt;&lt;/Selection&gt;
            &lt;/Space&gt;
            &lt;BarChart componentUsedIn={componentUsedIn}&gt;&lt;/BarChart&gt;
        &lt;/Fragment&gt;
    );

}
</code></pre>
<p>In this Selection, DateRangePicker and BarChart components are wrapped with <code>React.memo()</code>. Now for unit testing, I'm actually using jest and enzyme and to run useEffect in enzyme's shallow I'm using another package called <a href=""https://github.com/mikeborozdin/jest-react-hooks-shallow"" rel=""nofollow noreferrer"">jest-react-hooks-shallow</a></p>
<p>I actually want to test the <code>handleSelection</code> function inside <code>ResolutionCount</code> component. Because that function is not being covered by test cases. I was going through enzymes's docs on how to call this function and I found that if it was a class-based component we could get the instance of the wrapper and call the function. But in the react hooks components how should we test the functions inside a component.</p>
<p>I went through <a href=""https://stackoverflow.com/questions/54713644/testing-react-functional-component-with-hooks-using-jest"">Testing React Functional Component with Hooks using Jest</a> and this did not help.</p>
<p>I also read about it's not best practice to test internal implementations. In that case, test coverage will not be covered for this function right? Is that ok to do?</p>
<p>Can anyone please help/advice me?</p>
<p>Kindly excuse if this question is repeated and Thank you in advance!</p>
",https://stackoverflow.com/questions/64026145/how-to-cover-the-tests-for-a-function-inside-a-react-hooks-component-enzyme-je,"['reactjs', 'unit-testing', 'jestjs', 'react-hooks', 'enzyme']",1495,False,0,1
SinonJS Spy Cannot Restore Read Only Method/Property of Object,"<p>It gives me <code>TypeError: Cannot assign to read only property 'get' of object '#&lt;Config&gt;'</code>.</p>
<p>I'm using <code>mocha 8.0.1</code>, <code>chai 4.2.0</code>, <code>sinon 9.0.2</code> for Unit Testing.</p>
<p>I'm spying on a method in the <a href=""https://www.npmjs.com/package/config"" rel=""nofollow noreferrer"">config</a> npm package.</p>
<p>Here's how I spy the <code>get</code> method:</p>
<pre><code>...
before(() =&gt; {
      sandbox = sinon.createSandbox();
      configStub = sandbox.spy(config, 'get');
});

after(() =&gt; {
      sandbox.restore();
});

it('should something', async () =&gt; {
      console.log('Just logging');

      config.get('LOG.LEVEL'); // just to show the point. if I remove this line, it doesn't throw the error
});
...
</code></pre>
<p>What happens is, if I run <code>config</code>'s <code>get</code> method somewhere during the test, it can not be restored by spy. It throws that read-only property error. But when the <code>config.get</code> function is never called, it doesn't throw that error (I don't understand why not). For <code>stub</code> there's no problem, it can restore just fine.</p>
<p>But the reason I'm using <code>spy</code> is because I want <code>config.get</code> to work like it normally does while I'm testing my module/function that's using it, I just want to spy on it. And I also need to be able to restore it after this test suite. I spy on it because I need to test that it's being called by my module/function with some specific parameters.</p>
<p>How do I spy on a <strong>read-only</strong> property/method, allow my module/function to use it like it normally does, and then restore it?</p>
<p>Thank you :)</p>
",https://stackoverflow.com/questions/63070703/sinonjs-spy-cannot-restore-read-only-method-property-of-object,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'sinon']",361,True,0,1
SimpleJdbcInsert fail to insert because of null autogenerated id (HSQLDB),"<p>Good morning everyone</p>

<p>I am unit testing the persistence tier of a project with JUnit using HSQLDB. The project is using Spring with Hibernate + JPA. I'm using Spring's SimpleJdbcInsert to insert some data in the database for testing. However whenever I try to insert something I am getting:
<code>org.hsqldb.HsqlException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID</code> as shown below:</p>

<pre><code>org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO picture (DATA, MIME_TYPE, NAME, SIZE) VALUES(?, ?, ?, ?)]; violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID; nested exception is java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID

    at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:85)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:645)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:866)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:932)
    at org.springframework.jdbc.core.simple.AbstractJdbcInsert.executeInsertInternal(AbstractJdbcInsert.java:362)
    at org.springframework.jdbc.core.simple.AbstractJdbcInsert.doExecute(AbstractJdbcInsert.java:341)
    at org.springframework.jdbc.core.simple.SimpleJdbcInsert.execute(SimpleJdbcInsert.java:122)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertPicture(AppointmentDaoImplTest.java:330)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertUser(AppointmentDaoImplTest.java:345)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.insertPatient(AppointmentDaoImplTest.java:449)
    at ar.edu.itba.paw.tests.AppointmentDaoImplTest.testCreateAppointmentSuccessfully(AppointmentDaoImplTest.java:557)
    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.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.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
    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:271)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    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.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:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.sql.SQLIntegrityConstraintViolationException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:873)
    at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:866)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:629)
    ... 41 more
Caused by: org.hsqldb.HsqlException: violación del restricción de integridad: restricción ('check') NOT NULL; SYS_CT_10137 table: PICTURE column: PICTURE_ID
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.Table.enforceRowConstraints(Unknown Source)
    at org.hsqldb.Table.insertSingleRow(Unknown Source)
    at org.hsqldb.StatementDML.insertSingleRow(Unknown Source)
    at org.hsqldb.StatementInsert.getResult(Unknown Source)
    at org.hsqldb.StatementDMQL.execute(Unknown Source)
    at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 46 more
</code></pre>

<p>Here is my test (where <code>insertPatient()</code> is failing):</p>

<pre><code>@Test
public void testCreateAppointmentSuccessfully() {
    cleanAllTables();
    insertPatient();

    ... some code ...
}
</code></pre>

<p>The <code>insertPatient</code> function (where <code>insertPicture()</code> is failing):</p>

<pre><code>private void insertPatient() {
    insertUser();

    ... some code ...
}

private void insertUser() {
    insertPicture();

    ... some code ...
}

private void insertPicture() {
    Map&lt;String, Object&gt; map = new HashMap&lt;&gt;();
    map.put(""data"", IMG_DATA);
    map.put(""mime_type"", MIME_TYPE);
    map.put(""size"", IMG_SIZE);
    map.put(""name"", PICTURE);
    pictureJdbcInsert.execute(map);
}
</code></pre>

<p>The <code>SimpleJdbcInsert pictureJdbcInsert</code> instance is set in the following method:</p>

<pre><code>@Before
public void setUp(){
    this.pictureJdbcInsert = new SimpleJdbcInsert(this.ds)
                .withTableName(PICTURES_TABLE) // private static final String PICTURES_TABLE = ""picture"";
                .usingGeneratedKeyColumns(""picture_id"");

    ... some code ...
}
</code></pre>

<p>The test class is annotated with <code>@Sql(scripts = ""classpath:sql/schema.sql"")</code> being <code>schema.sql</code>:</p>

<pre><code>create table if not exists picture
(
    picture_id identity        not null constraint picture_pk primary key,
    name      varchar(1023),
    mime_type varchar(255)     not null,
    size      bigint           not null default 0,
    data      varbinary(65535) not null
);

... some more tables ...
</code></pre>

<p>As you can see, I am not putting the key  manually. I am expecting that <code>usingGeneratedKeyColumns</code> method will automatically generate it for me. From the stacktrace I understand that is trying to execute the following query:
<code>INSERT INTO picture (DATA, MIME_TYPE, NAME, SIZE) VALUES(?, ?, ?, ?)</code> where the <code>?</code> are replaced by the corresponding values in the map, but failing because there was no value for <code>picture_id</code> specified. I don't understand is this happening as the <code>schema.sql</code> file specifies that <code>picture_id</code> is of type <code>identity</code> meaning that is auto-generated and by default starting by 0 and with increment of 1.</p>

<p>I have been trying and looking for solutions but everything suggests this should be working.</p>
",https://stackoverflow.com/questions/62033848/simplejdbcinsert-fail-to-insert-because-of-null-autogenerated-id-hsqldb,"['java', 'spring', 'hibernate', 'junit', 'hsqldb']",886,True,0,2
issue unit testisng a RestController post request with mockmvc. It performs the request correctly when debug but why does mock response comes empty?,"<p>I am kind of new to testing and am currently having an issue <strong>unit testing a Spring RestController</strong> with <strong>MockMvc</strong>. The problem shows itself when I perform a post request to <strong>Add a new User</strong> with a requestBody and I get the http status that the request was performed successfully, but once I get the response converted to a String from MvcResult, it comes an empty String.</p>
<p>I debugged the test and checked that the request was performed, and the request body was taken successfully and has passed all validations, so following this logic my thoughts are that the problem lies with Mockito but I don't quite understand why. Can someone give me a pointer to what I am doing incorrectly?</p>
<p>This my Entity User:</p>
<pre><code>@Entity
@Table(name =&quot;users&quot;)
public class User {

  @Id
  @GeneratedValue(generator= &quot;UUID&quot;)
  @GenericGenerator(name=&quot;UUID&quot;, strategy = &quot;org.hibernate.id.UUIDGenerator&quot;)
  @Column(name = &quot;ID&quot;)
  private String id;

  @NotBlank(message = ResponseMessage.ERROR_INVALID_FIRST_NAME_INPUT)
  @Column(name = &quot;first_name&quot;)
  private String firstName;

  @NotBlank(message = ResponseMessage.ERROR_INVALID_LAST_NAME_INPUT)
  @Column(name = &quot;last_name&quot;)
  private String lastName;

  @NotBlank(message = ResponseMessage.ERROR_INVALID_EMAIL_INPUT)
  @Email(message = ResponseMessage.ERROR_INVALID_EMAIL_INPUT)
  @Column(name = &quot;email&quot;)
  private String email;

  @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
  @NotBlank(message = ResponseMessage.ERROR_INVALID_PASSWORD_INPUT)
  @Column(name = &quot;password&quot;)
  private String password;

  @Column(name = &quot;phone_number&quot;)
  private String phoneNumber;

  @Column(name = &quot;address&quot;)
  private String address;

  @Temporal(TemporalType.DATE)
  @Column(name = &quot;registered_on&quot;)
  private Date registeredDate;
  // Constructors and setters and getters down here
}
</code></pre>
<p>This is the rest controller:</p>
<pre><code>
@Validated
@RestController
@RequestMapping(path = &quot;/user&quot;)
public class UserController {

  @Autowired
  private UserService userService;

  @PostMapping(&quot;/add&quot;)
  public Response&lt;Object&gt; addUser(@Valid @RequestBody User user) {
    return this.userService.addUser(user);

  // other methods down here
  }

}
</code></pre>
<p>And this is my rest controller test:</p>
<pre><code>
@WebMvcTest(UserController.class)
class UserControllerTest {

  @Autowired
  private MockMvc mvc;

  @MockBean
  private UserService userService;

  private List&lt;User&gt; users;

  void populateUsers() {
    users = new ArrayList&lt;&gt;();
    users.add(new User(&quot;test&quot;,&quot;test&quot;,&quot;test@test.com&quot;,&quot;test&quot;));
    users.add(new User(&quot;test1&quot;,&quot;test1&quot;,&quot;test1@test.com&quot;,&quot;test1&quot;));
    users.add(new User(&quot;test2&quot;,&quot;test2&quot;,&quot;test2@test.com&quot;,&quot;test2&quot;));
  }

  @BeforeEach
  void setUp() {
    populateUsers();
  }

  @AfterEach
  void clear() {
    users.clear();
  }
     // other tests here. that actually work
 
  @Test
  void addUser() throws Exception {
    // Arrange
    Response&lt;Object&gt; expected = new Response&lt;&gt;(200, ResponseMessage.SUCCESS_SAVED_USER);
    ObjectMapper objectMapper = new ObjectMapper();
    User user = new User(&quot;Added&quot;,&quot;User&quot;,&quot;a@user.com&quot;,&quot;itWorks&quot;);
    String content = &quot;{&quot; +
            &quot;\&quot;firstName\&quot;:\&quot;Added\&quot;,&quot; +
            &quot;\&quot;lastName\&quot;:\&quot;User\&quot;,&quot; +
            &quot;\&quot;email\&quot;:\&quot;a@user.com\&quot;,&quot; +
            &quot;\&quot;password\&quot;:\&quot;itWorks\&quot;&quot; +
            &quot;}&quot;;
   Mockito.when(userService.addUser(user)).thenReturn(expected);

    // Act
    String actual = mvc
            .perform(TestHttpRequestBuilderHelper.httpPostRequestBuilder(&quot;/user/add&quot;, content))
            .andExpect(status().isOk())
            .andReturn()
            .getResponse()
            .getContentAsString();

    // Assert
    assertEquals(objectMapper.writeValueAsString(expected), actual);
  }
  
}
</code></pre>
<p>I used another helper class in building the MockMvcRequestBulders called TestHttpRequestBuilderHelper:</p>
<pre><code>
public class TestHttpRequestBuilderHelper {

  private static HttpHeaders generateHttpHeaders() {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(&quot;Content-type&quot;, &quot;application/json; charset=utf-8&quot;);
    httpHeaders.add(&quot;Accept&quot;,&quot;application/json&quot;);
    return httpHeaders;
  }
   // other overloaded methods here
 
  public static MockHttpServletRequestBuilder httpPostRequestBuilder(String url, String content) {
    return MockMvcRequestBuilders.post(url).headers(generateHttpHeaders()).content(content);
  }

}
</code></pre>
<p>This is the log output:</p>
<pre><code>
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /user/add
       Parameters = {}
          Headers = [Content-Type:&quot;application/json; charset=utf-8&quot;, Accept:&quot;application/json&quot;, Content-Length:&quot;81&quot;]
             Body = {&quot;firstName&quot;:&quot;Added&quot;,&quot;lastName&quot;:&quot;User&quot;,&quot;email&quot;:&quot;a@user.com&quot;,&quot;password&quot;:&quot;itWorks&quot;}
    Session Attrs = {}

Handler:
             Type = com.bibliotek.library.user.UserController
           Method = com.bibliotek.library.user.UserController#addUser(User)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Vary:&quot;Origin&quot;, &quot;Access-Control-Request-Method&quot;, &quot;Access-Control-Request-Headers&quot;, X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


org.opentest4j.AssertionFailedError: 
Expected :{&quot;httpCode&quot;:200,&quot;message&quot;:&quot;User was added successfully&quot;}
Actual   :
&lt;Click to see difference&gt;


    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
    at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
    at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
    at com.bibliotek.library.user.UserControllerTest.addUser(UserControllerTest.java:116)
    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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)


2020-12-07 11:33:43.380  INFO 16288 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code -1

</code></pre>
<p>So to be successful it must be like this:</p>
<pre><code>exptected: {&quot;httpCode&quot;:200,&quot;message&quot;:&quot;User was added successfully&quot;} 
actual : {&quot;httpCode&quot;:200,&quot;message&quot;:&quot;User was added successfully&quot;}
</code></pre>
<p>but in my case its returning :</p>
<pre><code>expected: {&quot;httpCode&quot;:200,&quot;message&quot;:&quot;User was added successfully&quot;}
actual: &quot;&quot;
</code></pre>
",https://stackoverflow.com/questions/65180308/issue-unit-testisng-a-restcontroller-post-request-with-mockmvc-it-performs-the,"['java', 'spring-boot', 'unit-testing', 'mockito', 'mockmvc']",75,False,0,0
Material Dialog testing data not making it into my dialog,"<p>I've been in Angular for a bit, but working on my first major solo project.</p>
<p>I have a basic component that I'm opening as a material dialog.</p>
<pre><code>@Component({
  selector: 'heavyweight-software-pizza-place-delete',
  templateUrl: './location-delete.component.html',
  styleUrls: ['./location-delete.component.css']
})
export class LocationDeleteComponent implements OnInit {
  @Input()
  currentLocation: PcLocation;

  constructor(protected dialogRef: MatDialogRef&lt;LocationDeleteComponent&gt;,
              @Inject(MAT_DIALOG_DATA) public data: LocationDeleteDialogData) { }

  ngOnInit() {
    console.log('data', this.data);
  }

  onButtonClick(confirmed = false) {
    this.data.confirmed = confirmed;
    this.dialogRef.close();
  }
}

&lt;h3&gt;
  Delete this pizza place?
&lt;/h3&gt;
&lt;p id=&quot;paraCustomerId&quot;&gt;{{data.customerId}}&lt;/p&gt;
&lt;p id=&quot;paraShopName&quot;&gt;{{data.shopName}}&lt;/p&gt;
&lt;p id=&quot;paraStreet&quot;&gt;{{data.street}}&lt;/p&gt;
&lt;br/&gt;
&lt;div&gt;
  &lt;button mat-raised-button
          id=&quot;btnYes&quot;
          (click)=&quot;onButtonClick(true)&quot;&gt; Yes &lt;/button&gt;
  &lt;button mat-raised-button
          id=&quot;btnNo&quot;
          (click)=&quot;onButtonClick(false)&quot;&gt; No &lt;/button&gt;
&lt;/div&gt;
</code></pre>
<p>I am attempting to test with the follow test</p>
<pre><code>const ID_CUST_ID = &quot;#paraCustomerId&quot;;
const ID_SHOP_NAME = &quot;#paraShopName&quot;;
const ID_STREET_ADDR = &quot;#paraStreet&quot;;
describe('LocationDeleteComponent', () =&gt; {
  let component: LocationDeleteComponent;
  let fixture: ComponentFixture&lt;LocationDeleteComponent&gt;;

  let locationDeleteData: LocationDeleteDialogData = new LocationDeleteDialogData();
  locationDeleteData.customerId = CUSTOMER_ID1;
  locationDeleteData.shopName = LOCATION1.shopName;
  locationDeleteData.street = LOCATION_ADDRESS1.street1;

  const matDialogData = {};
  let mockMatDialogRef: MockMatDialogRef;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        LocationDeleteComponent,
      ],
      imports: [
        BrowserAnimationsModule,
        MatButtonModule,
        MatDialogModule,
        MatFormFieldModule,
        MatIconModule,
        MatRadioModule,
        ReactiveFormsModule,
      ],
      providers: [
        {provide: LocationDeleteDialogData, useValue: locationDeleteData},
        {provide: MAT_DIALOG_DATA, useValue: matDialogData},
        {provide: MatDialogRef, useClass: MockMatDialogRef},
      ]
    })
      .compileComponents();
  }));

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

    locationDeleteData = TestBed.inject(LocationDeleteDialogData);
    console.log('locationDeleteData', locationDeleteData);
    mockMatDialogRef = TestBed.inject(MatDialogRef);
    console.log('mockMatDialogRef', mockMatDialogRef);
  });

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

    console.log('customerId', locationDeleteData.customerId);

    const rootElement: HTMLElement = fixture.nativeElement;
    const custId: HTMLParagraphElement = rootElement.querySelector(ID_CUST_ID);
    expect(custId.textContent).toEqual(CUSTOMER_ID1);
  });
});
</code></pre>
<p>When I run it, I get the following:</p>
<pre><code>  console.log
    data {}

      at LocationDeleteComponent.ngOnInit (src/app/components/location/location-delete/location-delete.component.ts:19:13)

  console.log
    locationDeleteData LocationDeleteDialogData {
      customerId: 'Who dey?',
      shopName: 'The Restaurant at the End of the Universe',
      street: '100 Hartland Plaze' }

      at beforeEach (src/app/components/location/location-delete/location-delete.component.spec.ts:60:13)

  console.log
    mockMatDialogRef MockMatDialogRef {}

      at beforeEach (src/app/components/location/location-delete/location-delete.component.spec.ts:62:13)

  console.log
    customerId Who dey?

      at it (src/app/components/location/location-delete/location-delete.component.spec.ts:68:13)

  console.error
    Unhandled Promise rejection: expect(received).toEqual(expected) // deep equality
    
    Expected: &quot;Who dey?&quot;
    Received: &quot;&quot; ; Zone: ProxyZone ; Task: Promise.then ; Value: { Error: expect(received).toEqual(expected) // deep equality
</code></pre>
<p>So, based on the console output, it doesn't appear that the data is getting populated with my data object being passed in. I cannot find what I'm doing wrong. Can someone point out what is probably obvious to everyone else?</p>
<p>I've read the following stack overflow entries, but didn't find them helpful.</p>
<ul>
<li><a href=""https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjfk4yjh-vqAhXroHIEHSNZATUQFjAAegQICxAB&amp;url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F53657241%2Funit-test-angular-material-dialog-how-to-include-mat-dialog-data&amp;usg=AOvVaw2a-ELrUPahs5n0ttWfFZKo"" rel=""nofollow noreferrer"">Unit test angular material dialog how to include mat-dialog-data</a></li>
<li><a href=""https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjfk4yjh-vqAhXroHIEHSNZATUQrAIoAHoECAcQAQ&amp;url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F48156316%2Fhow-to-test-angular-material-dialog&amp;usg=AOvVaw2SSUCIsUi2QWJTQLLKfwP9"" rel=""nofollow noreferrer"">How to test angular material dialog</a></li>
<li><a href=""https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjfk4yjh-vqAhXroHIEHSNZATUQrAIoAXoECAcQAg&amp;url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F52993583%2Fmatdialog-service-unit-test-angular-6-error&amp;usg=AOvVaw2C-PpZCvlgs4Yd6o-BNE_6"" rel=""nofollow noreferrer"">Matdialog service unit test angular 6 error</a></li>
<li><a href=""https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjfk4yjh-vqAhXroHIEHSNZATUQrAIoA3oECAcQBA&amp;url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F48703365%2Fangular-how-to-mock-matdialogref-while-testing&amp;usg=AOvVaw1tpapPAhQjE2TF9YbMRQqQ"" rel=""nofollow noreferrer"">Unit testing matdialog</a></li>
<li><a href=""https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjfk4yjh-vqAhXroHIEHSNZATUQrAIoA3oECAcQBA&amp;url=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F48703365%2Fangular-how-to-mock-matdialogref-while-testing&amp;usg=AOvVaw1tpapPAhQjE2TF9YbMRQqQ"" rel=""nofollow noreferrer"">Angular how to mock matdialogref while testing</a></li>
</ul>
<p>As well as many tutorials I found by googling, but I haven't seen my problem.</p>
<p>I removed the imports for the sake of brevity. Also, please notice the console.log of the data which shows it empty. That is the problem, but I don't know why.</p>
",https://stackoverflow.com/questions/63101321/material-dialog-testing-data-not-making-it-into-my-dialog,"['angular', 'unit-testing', 'angular-material', 'jestjs', 'dialog']",1328,True,0,1
Test with Easymock for cases testing,"<p>I'm currently working on unit testing, and I'm trying to create a test testing different cases for a single function. For example, I have the following function:</p>

<pre><code>public static String foo(Object arg0, Object arg1) {
    String returnValue = null;
    if(arg0.getName() != null &amp;&amp; arg0.getId() != null) {
        returnValue = ""Value 1"";
    } else if (arg1.getName() != null &amp;&amp; arg1.getId() != null ) {
        returnValue = ""Value 2"";
    }
    return returnValue;
}
</code></pre>

<p>I want to test the following cases :</p>

<ul>
<li>Case 1: <code>arg0.getName() == null</code> and <code>arg1.getName() == null</code></li>
<li>Case 2: <code>arg0.getName() != null</code> and <code>arg0.getId() != null</code> and <code>arg1.getName() == null</code></li>
<li>Case 3: <code>arg0.getName() == null</code> and <code>arg1.getName() != null</code> and <code>arg1.getId() != null</code></li>
</ul>

<p>etc...</p>

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

<pre><code>public void testFoo() {
    /** Setting up my mocks**/
    Obj arg0 = createMock(Obj.class);
    Obj arg1 = createMock(Obj.class);

    /** Setting my mocks behaviors **/

    // Case 1
    EasyMock.expect(arg0.getName()).andReturn(null);
    EasyMock.expect(arg1.getName()).andReturn(null);

    // Case 2
    EasyMock.expect(arg0.getName()).andReturn(""Jack"");
    EasyMock.expect(arg0.getId()).andReturn(1);
    EasyMock.expect(arg1.getName()).andReturn(null);

    // Case 3
    EasyMock.expect(arg0.getName()).andReturn(null);
    EasyMock.expect(arg1.getName()).andReturn(""Paul"");
    EasyMock.expect(arg1.getId()).andReturn(2);

    //End Cases
    EasyMock.replay(arg0_case1, arg0_case2, arg0_case3,
</code></pre>

<p>arg1_case1, arg1_case2, arg1_case3);</p>

<pre><code>    /** Testing **/

    // Case 1
    String expectedValue = null;
    String output = foo(arg0, arg1);
    assertEquals(expectedValue, output);

    // Case 2
    expectedValue = ""Value 1"";
    output = foo(arg0, arg1);
    assertEquals(expectedValue, output);

    // Case 3
    expectedValue = ""Value 2"";
    output = foo(arg0, arg1);
    assertEquals(expectedValue, output);
}
</code></pre>

<p>The issue I have with this test is that even if I set up my mocks for each test case, it seems that the set up fails to follow the order I choosed. I tried to add a <code>.once()</code>, <code>atLeastOnce()</code>, but even with that, it fails.</p>

<p>Do you have any solutions for this kind of test ? Maybe I should write a different test for each case ?</p>

<hr>

<p><strong>EDIT</strong>
I found a solution, thanks to @swayamraina's solution and some modification on my code. It's not the most efficient answer, but it does the job. Here's my edited code :</p>

<pre><code>public void testFoo() {
/** Setting my mocks behaviors **/

// Case 1
Obj arg0_case1 = createMock(Obj.class);
Obj arg1_case1 = createMock(Obj.class);
EasyMock.expect(arg0_case1.getName()).andReturn(null).anyTimes();
EasyMock.expect(arg1_case1.getName()).andReturn(null).anyTimes();

// Case 2
Obj arg0_case2 = createMock(Obj.class);
Obj arg1_case2 = createMock(Obj.class);
EasyMock.expect(arg0_case2.getName()).andReturn(""Jack"").anyTimes();
EasyMock.expect(arg0_case2.getId()).andReturn(1).anyTimes();
EasyMock.expect(arg1_case2.getName()).andReturn(null).anyTimes();

// Case 3
Obj arg0_case3 = createMock(Obj.class);
Obj arg1_case3 = createMock(Obj.class);
EasyMock.expect(arg0_case3.getName()).andReturn(null).anyTimes();
EasyMock.expect(arg1_case3.getName()).andReturn(""Paul"").anyTimes();
EasyMock.expect(arg1_case3.getId()).andReturn(2).anyTimes();

//End Cases
EasyMock.replay(arg0, arg1);

/** Testing **/

// Case 1
String expectedValue = null;
String output = foo(arg0_case1, arg1_case1);
assertEquals(expectedValue, output);

// Case 2
expectedValue = ""Value 1"";
output = foo(arg0_case2, arg1_case2);
assertEquals(expectedValue, output);

// Case 3
expectedValue = ""Value 2"";
output = foo(arg0_case3, arg1_case3);
assertEquals(expectedValue, output);
</code></pre>

<p>Like @swayamraina proposed in its answer, I created different mocks for each case test, and I add a <code>.anyTimes()</code> after each <code>EasyMock.expect().andReturn()</code>, and it works well.
I'll keep this post update on improvements I may implement.</p>
",https://stackoverflow.com/questions/59615204/test-with-easymock-for-cases-testing,"['java', 'unit-testing', 'junit', 'easymock']",376,True,0,1
PHPUnit framework keeps return class not found,"<p>The PHPUnit framework keeps returning this message</p>

<blockquote>
  <p>tests\IWPNoncesTest::testCreateNonce
  Error: Class 'tests\IWPNonces' not found</p>
  
  <p>C:\Users\user pc\Desktop\inpsyde\tests\IWPNoncesTest.php:25</p>
</blockquote>

<p>To start with, Am new to unit testing and I don't really know how it works. I tried following the offical  tutorial on the first page of the website [<a href=""https://phpunit.de/getting-started/phpunit-8.html][1]"" rel=""nofollow noreferrer"">https://phpunit.de/getting-started/phpunit-8.html][1]</a> but that too doesn't work as it also complain that the </p>

<blockquote>
  <p>Email class does not exits or so.</p>
</blockquote>

<p>My question is how do I work with the PHPUnit framework? And personally, this is the steps I already took
1. Create </p>

<blockquote>
  <p>phpunit.xml</p>
</blockquote>

<p>file in the root directory
and this is the code there</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit backupGlobals=""false""
    backupStaticAttributes=""false""
    colors=""true""
    convertErrorsToExceptions=""true""
    convertNoticesToExceptions=""true""
    convertWarningsToExceptions=""true""
    processIsolation=""false""
    stopOnFailure=""false""
    syntaxCheck=""false""
    bootstrap=""vendor/autoload.php""
&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=""WPNonces Test Suite""&gt;
            &lt;directory&gt;./tests&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;
    &lt;filter&gt;
        &lt;whitelist&gt;
            &lt;directory&gt;./classes&lt;/directory&gt;
        &lt;/whitelist&gt;
    &lt;/filter&gt;
&lt;/phpunit&gt;
</code></pre>

<ol start=""2"">
<li>Then create the classes folder that house the main code and in the classes folder, I </li>
</ol>

<blockquote>
  <p>createIWPNonces.php</p>
</blockquote>

<p>and this is the code there</p>

<pre><code>&lt;?php

declare(strict_types=1);

namespace IWPNoncesFunctions;

class IWPNonces{

    public function IWPCreateNonce(string $action): string {
        return wp_create_nonce($action);
    }

    public function IWPNonceURL(string $url, string $action): string {
        return wp_nonce_url($url, $action);
    }



    public function IWPNonceField(string $action, string $field): string {
        return wp_nonce_field($action, $field);
    }

    public function IWPVerifyNonce(string $action, string $field, string $type): string{
        switch($type){
            if('field' == $type){
                if(!isset($_REQUEST['field']) || !wp_verify_nonce(['field'], 'action')){
                    return false;
                }else{
                    return wp_verify_nonce(['field'], 'action');
                }
            }
            break;

            if('url' == $type){
                if ( ! empty( $_REQUEST ) &amp;&amp; check_admin_referer( 'action', 'field' ) ){
                    return check_admin_referer( 'action', 'field' );
                }
            }
            break;

            if('ajax' == $type){
                return check_ajax_referer('$action', $security);
            }
            break;
            default:
                return 'Error, the type name does not exist in wp nonce verifier. Please, use a valid verifier';
            break;
        }
    }

    public function IWPVerifyURLNonce(string $url, string $action): string {
        if ( ! empty( $_REQUEST ) &amp;&amp; check_admin_referer( 'action', 'field' ) ){
            return check_admin_referer( 'action', 'field' );
        }
    }

    public function IWPVerifyFieldNonce(string $action, string $field): string {
        if(!isset($_REQUEST['field']) || !wp_verify_nonce(['field'], 'action')){
            return false;
        }else{
            return wp_verify_nonce(['field'], 'action');
        }
    }

    public function IWPVerifyAjaxNonce(string $url, string $action): string {
        if('ajax' == $type){
            return check_ajax_referer('$action', $security);
        }
    }
}
</code></pre>

<ol start=""3"">
<li>After this, I created the </li>
</ol>

<blockquote>
  <p>tests/IWPNoncesTest folder</p>
</blockquote>

<p>that house the script that PHPUnit will test and this is the script written for the test</p>

<pre><code>&lt;?php
declare(strict_types=1);


// Created by : Gbenga Ogunbule
// Location : Ijebu Ode
// Date : 18/07/19
// Time : 21:44

namespace tests;

use IWPNoncesFunctions;
use PHPUnit\Framework\TestCase;;

class IWPNoncesTest extends TestCase{
    /*private $createNonce;
    public function setUp() {
        $this-&gt;createNonce = new IWPNonces('action');
        #$this-&gt;createNonce = IWPCreateNonce('action');
    }*/


    public function testCreateNonce(){
        $createNonce = new IWPNonces();
        $createNonce-&gt;IWPCreateNonce('action');

        $this-&gt;assertSame(
            'action',
            $this-&gt;createNonce,
            'The verify Nonce(WPNonce) is different from the one created above'
        );
    }

    /*public function testVerifyURLNonce(){
        $verifyURLNonce = new IWPNonces();
        $verifyURLNonce-&gt;IWPVerifyURLNonce('localhost/index.php', 'action');

        $this-&gt;assertSame('action', $verifyURLNonce, 'Verified not');
    }

    public function  testVerifyFieldNonce(){
        $verifyFieldNonce = new IWPNonces();
        $verifyFieldNonce-&gt;IWPVerifyFieldNonce('action', 'action');

        $this-&gt;assertSame('action', $verifyFieldNonce, 'Failed');       
    }

    public function testVerifyAjaxNonce(){
        $verifyAjaxNonce = new IWPNonces();
        $verifyAjaxNonce-&gt;IWPVerifyFieldNonce('localhost/index.php', 'action'); 

        $this-&gt;assertSame('action', $verifyAjaxNonce, 'Failure');   
    }*/
}
</code></pre>

<ol start=""4"">
<li>Inside the </li>
</ol>

<blockquote>
  <p>composer.json</p>
</blockquote>

<p>file
I have this</p>

<pre><code>""autoload"": {
        ""psr-4"": {
            ""WPNoncesFunction\\"": ""classes"",
            ""tests\\"": ""tests""
        }
    },
</code></pre>
",https://stackoverflow.com/questions/59787404/phpunit-framework-keeps-return-class-not-found,"['php', 'phpunit', 'php-7']",85,True,0,1
The instance of entity type &#39;Game&#39; cannot be tracked because another instance with the key value is already being tracked,"<p>I am unit testing an application I made with an in-memory database using Entity Framework Core but I am running into a problem with one of my functions. I have so far tested getting a game by Id (it works), adding a game to the collection (it works too) and updating a game in the collection (it doesn't work).</p>

<p>The function code: </p>

<pre><code> [TestMethod()]
        public async Task UpdateGameAsyncTest()
        {
            //Arrange
            await CreateDb();

            GameDto gameDto = new GameDto()
            {
                Id = 2,
                Team1 = ""PSG"",
                Team2 = ""AZ"",
                Date = DateTime.UtcNow
            };

            //Act
            var id = await _gameService2.UpdateGameAsync(gameDto);
            var game = await _gameService2.GetGameAsync(id);

            //Assert
            Assert.AreEqual(""AZ"", game.Team1);
        }
</code></pre>

<p>UpdateGameAsync() in my service layer:</p>

<pre><code>public async Task&lt;int&gt; UpdateGameAsync(GameDto game)
        {
            var gameEntity = game.ToEntity();

            return await _gameRepository.UpdateGameAsync(gameEntity);
        }
</code></pre>

<p>UpdateGameAsync() in my repository layer:</p>

<pre><code>public async Task&lt;int&gt; UpdateGameAsync(Game game)
        {
            if (game.Result != null)
            {
                if (game.Result.Length == 3 &amp;&amp; game.Result.Substring(1, 1) == ""-"")
                {
                    game.typeResult = await CheckTypeResult(game.Result);
                }
            }
            _dbContext.Games.Update(game);

            return await AutoSaveChangesAsync();
        }
</code></pre>

<p>CreateDb(): </p>

<pre><code>public async Task CreateDb()
        {
            var options = new DbContextOptionsBuilder&lt;StrikeNetDbContext&gt;()
                .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                .EnableSensitiveDataLogging()
                .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
                .Options;

            var dbContext = new StrikeNetDbContext(options);

            if (await dbContext.Games.CountAsync() &lt;= 0)
            {
                Game g1 = new Game()
                {
                    Id = 1,
                    Team1 = ""FCB"",
                    Team2 = ""BVB"",
                    Date = DateTime.UtcNow
                };
                Game g2 = new Game()
                {
                    Id = 2,
                    Team1 = ""PSG"",
                    Team2 = ""PSV"",
                    Date = DateTime.UtcNow
                };
                Game g3 = new Game()
                {
                    Id = 3,
                    Team1 = ""Ajax"",
                    Team2 = ""Feyenoord"",
                    Date = DateTime.UtcNow
                };
                dbContext.Games.Add(g1);
                dbContext.Games.Add(g2);
                dbContext.Games.Add(g3);
                await dbContext.SaveChangesAsync();
            }

            var gameRepository = new GameRepository(dbContext);
            _gameService2 = new GameService(gameRepository);
        }
</code></pre>

<p>When running the test I am running into the error: ""The instance of entity type 'Game' cannot be tracked because another instance with the key value '{Id: 2}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.""</p>

<p>For comparing purposes, here is the adding function that DOES work: </p>

<pre><code>[TestMethod()]
        public async Task AddGameAsyncTest()
        {
            //Arrange
            await CreateDb();

            GameDto game = new GameDto()
            {
                Team1 = ""Juve"",
                Team2 = ""Real"",
                Date = DateTime.UtcNow
            };

            //Act
            var id = await _gameService2.AddGameAsync(game);
            var expected = await _gameService2.GetGameAsync(id);

            //Assert
            Assert.AreEqual(""Juve"", expected.Team1);
        }
</code></pre>

<p>I have tried several things that answers to similar questions suggested but none of them work for me. I do have my repository en service scoped in Startup.cs, and detaching the entities in the createdb() function als doesn't seem to work. Does anyone have any other idea?</p>
",https://stackoverflow.com/questions/62217908/the-instance-of-entity-type-game-cannot-be-tracked-because-another-instance-wi,"['c#', 'visual-studio', 'unit-testing', 'entity-framework-core', 'in-memory-database']",1028,True,0,1
Jest unit tests with useRoute from react-navigation,"<p>We recently upgraded our react native codebase to version 5 of React Navigation and along the way we refactored a couple components from class components to functional components. This means we are using hooks like useNavigation() and useRoute().</p>
<p>I am having a difficult time figuring out how to get around an issue that I am facing when we are doing unit testing.  It would appear that the state of the navigation and route props aren't available to the test when it runs.  For example, I get the following error from Jest:</p>
<pre><code>● &lt;EULA /&gt; › Rendering › should match to snapshot

    TypeError: Cannot read property 'name' of undefined

      27 |   const route = useRoute();
      28 |   const authContext = useContext(AuthContext);
    &gt; 29 |   const isAcceptPP: boolean = route.name === &quot;AcceptEULA&quot;;
         |                                     ^
</code></pre>
<p>This error leads me to believe that when line 27 runs in the context of the unit test it isn't actually returning a route object from useRoute().  This error shows up on all of my tests for the file.</p>
<p>This is what the test looks like currently and I tried mocking the useRoute and just making route part of props, but these didn't seem to do much of anything:</p>
<pre><code>import React from &quot;react&quot;;
import { render, fireEvent, waitFor } from &quot;@testing-library/react-native&quot;;
import { WebView } from &quot;react-native-webview&quot;;
import { Alert } from &quot;react-native&quot;;

import EULA from &quot;../src/screens/EULA&quot;;
import { alertSpy } from &quot;../src/jest/spies&quot;;

describe(&quot;&lt;EULA /&gt;&quot;, () =&gt; {
  let props;
  let useRoute: jest.Mock;
  beforeEach(() =&gt; {
    useRoute = jest.fn();
    props = { navigation: { state: { routeName: &quot;AcceptEULA&quot; }, navigate: navigate }, route: { name: &quot;AcceptEULA&quot; } };
  });

  describe(&quot;Rendering&quot;, () =&gt; {
    it(&quot;should match to snapshot when accept EULA&quot;, async () =&gt; {
      const { toJSON, getByType } = render(&lt;EULA {...props} /&gt;);
      await waitFor(() =&gt; getByType(WebView));
      expect(toJSON()).toMatchSnapshot();
    });
</code></pre>
<p>I am still a bit new to Jest and I'm not really sure how I am supposed to go about with this because route isn't really part of navigation prop anymore, but I may just be overthinking this.</p>
",https://stackoverflow.com/questions/64470657/jest-unit-tests-with-useroute-from-react-navigation,"['react-native', 'unit-testing', 'jestjs', 'react-hooks', 'react-navigation']",5701,True,6,1
Is there any way to mock Pundit policy authorize in request specs?,"<p>I am using Pundit for authorization on my Rails app and I am unit testing my requests. 
I have already successfully tested the policy but now I want to verify that my request is using that policy. 
I want to do it in a generic way, that I can use in ANY request spec (regardless of the controller, the action, and the policy). 
To be honest at this point I would be conformed with a way of saying ""expect any policy to receive authorize"", generic to all requests. </p>

<p>For the index action (that uses the policy scope) it was easy:</p>

<p>In the request describe I say </p>

<pre><code>RSpec.describe 'GET /companies', type: :request do
  include_context 'invokes policy scope'
end
</code></pre>

<p>And then I defined the shared context as:</p>

<pre><code>RSpec.shared_context 'invokes policy scope', shared_context: :metadata do
  before do
    expect(Pundit).to receive(:policy_scope!) do |user_context, relation|
      expect(user_context.user).to eq(user)
      expect(user_context.current_group).to eq(group)

      relation
    end
  end
end
</code></pre>

<p>But how do I do the same for the authorize method. I don't know which concrete policy will be the one receiving it, neither which is the concrete controller that will invoke the <code>authorize</code>. </p>

<p>I don't understand how pundit does not provide a custom matcher to verify a certain request is actually invoking a given policy, or to ""simulate"" authorized/unauthorized scenarios so I test that my request returns the correct status code. </p>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/59758888/is-there-any-way-to-mock-pundit-policy-authorize-in-request-specs,"['ruby-on-rails', 'rspec', 'rspec-rails', 'pundit']",2350,True,5,3
Passing a C-styled integer array to an Ada function to retrieve the first element in the array,"<p>I am running an experiment in trying to link google test to ada95 for unit testing. I know ada has aunit and ahven, but this is just to see if this is possible and is outside of the scope of my question. I have successfully been able to do simple functions and procedures with the basic data types. The next thing I would like to try to do is similar to the following:</p>
<p>Here is the main.cpp file:</p>
<pre><code>#include &lt;stdio.h&gt;
#include &lt;gtest/gtest.h&gt;

extern &quot;C&quot; {
  int firstElement(int buffer[]);
}

TEST(tryTest, checkBuffer){
   int buffer[10] = {10,1,6,4,3,2,1,3,4,6};
   ASSERT_EQ(buffer[0],firstElement(buffer));
}

int main(int argc, char ** argv) {
  testing::InitGoogleTest(&amp;argc, argv);
  return RUN_ALL_TESTS();
}
</code></pre>
<p>for simplicity I will just put the ads file:</p>
<p>Lib_test.ads</p>
<pre><code>with Interfaces.C;
with Interfaces.C.Pointers;
package Lib_Test is

  function FirstElement(a: Interfaces.C.Pointers) return Interfaces.C.Int;
  pragma Export(C,FirstElement,&quot;firstElement&quot;);
end Lib_Test;
</code></pre>
<p>I know in c you are passing in the pointer to the first element not the entire array for the function. That is why I tried to use Interfaces.C.Pointers for the data type but I got the following error</p>
<pre><code>subtype mark required in this context
found &quot;Pointers&quot; declared at i-cpoint.ads:44
</code></pre>
<p>I have not found a good example of using other array types besides char arrays. Can someone show me how I can use Interfaces.C.Pointers for an integer array or even how I can fix this, I believe it is just my data type in the parameter of the function. I want to be able to access the c integer array in the ada function.</p>
<p>Thank you all!</p>
",https://stackoverflow.com/questions/62585930/passing-a-c-styled-integer-array-to-an-ada-function-to-retrieve-the-first-elemen,"['c', 'googletest', 'ada']",179,True,5,2
"Spring AOP with Mock, Spy. AspectJProxyFactory cannot addAspect Mock instance","<p>I am trying unit tests where an aspect class works well while unit testing.</p>
<p>Situtation.</p>
<ul>
<li>upgrade Spring Boot from 1.5.9 -&gt; 2.3.1.</li>
<li>Mockito, Junit frameworks are bumped up (mockito-core 1.10.19 -&gt; 3.3.3)</li>
</ul>
<p>I have a problem that unit tests for Spring AOP (internally AspectJ) will not pass while upgrading. The cause is from where <code>AbstractAspectJAdvisorFactory</code> class validates whether a given aspect class is a real aspect class or not.</p>
<p>My code</p>
<pre><code>    @Mock
    private RepositoryAspect aspect;

    @InjectMocks
    private NicknameRepository nicknameRepository;

    @Before
    public void setup() {

        AspectJProxyFactory aspectJProxyFactory = new AspectJProxyFactory(nicknameRepository);
        aspectJProxyFactory.addAspect(aspect); // fails 
        nicknameRepository = aspectJProxyFactory.getProxy();
    }

</code></pre>
<p><a href=""https://github.com/spring-projects/spring-framework/blob/0819a9fcc9a1168521995e0bac7de5633a819780/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java#L105-L110"" rel=""nofollow noreferrer"">https://github.com/spring-projects/spring-framework/blob/0819a9fcc9a1168521995e0bac7de5633a819780/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java#L105-L110</a></p>
<pre><code>public void validate(Class&lt;?&gt; aspectClass) throws AopConfigException {
    // If the parent has the annotation and isn't abstract it's an error
    if (aspectClass.getSuperclass().getAnnotation(Aspect.class) != null &amp;&amp;
            !Modifier.isAbstract(aspectClass.getSuperclass().getModifiers())) {
        throw new AopConfigException(&quot;[&quot; + aspectClass.getName() + &quot;] cannot extend concrete aspect [&quot; +
                    aspectClass.getSuperclass().getName() + &quot;]&quot;);
    }
...
</code></pre>
<p>It worked as normal. However, after upgrading from mockito-core 1.10.19 to 3.3.3, I found the validation fails due to different wrapped Mock class.</p>
<pre><code>1.10.19
&lt;instance&gt;$$EnhancerByMockitoWithCGLIB =&gt; not classified as a Mock class

3.3.3
&lt;instance&gt;$$MockitoMock =&gt; classified wrapped Mock class, not an aspect class
</code></pre>
<p>My research is below. I just found Spring AOP does not use Mockito as an injected aspect, but a real instance and its variables. I couldn't find a right way expect the code. How can I try with Mockito?</p>
<p><a href=""https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.html"" rel=""nofollow noreferrer"">https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.html</a></p>
<p><a href=""http://useof.org/java-open-source/org.springframework.aop.aspectj.annotation.AspectJProxyFactory"" rel=""nofollow noreferrer"">http://useof.org/java-open-source/org.springframework.aop.aspectj.annotation.AspectJProxyFactory</a></p>
<p><a href=""https://github.com/spring-projects/spring-framework/blob/3aa2605fdaa56d5c007f476f3f9bd1c550ec368c/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java"" rel=""nofollow noreferrer"">https://github.com/spring-projects/spring-framework/blob/3aa2605fdaa56d5c007f476f3f9bd1c550ec368c/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java</a></p>
",https://stackoverflow.com/questions/64856169/spring-aop-with-mock-spy-aspectjproxyfactory-cannot-addaspect-mock-instance,"['unit-testing', 'junit', 'mockito', 'spring-aop']",842,False,4,1
Problem in writing &quot;DivideByZero&quot; Unit test case using CPPUnitTest in Visual Studio 2019 C++,"<p>Unit testing means writing code that verifies individual parts, or units, of an application or library. A unit is the smallest testable part of an application. Unit tests assess code in isolation. In C++ this means writing tests for methods or functions.
I am writing a basic calculator program and trying to use CPPUnitTest to test the code in Visual studio 2019.After that I have to build this in Jenkins too.
Please don't judge .. I am writing unit Test for the 1st time ..
this is my Calculator.cpp</p>

<pre><code>#include &lt;iostream&gt;
#include ""Calc.h""
using namespace std;

int main()
{
        Calc obj;
        float a, b;
        cin &gt;&gt; a &gt;&gt; b;
        int menu;
        cout &lt;&lt; ""Enter what operation you want(1-4);"" &lt;&lt; endl;
        cout &lt;&lt; ""1. Addition"" &lt;&lt; endl;
        cout &lt;&lt; ""2. Subtraction"" &lt;&lt; endl;
        cout &lt;&lt; ""3. Multiplication"" &lt;&lt; endl;
        cout &lt;&lt; ""4. Division"" &lt;&lt; endl;
        cin &gt;&gt; menu;
        switch (menu)
        {
        case 1:obj.add(a, b);
            break;
        case 2:obj.sub(a, b);
            break;
        case 3:obj.multiply(a, b);
            break;
        case 4:
            try
            {
                obj.divide(a, b);
            }
            catch (std::runtime_error&amp; e)
            {
                cout &lt;&lt; e.what() &lt;&lt; ""\n"";
            }
            break;
        default:
        {
            cout &lt;&lt; ""Invalid input"" &lt;&lt; endl;
        }
    }
}
</code></pre>

<p>This is class Calc or ""Calc.h""
Here I have used <code>std::runtime_error</code> to throw error on division bye zero</p>

<pre><code>#pragma once
#include &lt;stdexcept&gt;
class Calc {

public:
    float add(float a, float b)
    {
        return a + b;
    }
    float sub(float a, float b) {

        return  a - b;
    }

    float multiply(float a, float b) {
        return  a * b;
    }

    float divide(float a, float b) {
        if (b == 0)
        {
            throw std::runtime_error(""Division by zero condition!"");
        }
        return a / b;
    }

};
</code></pre>

<p>I am trying to write unit test using CPPUnitTest for my code.
I have written code for add and subtract using <code>assert::AreEqual</code> but for divide by zero condition, I don't know to write the test case.
this is my unit test code.</p>

<pre><code>#include ""pch.h""
#include ""CppUnitTest.h""
#include ""../Calculator/Calc.h""
#include &lt;stdexcept&gt;

using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace CalculatorTest
{
    TEST_CLASS(CalculatorTest)
    {
    public:
        Calc cal;
        TEST_METHOD(AddTest)
        {
            float k = cal.add(3, 4);
            Assert::AreEqual(7.0f,k);
        }
        TEST_METHOD(SubTest)
        {
            float k = cal.sub(3, 4);
            Assert::AreNotEqual(-2.0f, k);
        }
        TEST_METHOD(DivByZeroTest)
        {
            //what should I write here
        }
    };
}
</code></pre>

<p>Please help me to write the test method for this .
Somewhere I read <code>CPPUNIT_ASSERT_THROW(cal-&gt;divide(12,0), std::runtime_error);</code> but this is not working in my case. How can I make <code>Assert::AreEqual</code>
Also suggest which else method I can use to increase my code coverage.</p>
",https://stackoverflow.com/questions/60506527/problem-in-writing-dividebyzero-unit-test-case-using-cppunittest-in-visual-stu,"['c++', 'visual-studio-2019', 'dividebyzeroexception', 'microsoft-cpp-unit-test']",727,True,4,1
How could I throw an exception using Fluent Assertions?,"<p>I am using a <a href=""https://github.com/thzinc/CloudMQTT"" rel=""nofollow noreferrer"">client</a> to interact with <a href=""https://www.cloudmqtt.com/docs/index.html"" rel=""nofollow noreferrer"">CloudMQTT API</a>. I am trying to <a href=""https://github.com/thzinc/CloudMQTT/blob/master/src/CloudMQTT.Client.Tests/WhenGettingUsers.cs#L28"" rel=""nofollow noreferrer"">create a user</a> but after trying the code provided below, I was not able to create a user. When using the code provided within the Github repository for this project, I noticed that I am unable to make use of a <code>ShouldThrow()</code> method (apparently it should be provided by <a href=""https://github.com/fluentassertions/fluentassertions"" rel=""nofollow noreferrer"">Fluent Assertions</a>).</p>

<p>I did find a <a href=""https://stackoverflow.com/questions/18240275/fluentassertions-shouldnotthrow-is-not-recognised-for-an-async-method-func"">post</a> on StackOverflow which looked very similar to the problem I am having. In the question is mentioned that FluentAssertions does not support async methods. In the example code for the client, however, I can see that the <code>ShouldThrow()</code> method is used regardless of this fact.</p>

<p>How could I get the <code>ShoudldThrow()</code> to work or do I even need it to work (because I think it is only supposed to be required in this code if you are applying unit testing)?</p>

<p>This is what a tried so far:</p>

<pre><code>public static async void CreateCloudUser(ICloudMqttApi client)
{
    var users = await client.GetUsers();
    Console.WriteLine($""Creating a user. Current users available: {users.Count}"");
    var expectedUser = new NewUser
    {
        Password = $""{Guid.NewGuid()}"",
        Username = $""staging-{Guid.NewGuid()}"",
    };

    var createUserResponse = await client.CreateUser(expectedUser);
    createUserResponse.IsSuccessStatusCode.Should().BeTrue();

    var actual = await client.GetUser(expectedUser.Username);
    actual.Should().NotBeNull();
    actual.Username.Should().Be(expectedUser.Username);

    //users.Should().Contain(u =&gt; u.Username == expectedUser.Username); // &lt;-- This throws an exception as well, but not of importance for this specific question.

    Func&lt;Task&gt; verifyUser = async () =&gt; await client.GetUser(expectedUser.Username);
    verifyUser.ShouldThrow&lt;ApiException&gt;() // &lt;-- Not recognized
            .And.StatusCode.Should().Be(HttpStatusCode.NotFound);

    Console.WriteLine($""Created a user. Current users available: {users.Count}"");
}
</code></pre>

<p>The client is defined in the way as provided in the documentation for the client right before calling the method:</p>

<pre><code>var client = CloudMqttApi.GetInstance(""username"", ""password"");
</code></pre>

<p>The user count will result in the same number before and after executing the method (which obviously should have incremented).</p>
",https://stackoverflow.com/questions/59749523/how-could-i-throw-an-exception-using-fluent-assertions,"['c#', 'mqtt', 'fluent-assertions']",2679,True,3,1
How to Ensure the apps info.plist contains a value for CFBundleIdentifier?,"<p>The app will not run on the simulator or the device but the trouble started when i went to get it on device. Running the latest and greatest Xcode and macOS. Any suggestions are most welcome.</p>

<p><a href=""https://i.stack.imgur.com/VEqno.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VEqno.png"" alt=""the challenge""></a></p>

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

<p>I suspect this issue is related to the unit testing targets but there is also odd behaviour in the ""Signing and Capabilities"", when i type in the bundle identifier ""com.sw.fw"" and hit enter the text in the the textfield vanishes and the ""Signing (Release)"" duplication appears below with that bundle id. I also created a fresh mobile provisioning profile with the appropriate bundle id <code>com.sw.fw</code></p>

<p>I also know that Xcode is doing something with the bundle id that i'm giving it because it appears on the <code>Certificates, Identifiers &amp; Profiles</code> page of <code>developer.apple.com</code> as can be seen here.</p>

<p><a href=""https://i.stack.imgur.com/zTOBO.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/zTOBO.png"" alt=""developer.apple.com""></a></p>

<p>Here's the target signing after hitting enter. </p>

<p><a href=""https://i.stack.imgur.com/wSEfZ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wSEfZ.png"" alt=""Target Signing""></a></p>

<p>Here's the ""Build Settings"" for the target</p>

<p><a href=""https://i.stack.imgur.com/9PazZ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9PazZ.png"" alt=""build settings for target""></a></p>

<p>Here's my info.plist it is the same as an app i have running on device.</p>

<p><a href=""https://i.stack.imgur.com/biVfN.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/biVfN.png"" alt=""info.plist""></a></p>

<p>Here's a unit test signing</p>

<p><a href=""https://i.stack.imgur.com/gZe9C.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gZe9C.png"" alt=""test signing""></a></p>

<p>Here's the ""Build Settings"" for a unit test target</p>

<p><a href=""https://i.stack.imgur.com/okxRH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/okxRH.png"" alt=""test build settings""></a></p>

<p>App Targets ""General"" pane doesn't let me type anything in the Bundle Identifier Field. You can see it reads <code>&lt;Multiple Values&gt;</code>.</p>

<p><a href=""https://i.stack.imgur.com/efuhv.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/efuhv.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/61527845/how-to-ensure-the-apps-info-plist-contains-a-value-for-cfbundleidentifier,"['ios', 'swift', 'xcode', 'bundle']",7131,True,3,6
Struts 2.5 running Junit 4 test and getting runtime errors finding a Struts plugin parent package,"<p>struts version: 2.5.25 - using the REST plugin
Junit 4.12</p>
<p>I am trying to setup the unit testing framework to begin testing struts actions and having issues getting a basic test to run.  It is currently complaining that it cannot find the parent package &quot;jinjava&quot; (this is a custom struts plugin which builds and runs fine outside of the unit test)</p>
<p>Is there anything that needs to be configured for the struts configuration to load the struts plugins?  Below is my current setup, along with the error I am seeing when the test is run.</p>
<p>Stack Trace:</p>
<pre><code>com.opensymphony.xwork2.config.ConfigurationException: Unable to load configuration.
    at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69)
    at org.apache.struts2.dispatcher.Dispatcher.getContainer(Dispatcher.java:970)
    at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:463)
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:496)
    at org.apache.struts2.util.StrutsTestCaseHelper.initDispatcher(StrutsTestCaseHelper.java:44)
    at org.apache.struts2.StrutsJUnit4TestCase.initDispatcher(StrutsJUnit4TestCase.java:256)
    at org.apache.struts2.StrutsJUnit4TestCase.setUp(StrutsJUnit4TestCase.java:245)
    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.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.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.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)
Caused by: com.opensymphony.xwork2.config.ConfigurationException: Parent package is not defined: jinjava
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.buildPackageContext(XmlConfigurationProvider.java:689)
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:539)
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:326)
    at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:108)
    at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:196)
    at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:66)
    ... 42 common frames omitted
</code></pre>
<p>Unit Test (spring beans are configured via annotations, we are not using any xml)</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = LoginActionSpringConfig.class)
public class LoginActionTest extends IwsStrutsSpringTestCase&lt;LoginAction&gt; {

    @Test
    public void getActionMapping() {
        ActionMapping mapping = getActionMapping(&quot;/security/login&quot;);
        Assert.assertNotNull(mapping);
        Assert.assertEquals(&quot;/security&quot;, mapping.getNamespace());
        Assert.assertEquals(&quot;login&quot;, mapping.getName());
    }


}
</code></pre>
<p>Below is the IwsStrutsSpringTestCase super class that is extending StrutsSpringJUnit4TestCase.  I have supplied a getConfigPath() including also attempting to put struts-plugin.xml in.</p>
<pre><code>public abstract class IwsStrutsSpringTestCase&lt;T&gt; extends StrutsSpringJUnit4TestCase&lt;T&gt; {

    @Override
    protected String getConfigPath() {
        return &quot;struts.xml, struts-plugin.xml&quot;;
    }
}
</code></pre>
<p>Below is the struts-plugin.xml from the jinjava plugin that is being complained about in the stack trace</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;!DOCTYPE struts PUBLIC
        &quot;-//Apache Software Foundation//DTD Struts Configuration 2.5//EN&quot;
        &quot;http://struts.apache.org/dtds/struts-2.5.dtd&quot;&gt;

&lt;struts&gt;

    &lt;constant name=&quot;struts.jinjava.basepath&quot; value=&quot;WEB-INF/jinJava&quot; /&gt;

    &lt;package name=&quot;jinjava&quot; extends=&quot;struts-default&quot;&gt;
        &lt;result-types&gt;
            &lt;result-type name=&quot;jinjava&quot; class=&quot;com.hs.struts.result.JinJavaResult&quot; /&gt;
        &lt;/result-types&gt;
    &lt;/package&gt;
&lt;/struts&gt;
</code></pre>
<p><strong>update 10/18/2020</strong>
<a href=""https://pastebin.pl/view/b5fcad7e"" rel=""nofollow noreferrer"">pom.xml</a> I would also like to note that the webapp directory is not following the default maven layout.  The web files are stored under /web</p>
<p><strong>update 11/1/2020</strong>
Below is my LoginActionSpringConfig.class as requested</p>
<pre><code>@Configuration
public class LoginActionSpringConfig {

    @Bean
    public IIwsAuthenticationService authenticationService() {
        return new IwsAuthenticationServiceTest();
    }

    @Bean
    public ISecurityLogDao securityLogDao() {
        return new SecurityLogDaoTest();
    }

    @Bean
    public IUsersDepartmentDao usersDepartmentDao() {
        return new UsersDepartmentDaoTest();
    }

    @Bean
    public IDepartmentDao departmentDao() {
        return new DepartmentDaoTest();
    }

    @Bean
    public IwsCookieInterface iwsCookie() {
        return new IwsCookieTest();
    }

}
</code></pre>
",https://stackoverflow.com/questions/64393937/struts-2-5-running-junit-4-test-and-getting-runtime-errors-finding-a-struts-plug,"['java', 'struts2', 'junit4']",158,True,2,1
Flask unit tests not closing port after each test,"<p>I'm doing some unit testing for a flask application. A part of this includes restarting the flask application for each test. To do this, I'm creating my flask application in the <code>setUp()</code> function of my <code>unitest.TestCase</code>, so that I get the application in its fresh state for each run. Also, I'm starting the application in a separate thread so the tests can run without the flask application blocking.</p>

<p>Example below:</p>

<pre class=""lang-py prettyprint-override""><code>import requests
import unittest
from threading import Thread

class MyTest(unittest.TestCase):

    def setUp(self):
        test_port = 8000
        self.test_url = f""http://0.0.0.0:{str(test_port)}""
        self.app_thread = Thread(target=app.run, kwargs={""host"": ""0.0.0.0"", ""port"": test_port, ""debug"": False})
        self.app_thread.start()

    def test_a_test_that_contacts_the_server(self):
        response = requests.post(
            f""{self.test_url}/dosomething"",
            json={""foo"": ""bar""},
            headers=foo_bar
        )
        is_successful = json.loads(response.text)[""isSuccessful""]
        self.assertTrue(is_successful, msg=json.loads(response.text)[""message""])

    def tearDown(self):
        # what should I do here???
        pass
</code></pre>

<p>This becomes problematic because when the tests that come after the initial test run, they run into an issue with port <code>8000</code> being used. This raises <code>OSError: [Errno 98] Address already in use</code>.</p>

<p>(For now, I've built a workaround, where I generate a list of high ranged ports, and another list of ports used per test, so that I never select a port used by a previous test. This work around works, but I'd really like to know the proper way to shut down this flask application, ultimately closing the connection and releasing/freeing that port.)</p>

<p>I'm hopeful that there is a specific way to shutdown this flask application in the <code>tearDown()</code> function.</p>

<p><strong>How should I go about shutting down the flask application in my <code>tearDown()</code> method?</strong></p>
",https://stackoverflow.com/questions/59816374/flask-unit-tests-not-closing-port-after-each-test,"['python', 'multithreading', 'unit-testing', 'flask', 'multiprocessing']",1274,True,2,1
Double Reference Causing Issues in Intellisense,"<p>First i explain our current project structure, then problem statement</p>

<p>I have a plugin project for CRM, and that project is referencing another service project. In order to deploy the project i am using ILMerge , so when plugin project compiled , it will contain all Service Project contract and models also.I have created unit test project also on the same solution, i have written test methods for Service Project , (by referring to Service Project) .All Test methods are working fine</p>

<p>Now we have changed our strategy to do the unit testing on plugin project instead of Service Project. So i remove the reference of service and added the reference of Plugins,All the unit test are still pass on run time. because on run time assembly internally contains service class attributes and methods.</p>

<p>But on editing the unit test, we lost the intellisense help from Visual Studio because we are not directly referring Service Project, if i try to refer service &amp; plugin both, then getting compile time error saying that these classes exists via plugins.</p>

<p>Here i want to use intellisense to make better code, and don't want double reference issue also.</p>

<p>Can some one help on this</p>
",https://stackoverflow.com/questions/62078065/double-reference-causing-issues-in-intellisense,"['c#', '.net', 'visual-studio', 'ilmerge']",117,False,2,1
SpringBoot @interface to summarize different annotations,"<p>I have an own annotations for Unit testing which looks like</p>

<pre><code>@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles(""test"")
@Transactional(rollbackFor = MyException.class)
public @interface DefaultTestAnnotations {
}
</code></pre>

<p>My different test classes are annotated like</p>

<pre><code>@RunWith(SpringRunner.class)
// @SpringBootTest() &lt;--------------(1)
@DefaultTestAnnotations
public class MyTest1 extends Basic4Tests {
</code></pre>

<p>When I run <code>MyTest1</code> individually than it succeed. If I run it within an larger compound it fails due to some strange DB entities failures. I skip the details for the sake of brevity. </p>

<p>When I uncomment (1) than the tests - either individually or in a compound - succeeds. Now I thought that the anntoation 
<code>@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)</code> 
is already enough. But obviously not.</p>

<p>Has anybody an idea</p>

<ul>
<li>What can be summarized in the <code>@interface</code> declaration? In sense of that these are used and are 'meaningful'</li>
<li>Why do I need to specify the <code>@SpringBootTest()</code> again? I thought declaring in the <code>interface</code> is sufficient.</li>
</ul>

<p><strong>UPDATE</strong>:</p>

<p>'to some strange DB entities failures' - means that the test saves data into the DB and when retrieving it fails to restore enums properly. The raised exceptions indicate that some spurious data is retrieved which seems to be never stored. Tracking the specific issue is out of scope for this question since I found a solution - which I do <strong>NOT</strong> understand. To avoid running into similar issues I want more clarity how <code>@interface</code> could be used.</p>
",https://stackoverflow.com/questions/61474599/springboot-interface-to-summarize-different-annotations,"['java', 'spring-boot', 'junit']",50,False,1,1
Stuck with unit testing largest number in array,"<p>I am a bit new to C# and unit testing, and we have an assignment in school that I have a hard time understanding, and under the circumstances of corona and school at home, it has been difficult for me to get help from my teacher.</p>

<p>My assignment is to make a method that finds the largest number in an array, and then test it. The array shall also be allowed to be empty.</p>

<p>This is what I have so far:</p>

<pre><code>public class Large
{
    public int Find(int[] mynumbers)
    {
        int mylargest = mynumbers[0];

        for (int i = 0; i &lt; mynumbers.Length; i++)
        {
            if (mynumbers[i] &gt; mylargest) mylargest = mynumbers[0];
        }
        return mylargest;
    }
}
</code></pre>

<p>My teacher made this method but I don't really understand the loop.
I tried to make a test method, but it keeps returning the first integer in my array, as the expected number.</p>

<pre><code>[TestMethod]
public void TestMethod1()
{
    //arrange
    Large mynumber = new Large();

    //act
    int[] myarray = { 3, 5, 1, 7, 3, 8 };
    int result = mynumber.Find(myarray);

    //assert
    Assert.AreEqual(3, result);
}
</code></pre>

<p>When I try this, my test gets passed. But when I change the result (which should have been the biggest), it fails.</p>

<p>What am I not getting?</p>

<p>To sum up:</p>

<ul>
<li>I have to test my method, to see that it indeed finds the largest number</li>
<li>I have to test my method so it won't throw and exception when the array is empty</li>
<li>I don't understand it at all, and my teacher can't explain it to me...</li>
</ul>
",https://stackoverflow.com/questions/61442068/stuck-with-unit-testing-largest-number-in-array,"['c#', 'arrays', 'unit-testing', 'methods']",599,True,1,1
How to cover the test for form control in angular? (Stackblitz attached),"<p>I am making a simple application which has an input field and a button and on click of the button an api call was made and respective response is fetched.</p>

<p>Everything working fine with this.</p>

<p><strong>Things done as of now:</strong> I am making a validation and display the error message via a function like,</p>

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

<pre><code>controlErrors(formControl: AbstractControl | FormControl): string {
    if (
      formControl &amp;&amp;
      formControl.touched &amp;&amp;
      formControl.invalid &amp;&amp;
      formControl.errors
    ) {
      return Object.keys(formControl.errors)[0];
    } else {
      return null;
    }
  }
</code></pre>

<p>And in <code>HTML</code> template adding the validation message like,</p>

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

<pre><code>  &lt;form [formGroup]=""userForm"" novalidate&gt;
      &lt;input
        class=""email-input mat-body-1""
        type=""email""
        formControlName=""email""
      /&gt;
      &lt;button class=""subscribe mat-body-2"" [disabled]=""userForm.invalid || submitted"" (click)=""subscribeEmail()""&gt;
        Subscribe
      &lt;/button&gt;
      &lt;span *ngIf=""controlErrors(userForm.get('email')); let error""&gt;{{
        error
      }}&lt;/span&gt;
    &lt;/form&gt;
</code></pre>

<p>I have written test case to cover the control errors (as other test were already covered) like,</p>

<p><strong>hello.component.spec.ts</strong>:</p>

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

    it('should return null if !formControl', () =&gt; {
      const result = component.controlErrors(null);
      expect(result).toBeNull();
    });

    it('should return null if formControl is untouched', () =&gt; {
      const formControl = new FormControl();
      const result = component.controlErrors(formControl);
      expect(result).toBeNull();
    });

  });
</code></pre>

<p><strong>Issue:</strong> And the issue is while running the test coverage it is showing that the <strong>branch (yellow highlighted) and statement(red highlighted) not covered</strong> like,</p>

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

<p>Requirement: Kindly please help me to cover these tests of control errors completely so that this spec file will have 100% test coverage.</p>

<p><strong>Working test case written stackblitz:</strong> <strong><a href=""https://stackblitz.com/edit/angular-testing-x5rx7s"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/angular-testing-x5rx7s</a></strong></p>

<p>As I am a beginner in angular unit testing please guide me with right solution.</p>

<p>Big thanks in advance.</p>

<p><strong>Update:</strong></p>

<p>Based on the comment by @Marc, I have tried like,</p>

<pre><code>it('should return invalid formControl if touched with invalid email', () =&gt; {
  const formControl = new FormControl('test');
  formControl.touched;
  fixture.detectChanges();
  const result = component.controlErrors(formControl);
  expect(result).toBeNull();
});
</code></pre>

<p>But it results in the same issue like the above screenshot.. Can anyone please help me how should I need to achieve the result of full test coverage?</p>
",https://stackoverflow.com/questions/62153001/how-to-cover-the-test-for-form-control-in-angular-stackblitz-attached,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",953,False,1,0
Module moment not found after installing react-native-community/netinfo,"<p>I am facing the issue ""react-native-community/netinfo"" while running my react-native project.</p>

<p>I have reinstall this module but get the same error again.
Before I run my application, I run Yarn and pod install, that run successfully, but after that it is showing this error that I have shown in the in this image. How can I resolve this error to run my project?</p>

<p>I am attaching the error and followed the given steps but it did not work for me.</p>

<blockquote>
  <p>Unhandled JS Exception: @react-native-community/netinfo: NativeModule.RNCNetInfo is null. To fix this issue try these steps:</p>
  
  <ul>
  <li>Run <code>react-native link @react-native-community/netinfo</code> in the project root.</li>
  <li>Rebuild and re-run the app.</li>
  <li>If you are using CocoaPods on iOS, run <code>pod install</code> in the <code>ios</code> directory and then rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.</li>
  <li>Check that the library was linked correctly when you used the link command by running through the manual installation instructions in the README.</li>
  <li>If you are getting this error while unit testing you need to mock the native module. Follow the guide in the README</li>
  </ul>
</blockquote>
",https://stackoverflow.com/questions/60427887/module-moment-not-found-after-installing-react-native-community-netinfo,"['xcode', 'react-native', 'cocoapods', 'yarnpkg']",376,False,1,0
Flutter unit testing - unable to pump full widget tree,"<p>I am just getting started with unit testing in Flutter, and I have hit a bit of a wall. I have a fairly simple app located here:
<a href=""https://github.com/chuckntaylor/kwjs_flutter_demo"" rel=""nofollow noreferrer"">https://github.com/chuckntaylor/kwjs_flutter_demo</a></p>

<p>The app is essentially a list view of events where you can tap on one to read more details about the event.</p>

<p><img src=""https://res.cloudinary.com/chucktaylor/image/upload/v1590504833/kwjsApp-optimized.gif"" alt=""KWJS Flutter App in action""></p>

<p>I have two screens for this: <code>events_screen.dart</code> for the list view, and <code>event_screen.dart</code> for the details. I have been trying to write my tests in <code>events_screen_test.dart</code></p>

<p>My testing difficulties are with the events screen (the list view). After running <code>await tester.pumpWidget(MaterialApp(home: EventsScreen())</code> I can use <code>find.text('Events')</code> for example to find the title in the AppBar, but I cannot find any of the elements that make up the list.</p>

<p>To clarify further. I am using <code>get_it</code> as a serviceLocator to get the viewModel for the EventsScreen when it loads. The viewModel is the <code>ChangeNotifierProvider</code>, and EventsScreen contains a <code>Consumer</code> to update the list. in EventsScreen <code>initState()</code>, it calls loadEvents() on the viewModel. After loadEvents() is done, the viewModel calls notifyListeners(), so that EventsScreen can update.</p>

<p>How do I ensure that all these steps occur so that I can properly test if the EventsScreen is rendering properly?</p>

<p>I could be approaching this all wrong, so any advice is appreciated.</p>
",https://stackoverflow.com/questions/62029967/flutter-unit-testing-unable-to-pump-full-widget-tree,"['unit-testing', 'flutter', 'testing', 'dart']",1596,True,1,2
Unit testing by CTest of Cross-compiled Project,"<p>I am developing hobby OS which is cross-compiled to other architecture than my development PC and is run in QEMU emulator.</p>
<p>I am trying to introduce unit testing of the source files I develop for my kernel but to let them run on my development machine rather than in QEMU on my target.</p>
<p>In order to cross-compile my sources, I use the toolchain file which uses my custom GCC toolchain. As coming from CMake principle of toolchain file usage, the toolchain file is set up prior to <code>project(...)</code> definition in my root <code>CMakeLists.txt</code> file.</p>
<p>My question is how to build my test executables for my dev machine (x86_64) using the built-in GCC while cross-compiling my kernel binary for target platform... I do not know how to set <code>CMAKE_CXX_COMPILER</code> / <code>CMAKE_C_COMPILER</code> cmake variables specifically for each use case (testing, target build)</p>
<p>To have a look at my particular project, please feel free to navigate here:<a href=""https://gitlab.com/revolta/revolta"" rel=""nofollow noreferrer"">https://gitlab.com/revolta/revolta</a></p>
<p>I would like to add <code>test/</code> to my project root including selected sources from <code>source/...</code> and manage it somehow from my root <code>CMakeLists.txt</code></p>
<p>Thanks in advance for any concept ideas and help! Cheers Martin</p>
",https://stackoverflow.com/questions/64927375/unit-testing-by-ctest-of-cross-compiled-project,"['unit-testing', 'cmake', 'cross-compiling']",1051,True,0,1
Testing React with enzyme and jest giving error Cannot find module &#39;@babel/polyfill/lib/noConflict&#39; from &#39;index.js&#39;,"<p>I'm new to unit testing and I've just started writing unit tests for my react project. My project is created using create-react-app and I've installed required testing libraries such as enzyme, enzyme-adapter-react-16, and jest-enzyme.</p>
<p>I've created a new file setupTests.js inside the src directory and add enzyme configurations.</p>
<p>When I'm trying to run the unit test using the command <code>npm test</code> I'm receiving the below error and because of that my test is failing.</p>
<pre><code>src/App.test.js
● Test suite failed to run

Cannot find module '@babel/polyfill/lib/noConflict' from 'index.js'

However, Jest was able to find:
    './ComponentName.jsx'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string
</code></pre>
<p>Below is the screenshot of the error
<a href=""https://i.stack.imgur.com/27wLn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/27wLn.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/cU89k.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cU89k.png"" alt=""enter image description here"" /></a></p>
<p>Below is the setupTests.js file looks like inside the src directory</p>
<pre><code>import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-enzyme';

configure({ adapter: new Adapter() });
</code></pre>
<p>Below is my test App.test.js file looks like where I'm just trying to console.log and here it's failing. If I remove App's import it will work.</p>
<pre><code>import React from 'react';
import App from './App'
import { shallow } from 'enzyme';

test(&quot;this is my first test&quot;, () =&gt; {
    console.log('this is my first test')
});
</code></pre>
<p>I'm trying this on WSL Ubuntu 18.04 LTS and Node 12.8.4</p>
<p>Can anyone please tell me where I'm making mistake and correct me and Kindly excuse if the question is repeated.</p>
<p>Thank you in advance.</p>
<p><strong>Update</strong></p>
<p>Here is the GitHub link where I tried to reproduce the error
<a href=""https://github.com/aashayamballi/react-jest-enzyme-testing-error"" rel=""nofollow noreferrer"">https://github.com/aashayamballi/react-jest-enzyme-testing-error</a></p>
<p>I'm assuming that inside components/TestComponent1.jsx I'm importing <code>import { HotTable } from &quot;@handsontable/react&quot;;</code> Because of this the test suite is failing and giving an error.</p>
",https://stackoverflow.com/questions/63934972/testing-react-with-enzyme-and-jest-giving-error-cannot-find-module-babel-polyf,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",1077,True,0,1
Testing firebase cloud functions - validate database changes,"<p>Based on the <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">documentation</a> for unit testing Cloud Functions, I understand how I could effectively test rather simple Cloud Functions by asserting a response to be what I would expect it. However, I have a few somewhat complex Cloud Functions, where on change of one type of data in my database, a number of private methods retrieve a few other types of data, make calculations on those, I then put a number of database update calls into an array of promises and call <code>Promise.all(my_array)</code> on it to complete my Cloud Function execution.</p>

<p>This results in the response being an array of variable length and composition, which is very difficult to validate.</p>

<p>Instead, I would prefer to be able to test Cloud Functions in a sequence something like below:</p>

<ul>
<li>Set an initial database</li>
<li>Trigger a Could Function</li>
<li>Check the updated database if all is as I expect</li>
</ul>

<p>Is it possible to do something like this with the <code>firebase-functions-test</code> library? How do I do it? I understand the above scenario is more of an integration test, still I'd like to know if said library would be able to handle it.</p>
",https://stackoverflow.com/questions/59609124/testing-firebase-cloud-functions-validate-database-changes,"['firebase', 'unit-testing', 'google-cloud-functions']",311,True,0,1
Python unittest with external depenincies,"<p>So I am confused how the mocking stuff works. patch in particular with external dependencies. So far I have seen examples like this one <a href=""https://stackoverflow.com/questions/32672906/how-to-mock-dependency-in-python"">how to mock dependency in python</a> where it shows how to mock out one of your own objects, but then uses things like &quot;with mock.patch.dict('os.environ', PLATFORM='X_PLATFORM'):&quot; to mock out the os.environ.</p>
<p>I have also seen examples like this <a href=""https://stackoverflow.com/questions/3942820/how-to-do-unit-testing-of-functions-writing-files-using-python-unittest"">How to do unit testing of functions writing files using python unittest</a> where they are using mock_open to mock os.open. But none of this seems to fit what I need.</p>
<p>Lets say you have a function as follows</p>
<pre><code>import tensorflow as tf

def load_model(self, model_path=None):
    if model_path is None:
        model_path = self.model_path
    graph_def = None
    with tf.gfile.GFile(model_path, &quot;rb&quot;) as file_handle:
        graph_def = tf.GraphDef.FromString(file_handle.read())
    if graph_def is None:
        print('Cannot find inference graph in tar archive.')
        raise
    try:
        with self.graph.as_default() as self.graph:
            tf.import_graph_def(graph_def, name='')
    except Exception as error:
        print(str(error))
        raise
    self.session = tf.Session(graph=self.graph)

    return True
</code></pre>
<p>How do you mock out all the tensorflow functions? I want to mock what the file_handle.read() call returns so I can control what is sent into the tf.GraphDef.FromString function, which I also want to mock. I just want some asserts that tell me if these functions are called with the data I feed it. If I control what FromString returns, that controls what goes into the tf.import_graph_def call as well. So I want to mock that as well and assert that it is called with the proper data as well. Anyone know how to do this?</p>
",https://stackoverflow.com/questions/63928057/python-unittest-with-external-depenincies,"['python', 'unit-testing']",118,False,0,1
Unit testing a controller action which calls a private method that uses HTTPClient,"<p>I am a newbie to C# and TDD. I am developing a product in which I need to write unit tests for some HTTP API calls. Below is how a controller looks like:</p>

<pre><code>public class CommunicationController : ControllerBase
{
 private readonly IHttpClientFactory _clientFactory;
 private readonly AppSettings _appSettings;

 public CommunicationController(IHttpClientFactory clientFactory, IOptions&lt;AppSettings&gt; appSettings)
 {
  _clientFactory = clientFactory;
  _appSettings = appSettings.Value;
 }

 [HttpPost]
 public async Task&lt;IActionResult&gt; PostEntity([FromBody] Entity entity)
 {
  if (entity.foo == null)
  {
   NoActionsMessage noActionsMessage = new NoActionsMessage
   {
    Message = ""No actions performed""
   };
   return Ok(noActionsMessage);
  }

  var accessTokenDatails = await GetAccessTokenDetailsAsync();
  var callUrl = ""http://someUrlGoesHere"";

  var json = JsonConvert.SerializeObject(entity);
  var content = new System.Net.Http.StringContent(json, Encoding.UTF8, ""application/json"");
  var request = new HttpRequestMessage(HttpMethod.Put, new Uri(callUrl))
  {
   Content = content
  };
  request.Headers.Add(""accessToken"", accessTokenDatails.AccessToken);

  return await InvokeHttpCall(request);
 }


 private async Task&lt;AccessTokenDetails&gt; GetAccessTokenDetailsAsync()
 {
  var appId = _appSettings.AppId;
  var appSecret = _appSettings.AppSecret;
  var refreshToken = _appSettings.RefreshToken;

  var request = new HttpRequestMessage(HttpMethod.Get, new Uri(""sometokenproviderUrl""));

  request.Headers.Add(""applicationId"", appId);
  request.Headers.Add(""applicationSecret"", appSecret);
  request.Headers.Add(""refreshToken"", refreshToken);

  var client = _clientFactory.CreateClient();

  var response = await client.SendAsync(request);

  if (response.IsSuccessStatusCode)
  {
   var responseStream = response.Content.ReadAsStringAsync();

   // [ALERT] the failing line in unit test - because responseStream.Result is just a GUID and this the the problem
   var result = JsonConvert.DeserializeObject&lt;AccessTokenDetails&gt;(responseStream.Result);

   return result;
  }
  else
  {
   throw new ArgumentException(""Unable to get  Access Token"");
  }
 }
}
</code></pre>

<p>This POST method which is calling a private method. By calling this post method with appropriate entity given:
 1. Should make a call to the token provider service and get the token
 2. Using the token, authenticate the service to add the entity</p>

<p><code>AccessTokenDetails</code> class looks is below:</p>

<pre><code>public sealed class AccessTokenDetails
{
 [JsonProperty(""accessToken"")]
 public string AccessToken { get; set; }

 [JsonProperty(""endpointUrl"")]
 public Uri EndpointUrl { get; set; }

 [JsonProperty(""accessTokenExpiry"")]
 public long AccessTokenExpiry { get; set; }

 [JsonProperty(""scope"")]
 public string Scope { get; set; }
}
</code></pre>

<p>Now when it comes to unit testing (I am using XUnit) I have a test method like below:</p>

<pre><code>public async Task Entity_Post_Should_Return_OK()
{
 / Arrange - IHttpClientFactoryHttpClientFactory
 var httpClientFactory = new Mock&lt;IHttpClientFactory&gt;();
 var mockHttpMessageHandler = new Mock&lt;HttpMessageHandler&gt;();
 var fixture = new Fixture();

 mockHttpMessageHandler.Protected()
  .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(""SendAsync"", ItExpr.IsAny&lt;HttpRequestMessage&gt;(), ItExpr.IsAny&lt;CancellationToken&gt;())
  .ReturnsAsync(new HttpResponseMessage
  {
   StatusCode = HttpStatusCode.OK,
   Content = new StringContent(fixture.Create&lt;string&gt;),
  });

 var client = new HttpClient(mockHttpMessageHandler.Object);
 client.BaseAddress = fixture.Create&lt;Uri&gt;();
 httpClientFactory.Setup(_ =&gt; _.CreateClient(It.IsAny&lt;string&gt;())).Returns(client);

 // Arrange - IOptions
 var optionsMock = new Mock&lt;IOptions&lt;AppSettings&gt;&gt;();
 optionsMock.SetupGet(o =&gt; o.Value).Returns(new AppSettings
 {
  AppId = ""mockappid"",
  AppSecret = ""mockappsecret"",
  RefreshToken = ""mockrefreshtoken""
 });

 // Arrange - Entity
 AddActionEntity entity = new Entity();
 entity.foo = ""justfoo"";

 // Act  
 var controller = new CommunicationController(httpClientFactory.Object, optionsMock.Object);
 var result = await controller.PostEntity(entity);

 // Assert  
 Assert.NotNull(result);
 Assert.IsAssignableFrom&lt;OkObjectResult&gt;(result);
}
</code></pre>

<p>This particular test case is failing in the when calling the <code>PostEntity</code> method as it failed to deserialize the <code>responseStream.Result</code> in the <code>GetAccessTokenDetailsAsync()</code> private method, to <code>AccessTokenDetails</code> in this unit test. The deserialization failed as the value of <code>responseStream.Result</code> is just a GUID string.</p>

<p>Can anyone please tell me that I am getting into a ""dependency inversion"" problem and tell me a way to overcome this?</p>

<p>I am thinking of separating the <code>GetAccessTokenDetailsAsync</code> to a different class, something like <code>AccessTokenProvider</code> and mock it to over come it - will it be a good approach? what could be a best approach to solve this problem.</p>
",https://stackoverflow.com/questions/61455068/unit-testing-a-controller-action-which-calls-a-private-method-that-uses-httpclie,"['c#', 'unit-testing', 'moq']",896,True,0,1
In what cases can there be such a situation when unit tests will run earlier than View is fully loaded?,"<p>I was stumbled upon <code>RunLoop.current.run(until: Date())</code> string in ViewController unit testing tutorial.
In article the author wrote: “ <em>The RunLoop.current.run(until: Date()) statement makes sure the run loop associated with the current thread has ample time to let the drawing operations to complete.</em>”</p>

<p>Here the code: </p>

<pre><code>class CreateOrderViewControllerTests: XCTestCase
{
 // MARK: - Subject under test

 var sut: CreateOrderViewController!
 var window: UIWindow!

 // MARK: - Test lifecycle

 override func setUp()
 {
   super.setUp()
   window = UIWindow()
   setupCreateOrderViewController()
   loadView()
 }

override func tearDown()
{
   window = nil
   super.tearDown()
}

// MARK: - Test setup

func setupCreateOrderViewController()
{
  let bundle = Bundle.main
  let storyboard = UIStoryboard(name: ""Main"", bundle: bundle)
sut = storyboard.instantiateViewController(withIdentifier: ""CreateOrderViewController"") as? CreateOrderViewController
}

func loadView()
{
    window.addSubview(sut.view)  
    RunLoop.current.run(until:Date())
}

func testCursorFocusShouldMoveToNextTextFieldWhenUserTapsReturnKey()
{
// Given


// Scroll to the top of table view so the first text field is visible and can actually become first responder
let firstSectionIndex = 0
let firstRowIndex = 0
sut.tableView.scrollToRow(at: IndexPath(row: firstRowIndex, section: firstSectionIndex), at: .bottom, animated: false)

// When
let currentTextField = sut.textFields[0]
let nextTextField = sut.textFields[1]
currentTextField.becomeFirstResponder()
_ = sut.textFieldShouldReturn(currentTextField)

// Then
XCTAssert(!currentTextField.isFirstResponder, ""Current text field should lose keyboard focus"")

XCTAssert(nextTextField.isFirstResponder, ""Next text field should gain keyboard focus"")
}
</code></pre>

<p>I read a few articles about RunLoop, and tried to replace   <code>RunLoop.current.run(until:Date())</code> with
<code>RunLoop.current.run(until:Date(timeIntervalSinceNow: 30))</code>. <a href=""https://i.stack.imgur.com/c6Tt4.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/c6Tt4.png"" alt=""enter image description here""></a>
and saw that all 30 seconds xcode did not proceed to the next process.</p>

<p>Then I conducted experiment with assigning view to window on background concurrent thread with <code>RunLoop.current.run(until:Date(timeIntervalSinceNow: 30))</code>.<a href=""https://i.stack.imgur.com/3sl9g.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3sl9g.png"" alt=""enter image description here""></a>
It also didn’t call any other processes on any threads for 30 seconds, that is, the system waited 30 seconds and at that time the process that was already running, it was being finalized, and again any other processes on any threads haven't been called for 30 seconds.</p>

<p>Then I looked on what thread the viewController initialization and window.addSubview() processes are running - it is <strong><code>Thread 1 Queue : com.apple.main-thread (serial)</code></strong>, then I looked on what thread test functions are running this is also <strong><code>Thread 1 Queue : com.apple.main-thread (serial)</code></strong>. Due to it is serial it is impossible that test functions is executing before viewController initialization and window.addSubview() processes are done. But some people wrote that it could be, when and why?</p>
",https://stackoverflow.com/questions/62076626/in-what-cases-can-there-be-such-a-situation-when-unit-tests-will-run-earlier-tha,"['ios', 'swift', 'multithreading', 'unit-testing', 'nsrunloop']",443,False,0,0
Python logging file handler not using specified handler,"<p>I am using a logger.conf file included below where I have two loggers three if you count root. OnPremLog is used in normal circumstances and I just recently created TestingLog for handling automated unit testing that requires to run the code not in the normal operational environment. When I implemented this new logger I now have a handler for each. </p>

<p>The issue is when I was running my OnPremCode using that logger as usual, the file handler is now behaving as if it was the testing handler (it is writing instead of appending). I want the test logger to just overwrite the log each time but normal operations I have dozens of scripts that write to the same log and should append. First is my implementation of the logger from a snippet of actual code then the conf file in entirety.</p>

<p>For those that want more background this is running on python 3.7 on windows and the automated build happens on some docker image of linux but that is not the issue being dealt with. </p>

<p>Implementation:</p>

<pre><code>logging.logFileFullPath = cfg.LogsFolder + cfg.onPremLogFile + T_STAMP + '.log'
logging.config.fileConfig(cfg.ScriptsFolder + cfg.LogConfFile)
LOGGER = logging.getLogger('OnPremLog')
</code></pre>

<p>After seeing the similar question and answer to it pointing to case sensitivity I checked and my references are case correct.</p>

<p>Conf File: </p>

<pre><code>[loggers]
keys=root,OnPremLog,TestingLog

[handlers]
keys=MainHand,OnPremHand,TestingHand

[formatters]
keys=MainForm

[logger_root]
level=NOTSET
handlers=MainHand

[logger_OnPremLog]
level=INFO
handlers=OnPremHand
qualname=OnPremLog
propagate=0

[logger_TestingLog]
level=INFO
handlers=TestingHand
qualname=TestingLog
propagate=0

[handler_MainHand]
class=StreamHandler
level=WARNING
formatter=MainForm
args=(sys.stdout,)

[handler_OnPremHand]
class=FileHandler
level=INFO
formatter=MainForm
args=(logFileFullPath, 'a')

[handler_TestingHand]
class=FileHandler
level=INFO
formatter=MainForm
args=(logFileFullPath, 'w')

[formatter_MainForm]
format=GACF~%(asctime)s~%(levelname)s~%(filename)s~%(name)s~%(message)s
datefmt=
class=logging.Formatter
</code></pre>
",https://stackoverflow.com/questions/61369294/python-logging-file-handler-not-using-specified-handler,"['python', 'logging']",41,False,0,0
How to use the data in the test resource folder during unit testing,"<p>I have a folder in my intellij project which has some .svg files, with the path <strong>""data/system/svgfiles1""</strong></p>

<p>I'm doing unit testing for a method that uses these .svg files.<br>
When I run my test locally every test is Ok. 
But, in Jenkins I get an error.</p>

<p>The reason for this error is that I use some .svg files locally that the test needs and they are not in jenkins. </p>

<p>Now, the method defines a path where the data is placed. I commented where the path is defined. 
As you can see, the path is hard coded. </p>

<pre><code> public Optional&lt;String&gt; content(final Record content, final int sides) {
            final Optional&lt;String&gt; path = Utils.findAttachmentPathById(
                ""./data/"" + DataController.Sides[sides], // here I get the path ""data/system/svgfiles1""
                content.getId()
        );
        if (!path.isPresent()) {
            return Optional.empty();
        }
        Optional&lt;String&gt; value1 = Optional.empty();
        Optional&lt;String&gt; value2 = Optional.empty();
        try {
            value2 = Optional.of(FileUtils.readFileToString(new File(path.get()), StandardCharsets.UTF_8));
        } catch (IOException ioException) {
            logger.error(""An exception"", ioException);
        }
        try {
            value1 = Optional.of(Record.format(value2.get(), content.getData()));
        } catch (Exception exception) {
            logger.error(""An exception"", exception);
        }
        return value1;
    }
</code></pre>

<p>Now I created a resource folder in the tests where I added these .svg files. 
The test method is this: </p>

<pre><code>   @Test
    public void exportZipPlateSvgContentTest() {
        // prepare
        Record record = new Record(recordValues); // record values are only some string values
        record.setId(1L);

        // expected
        Optional&lt;String&gt; expected = Optional.of(values) 

        // test
        Optional&lt;String&gt; result = platesService.content(record, 1); // this is the method under test 

        // run
        assertEquals(expected, result 
    }
</code></pre>

<p>As you can see in the test method. The path is not given as a parameter. The path is hard coded in the <strong>content</strong> method. </p>

<p>Since the path is hard coded in the method. Is it possible for the method to use a different path during testing? </p>

<p>Like, when I test it to say use the data from ""test/resources/data/svgfiles1""?</p>

<p>I would really appreciate any input. Please let me know to clarify anything. </p>
",https://stackoverflow.com/questions/60606576/how-to-use-the-data-in-the-test-resource-folder-during-unit-testing,"['java', 'junit']",281,False,0,1
What is the preferred method of running background tasks in IsolatedAsyncioTestCase?,"<p>I'm using pytest 5.4.3 to run asynchronous unit tests.</p>
<p>Typically I like to run an isolated server instance and perform the unit test cases together with the spinned up server. Currently I'm trying to perform asynchronous unit tests, running a uvicorn server instance.</p>
<p>Anywhere else, I'd use <strong><code>asyncio.gather</code></strong> for running tasks in parallel, but <code>asyncSetUp</code> method forces the use of <code>run_until_complete</code>, as seen in <code>_callAsync</code> implementation in <code>lib/python3.8/unittest/async_case.py:74</code>.</p>
<p>Any long-running task will therefore make the unit test stuck on beginning, until <code>KeyboardInterrupt</code> is raised. The interrupt, indeed, stops the server instance and continues to perform the individual test cases.</p>
<p>Using <code>asyncio.create_task</code> to schedule the coroutine on the loop will on the other hand freezes the process completely and needs to be killed. The code used in this case follows:</p>
<pre class=""lang-py prettyprint-override""><code>class HttpTestCase(IsolatedAsyncioTestCase):
    async def asyncSetUp(self):
        ...
        self.task = uvicorn.Server(server_config).serve()
        asyncio.create_task(self.task)
</code></pre>
<p>I've also noticed that it depends on the implementation of the long-running task. For example, running a <code>aiocoap</code> server instance works perfectly well, because the coroutine will finish after the server start and handles the running in the background itself:</p>
<pre class=""lang-py prettyprint-override""><code>class CoapTestCase(IsolatedAsyncioTestCase):
    async def asyncSetUp(self):
        ...
        self.server = await aiocoap.Context.create_server_context(...)

    async def asyncTearDown(self):
        await self.server.shutdown()
</code></pre>
<p>What is the correct way to achieve having long-running tasks in background and continue with unit testing? Running the server in separate thread/process is always an option, but I'd be interested in figuring out how to do this using just asyncio.<br />
Thanks for answers.</p>
",https://stackoverflow.com/questions/64523771/what-is-the-preferred-method-of-running-background-tasks-in-isolatedasynciotestc,"['python', 'asynchronous', 'python-asyncio']",780,False,4,0
C# Create Mock Configuration.GetSection(“Section:SubSection”) for objects list,"<h2>Objective</h2>
<p>Create a mock object, using Moq and XUnit, for loading the specific section &quot;Character/Skills&quot; to enhance the coverage in unit testing.</p>
<p>The SUT (in some point), loads the setting in the way</p>
<pre><code>var skills = Configuration.GetSection(“Character:Skills”);
</code></pre>
<p>From the following appSetting:</p>
<pre><code>{
    &quot;dummyConfig1&quot;: {
        &quot;Description&quot;: &quot;bla bla bla...&quot;,
    },
    &quot;Character&quot;: {
    &quot;Name&quot;: &quot;John Wick&quot;,
    &quot;Description&quot;: &quot;A retired hitman seeking vengeance for the killing of the dog given to him...&quot;,
    &quot;Skills&quot;: [
        {
        &quot;Key&quot;: &quot;CQC Combat&quot;,
        &quot;Id&quot;: &quot;15465&quot;
        },
        {
        &quot;Key&quot;: &quot;Firearms&quot;,
        &quot;Id&quot;: &quot;14321&quot;
        },
        {
        &quot;Key&quot;: &quot;Stealth&quot;,
        &quot;Id&quot;: &quot;09674&quot;
        },
        {
        &quot;Key&quot;: &quot;Speed&quot;,
        &quot;Id&quot;: &quot;10203&quot;
        }
    ],
    &quot;DummyConf2&quot;: &quot;more bla bla bla...&quot;
}
</code></pre>
<h2>Previous Reading</h2>
<p>Reading these posts (and other others, as result of Googling), I noticed that we can only use a primitive &quot;string&quot; datatype or else <em>new Mock&lt;IConfigurationSection&gt;</em> object (with no setting):</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/50201588/c-sharp-how-to-mock-configuration-getsectionfoobar-getliststring"">Stack Overflow - how to mock Configuration.GetSection(“foo:bar”)</a>,</li>
<li><a href=""https://www.pmichaels.net/2019/05/04/mocking-iconfiguration-extension-method/"" rel=""nofollow noreferrer"">Mocking IConfiguration extension method</a></li>
<li><a href=""https://dejanstojanovic.net/aspnet/2018/november/mocking-iconfiguration-getvalue-extension-methods-in-unit-test/"" rel=""nofollow noreferrer"">Mocking IConfiguration Getvalue() extension method in Unit Test</a></li>
</ul>
<p><strong>Constraint:</strong> Copying the appSetting file into the TestProject (or create a MemoryStream) to load the real settings could solve this scenario, but the test would be a &quot;Integration&quot; instead of &quot;Unit&quot;; since there is an I/O dependency.</p>
<h2>The approach</h2>
<p>The code's idea (shown later) is mocking each property (key/id) and then merging them in a tree similar to this:</p>
<ul>
<li>&quot;Character&quot; ------ Configuration to be read, using <code>GetSection()</code> and then <code>Get&lt;T&gt;()</code>
<ul>
<li>&quot;Skills&quot; ------ Configuration list with merged attribute
<ul>
<li>&quot;Key&quot; - &quot;CQC Combat&quot;   ------ Primitive value 1</li>
<li>&quot;Id&quot;  - &quot;15465&quot;        ------ Primitive value 2</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2>The Code</h2>
<pre><code>var skillsConfiguration = new List&lt;SkillsConfig&gt;
{
    new SkillsConfig { Key = &quot;CQC Combat&quot;   , Id = &quot;15465&quot; },
    new SkillsConfig { Key = &quot;Firearms&quot;     , Id = &quot;14321&quot; },
    new SkillsConfig { Key = &quot;Stealh&quot;       , Id = &quot;09674&quot; },
    new SkillsConfig { Key = &quot;Speed&quot;        , Id = &quot;10203&quot; },
};

var configurationMock = new Mock&lt;IConfiguration&gt;();
var mockConfSections = new List&lt;IConfigurationSection&gt;();

foreach (var skill in skillsConfiguration)
{
    var index = skillsConfiguration.IndexOf(skill);

    //Set the Key string value
    var mockConfSectionKey = new Mock&lt;IConfigurationSection&gt;();
    mockConfSectionKey.Setup(s =&gt; s.Path).Returns($&quot;Character:Skills:{index}:Key&quot;);
    mockConfSectionKey.Setup(s =&gt; s.Key).Returns(&quot;Key&quot;);
    mockConfSectionKey.Setup(s =&gt; s.Value).Returns(skill.Key);

    //Set the Id string value
    var mockConfSectionId = new Mock&lt;IConfigurationSection&gt;();
    mockConfSectionId.Setup(s =&gt; s.Path).Returns($&quot;Character:Skills:{index}:Id&quot;);
    mockConfSectionId.Setup(s =&gt; s.Key).Returns(&quot;Id&quot;);
    mockConfSectionId.Setup(s =&gt; s.Value).Returns(skill.Id);

    //Merge the attribute &quot;key/id&quot; as Configuration section list
    var mockConfSection = new Mock&lt;IConfigurationSection&gt;();                
    mockConfSection.Setup(s =&gt; s.Path).Returns($&quot;Character:Skills:{index}&quot;);
    mockConfSection.Setup(s =&gt; s.Key).Returns(index.ToString());
    mockConfSection.Setup(s =&gt; s.GetChildren()).Returns(new List&lt;IConfigurationSection&gt; { mockConfSectionKey.Object, mockConfSectionId.Object });    
    
    //Add the skill object with merged attributes
    mockConfSections.Add(mockConfSection.Object);
}

// Add the Skill's list
var skillsMockSections = new Mock&lt;IConfigurationSection&gt;();
skillsMockSections.Setup(cfg =&gt; cfg.Path).Returns(&quot;Character:Skills&quot;);
skillsMockSections.Setup(cfg =&gt; cfg.Key).Returns(&quot;Skills&quot;);
skillsMockSections.Setup(cfg =&gt; cfg.GetChildren()).Returns(mockConfSections);

//Mock the whole section, for using GetSection() method withing SUT
configurationMock.Setup(cfg =&gt; cfg.GetSection(&quot;Character:Skills&quot;)).Returns(skillsMockSections.Object);
</code></pre>
<h2>Expected result</h2>
<p>Running the original system, I get the instantiated list with its respective
Here is the screenshot:</p>
<p><a href=""https://i.stack.imgur.com/rHnlP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rHnlP.png"" alt=""appsetting loaded sucessfully"" /></a></p>
<h2>Mocked result</h2>
<p>The code above, I only get the instantiated list but all attributes return null.
Here is the screenshot:</p>
<p><a href=""https://i.stack.imgur.com/yu3Vb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yu3Vb.png"" alt=""appsetting mocked with null values"" /></a></p>
",https://stackoverflow.com/questions/63692671/c-create-mock-configuration-getsection-sectionsubsection-for-objects-list,"['c#', 'unit-testing', 'mocking', 'moq', 'xunit']",2169,True,4,1
How To Create A Temp File Structure For Testing,"<p>During unit testing and Selenium functional testing files are generated which are not cleaned up afterwards. I have spent a very long time trying to get <a href=""https://pypi.org/project/django-cleanup/"" rel=""nofollow noreferrer"">django-cleanup</a> working, but it just does nothing.</p>
<p>I figure I need to create a temporary file structure which files can be uploaded to during testing then destroyed after. This is how I created a temp MEDIA_ROOT file:</p>
<pre><code>MEDIA_ROOT = tempfile.mkdtemp()

@override_settings(MEDIA_ROOT=MEDIA_ROOT)
class UnitTest(TestCase):

    @classmethod
    def tearDownClass(cls): 
        shutil.rmtree(MEDIA_ROOT, ignore_errors=True)
        super().tearDownClass()
</code></pre>
<p>The problem is that, while I may have created a temporary MEDIA_ROOT folder, it doesn't create the subfolders and files.</p>
<p>My file structure in my project looks like this</p>
<pre><code>MEDIA_ROOT
    profile_pics
        default.jpg
    user_files
</code></pre>
<p>Prior to executing each test a user is created and during user creation the user is assigned a profile pic 'default.jpg'. This crashes every test as neither the profile_pics folder nor the default.jpg image exist. If it didn't crash here it would crash later as it would try to save files within folders located within MEDIA, which won't exist in my tempfile.</p>
<p>How can I delete all files after testing without using Django Cleanup? Or how can I create a temporary media file (similar to what I'm already doing), and also the file structure within it (it also would have to include the default.jpg image which is needed during user creation)?</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/63263423/how-to-create-a-temp-file-structure-for-testing,"['django', 'django-testing', 'django-tests']",887,False,4,1
Advice and experience for testing a CN1 app,"<p>I would like to start automating the testing of my app written in CodenameOne, but I find it difficult to visualize how to use the <a href=""https://www.codenameone.com/manual/performance-debugging.html#_device_testing_framework/unit_testing"" rel=""nofollow noreferrer"">TestRecorder</a> (section ""Unit Testing"") for ""industrial"" testing. </p>

<p>If anyone here is already using it, could you share a few tips about how you use it?</p>

<p>E.g. how do you use the different ""Asserts"" buttons, how do you structure your tests into suites and how do you chain them together (e.g. so each test case will start in the right context like where in the navigation structure it is supposed to run), do you need to manually edit the tests, ... And is there anything to be aware of before creating lots of tests interactively, e.g. to avoid that your tests are invalidated by some irrelevant change to your UI?</p>

<p>I read in the <a href=""https://www.codenameone.com/blog/test-recorder-toolbar.html"" rel=""nofollow noreferrer"">blog post</a> from May 2017 that the TestRecorder ""wasn’t picked up by many developers and as such it stagnated"". I tried TestRecorder and immediately came across a seemingly basis error in it (missing test for null) when recording a test case using the Toolbar, which gave the impression it is still the case. So, if anyone here is using another approach that is working well for you, I'd love to hear about that.</p>
",https://stackoverflow.com/questions/59916514/advice-and-experience-for-testing-a-cn1-app,['codenameone'],43,False,3,1
"Unit test-Cant test for equality of returned object, what to test for?","<p>Java 11, New to TDD and to unit testing in general.
I have a class that contains a unique method : buy()
It does a few thing like search for the product in the productRepo, prepare the receipt.
It finally returns an object (receipt).</p>
<pre><code>public Receipt buy(){
   // find product
   // create the receipt
   return receipt; 
}
</code></pre>
<p>NOTE : I omitted the parameters because they are not important to the problem</p>
<p>Now I have to do the unit tests for that method. I have a few problems :
I would normally run a test and compare the expectedReceipt with the one obtained from the call.
However :</p>
<ol>
<li>the Receipt class has no getters (only a constructor)</li>
<li>theReceipt class doesnt override the equals method and doesnt only have simple attributes (double, string ,etc)</li>
<li>I cant include any new dependency to my project, I got : mockito and junit.</li>
<li>The method buy() has to absolutely return an instance of Receipt.</li>
</ol>
<p>So I have no way of testing for equality. What can I do ?
Heres what I tried :</p>
<ol>
<li>I verified that some method was called from my mock (productRepository).</li>
<li>I tried extending that Receipt class and implement myself an equals method. However,
the generic equals method from the Object class seems to be called in my tests.</li>
</ol>
<p>Any ideas or hints ?
Thank you</p>
",https://stackoverflow.com/questions/63866569/unit-test-cant-test-for-equality-of-returned-object-what-to-test-for,"['java', 'unit-testing', 'junit']",326,True,2,1
EF Core 2 Provider specific HasDefaultValueSql,"<p>I am trying to use my <code>DbContext</code> with multiple providers. So far everything works okay, except when using <code>HasDefaultValueSql()</code>.  </p>

<p>What I am trying to do is to have a property <code>AuditTimestamp</code> that has the current time when added (and saved) on the <code>dbContext</code>. This can easily be done using something like this that works for the SQL Server provider</p>

<pre><code>modelBuilder
   .Entity(entityType.ClrType)
   .Property(nameof(AuditBase.AuditTimestamp))
   .HasDefaultValueSql(""SYSUTCDATETIME()"");
</code></pre>

<p>But when trying to use the same <code>dbContext</code> with SqLite provider, it doesn't work since <code>SYSUTCDATETIME</code> isn't a valid SQL function in SqLite. </p>

<p>Based on <a href=""https://stackoverflow.com/questions/46088952/ef-core-2-0-provider-specific-model-configuration"">this question</a> I tried to do</p>

<pre><code>modelBuilder
   .Entity(entityType.ClrType)
   .Property(nameof(AuditBase.AuditTimestamp))
   .HasDefaultValueSql(Database.IsSqlite() ? ""DATETIME('now')"" : ""SYSUTCDATETIME()"");
</code></pre>

<p>But it generates this in the migrations</p>

<pre><code>b.Property&lt;DateTime&gt;(""AuditTimestamp"")
   .ValueGeneratedOnAdd()
   .HasDefaultValueSql(""SYSUTCDATETIME()"");
</code></pre>

<p>because I use a SQL Server connection string when generating the migrations. This implies that I need different sets of migrations based on what provider I use which shouldn't be the case. </p>

<p>Based on <a href=""https://stackoverflow.com/questions/52365060/entity-framework-core-2-1-multiple-providers"">this question</a> it is possible to have provider specific configurations in the migration files but the example is based on auto generated Id column and I don't know how to apply this to <code>HasDefaultValueSql()</code></p>

<p>From <a href=""https://github.com/aspnet/EntityFrameworkCore/issues/10193"" rel=""nofollow noreferrer"">here</a> I found that this might work</p>

<pre><code>HasDefaultValueSql(""CURRENT_TIMESTAMP"")
</code></pre>

<p>But I would like a more general solution for when you have two (or more) providers that don't share same SQL function names. </p>

<p>The providers I use is SQL Server for production and SqLite for unit testing. EF Core is version 2.2</p>
",https://stackoverflow.com/questions/59585533/ef-core-2-provider-specific-hasdefaultvaluesql,"['c#', 'entity-framework-core']",3707,False,2,1
Stubbing lit-element method with sinon in open-wc test,"<p>I'm working on unit testing a custom element written with lit-element using open-wc. We are using Karma, Mocha, Sinon and Chai. I'm trying to test the element's constructor:</p>

<pre><code>constructor() {
  super();
  window.addEventListener(
    'click',
     this._handleClickOutside
  );
}
</code></pre>

<p>For reference, the functions used in the test are:</p>

<pre><code> _handleClickOutside = () =&gt; {
    console.log('calling real')
    this.active = false;
  };

disconnectedCallback() {
    window.removeEventListener('click', this._handleClickOutside);
  }
</code></pre>

<p>In order to test this, I need to stub this._handleClickOutside and check that when a click event is dispatched, this._handleClickOutside is called. Here is my attempt at a test, where el is my custom element that has been initialized with open-wc:</p>

<pre><code>    it('should add event listener to window for click', () =&gt; {
      const clickEvent = new Event('click');
      el.disconnectedCallback();
      const spy = sinon.stub(el, '_handleClickOutside').callsFake( () =&gt; {console.log('calling fake')});
      el._handleClickOutside = spy;
      el.constructor();
      window.dispatchEvent(clickEvent);
      expect(spy.callCount).to.equal(1);
     });
</code></pre>

<p>I understand that when I use open-wc to create the element the constructor will be called before my stub is in place so I've tried to remove the event listener with el.disconnectedCallback(), stub the function, and then call the constructor again to add the event listener using the stub. However, this is still calling the real function. </p>

<p>I've been able to get the test to work by using an anonymous function in the constructor that calls this._handleClickOutside but I don't see a way to remove the event listener in the disconnected callback if I do it this way. Wondering why calling the constructor again when the stub is in place isn't working to stub the function.</p>
",https://stackoverflow.com/questions/59567755/stubbing-lit-element-method-with-sinon-in-open-wc-test,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'lit-element']",1521,True,2,1
Jest tests not passing even though component seems to render correctly,"<p>I am trying to learn to write unit tests for a react application I am building, but I keep running into problems when I try to do a shallow or full render. However when I look at in in chrome it doesn't throw errors and renders properly. I am trying to understand why the tests are failing.</p>
<p><strong>Failing Tests</strong></p>
<p>App.test.js</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import App from './App';

//fails
it('Full render without crash', () =&gt; {
  const div = document.createElement('div');
  ReactDOM.render(&lt;App /&gt;, div);
});

//Passes
it('Shallow render without crash', () =&gt; {
  shallow(&lt;App /&gt;);
});
</code></pre>
<p>The test that fails and gives the error:
TypeError: Cannot read property '_layerAdd' of null.
The above error occurred in the  component:</p>
<pre><code>      in GeoJSON (created by Context.Consumer)

      in ForwardRef(Leaflet(GeoJSON)) (at Country.js:87)

      in ErrorBoundary (at Country.js:86)

      in div (at Country.js:85)

      in Country (at CountryList.js:21)

      in div (at CountryList.js:20)

      in CountryList (at MainMap.js:33)

      in div (created by Map)

      in Map (at MainMap.js:28)

      in MainMap (at App.js:9)

      in div (at App.js:8)

      in App (at App.test.js:9)
</code></pre>
<p>So I think it has to do with the way I am passing data from the CountryList component to the Country component.  But when I try to look at it during run time I cant find anything. I read data in from a json file in country list and feed it as props to the country component.</p>
<p>CountryList.js</p>
<pre><code>import React, { Component } from 'react';
import Country from './Country.js';
import data from '../../../data/test.json';




export default class CountryList extends Component {

    constructor(props) {
        super(props);
        this.state = {
        }

    }


    render() {
        return(
            &lt;div&gt;
                &lt;Country data={data[0]} key={data[0].properties.NAME}/&gt;
            &lt;/div&gt;
        );
    }
}
</code></pre>
<p>Country.js</p>
<pre><code>import React, { Component } from 'react';
import { GeoJSON } from 'react-leaflet';
import SlidingPane from 'react-sliding-pane';
import &quot;./SidePanel.css&quot;;



class ErrorBoundary extends React.Component {
    constructor(props) {
      super(props);
      this.state = { 
          hasError: false,
          err : null, 
          help : null, 
        };
    }
  
    componentDidCatch(error, info) {
      // Display fallback UI
      this.setState({ 
          hasError: true,
          err : error,
          help : info
         });
      // You can also log the error to an error reporting service
      console.log(&quot;Error incoming&quot;);
      console.log(error);
      console.log(info);
    }
  
    render() {
      if (this.state.hasError) {
        // You can render any custom fallback UI
        console.log(&quot;There was an error&quot;);
        console.log(this.state.err);
        console.log(this.state.help);
      }
      return this.props.children;
    }
  }



export default class Country extends Component {
        constructor(props) {
        super(props);
        this.state = {
            color: 'green', 
            isPaneOpen: false
        }
        console.log(&quot;Props from contry list&quot;)
        console.log(props)
    }

    color_control = (color) =&gt; {
        return {color: this.state.color};
    }

    render() {
        return (
            &lt;div&gt;
                &lt;ErrorBoundary&gt;
                    &lt;GeoJSON 
                        data={this.props.data.geometry} 
                        key={this.props.data.properties.NAME}
                        style={this.color_control}
                    /&gt;
                &lt;/ErrorBoundary&gt;
            &lt;/div&gt;
        );
    }
}
</code></pre>
<p>The other test that fails in the same place just with the error:</p>
<p>TypeError: Cannot read property 'geometry' of undefined</p>
<p>Any help would be appreciated. I am new with react and unit testing it so I may just be feeding the data into things incorrectly, but it appears to render correctly in browsers so I am stuck right now.</p>
",https://stackoverflow.com/questions/62745388/jest-tests-not-passing-even-though-component-seems-to-render-correctly,"['reactjs', 'jestjs', 'leaflet', 'enzyme', 'react-leaflet']",956,False,1,0
Installing and running python unit tests within visual studio,"<p>I tried configuring unittest for Visual Studio Community Edition 2019 version 16.6.2.  I had no success with the Test Explorer finding my unit test.  I simply added a simple unit test using Add Python Unit Test from right-clicking on the project.  And it couldn't find the test_1.py file.</p>
<p>Then, I switched to pytest and Test Explorer found my unit test in test_1.py.  But, when I added any import statements to find my code in my project, it rendered the Test Explorer unable to find my unit test once again.</p>
<p>Next, I looked for a way to install nose unit testing under Visual Studio and it asked me to configure some settings file for which I could not find.</p>
<p>I have blank <strong>init</strong>.py files in all my source folders.</p>
<p>Anyway, can someone please suggest a unit test framework that does work within Visual Studio and isn't so hard to configure?  Perhaps even uploading a simple project with src files would be of help.  Please explain how to configure it.</p>
<p>For the time being, I may just try executing my tests from the commandline....I have used nose successfully from the commandline before....</p>
<p>I am using Anaconda Python 3.7.</p>
<p>Thanks,</p>
<p>Dan</p>
",https://stackoverflow.com/questions/62525168/installing-and-running-python-unit-tests-within-visual-studio,"['python', 'unit-testing', 'anaconda', 'visual-studio-2019']",128,False,1,0
How to properly wrap a Jenkins plugin function such as copyArtifacts?,"<p>I have to wrap some Jenkins steps in dedicated functions, one of them is copyArtifacts</p>

<p>Here is some doc about this function, it list all of its parameters, but no default values for the optional parameters: <a href=""https://jenkins.io/doc/pipeline/steps/copyartifact/"" rel=""nofollow noreferrer"">https://jenkins.io/doc/pipeline/steps/copyartifact/</a></p>

<p>The usual way to call the copyArtifacts function is the following:</p>

<pre><code>copyArtifacts projectName: ""myJenkinsJob"", filter: ""*.pdf"", excludes: ""iAmUseless.pdf"", flatten: false
</code></pre>

<p>One way to wrap it in a function while allowing for the same call syntax is the following:</p>

<pre><code>void myCopyArtifacts(Map&lt;String, Object&gt; parameters) {
   ...
}
</code></pre>

<p>The fun part is to actually implement the wrapper. Since I cannot implement all the possible combination of arguments, I have to parse them manually one by one and give them a default value (which, in this case, I can find in the source code, but not always). And then call the plugin function.</p>

<p>This is not really practical, error prone, and not maintainable. Naively I thought that, because of the way groovy can receive Maps, the following would work:</p>

<pre><code>void myCopyArtifacts(Map&lt;String, Object&gt; parameters) {
   currentWorkflowScript.copyArtifacts(parameters)
}
</code></pre>

<p>But it's not.</p>

<p>So is there a proper way to do it ?</p>

<p>For those wondering, if we are doing that it's for unit testing purposes with Mockito, we needed to wrap the functions to be mocked and at the same time we take the opportunity to limit and control the usages that can be done with them.</p>
",https://stackoverflow.com/questions/60513597/how-to-properly-wrap-a-jenkins-plugin-function-such-as-copyartifacts,"['jenkins', 'groovy', 'jenkins-pipeline', 'shared-libraries', 'jenkins-groovy']",428,False,1,2
Client Side Unit Testing Meteor/React w/Enzyme,"<p>so i've been stuck for several days on an issue while implementing Unit Testing and Integration testing in a large production application that was built in Meteor/React tech stack. I am using the meteortesting:mocha package as recommended by the meteor documentation and enzyme.</p>
<p>The issue i am having is that i am not really grasping how i can mock the withTracker functionality. I am trying to use our dev database as the source for the test users and mock data. All of the props are generated in the tracker and then sent to the component it wraps. (Code sample below). Another issue i am having is that we are using meteor:universe for i18n internationalization. When mounting the component it shows plain text instead of the translated content. Wondering if there's a work around. Thanks in advance!</p>
<p><strong>Component I am testing:</strong></p>
<pre><code>import React, { useState } from &quot;react&quot;;
import ABCComponent from &quot;./ABCComponent&quot;;
import XYZ from &quot;./XYZComponent&quot;;
import * as ROUTE_CONSTANTS from &quot;../../global/RoutesConstants&quot;;
import { withRouter } from &quot;react-router-dom&quot;;
import { withTracker } from &quot;meteor/react-meteor-data&quot;;
import UserAssessments from &quot;../../collections/UserAssessments&quot;;
import moment from &quot;moment-timezone&quot;;
import { i18n } from &quot;meteor/universe:i18n&quot;;

const SortDashboard = (props) =&gt; {
  const [isSkillsSort, setIsSkillSort] = useState(true);

  return (
   &lt;div&gt;
       {/* Contains some logic to set 'isSetSkillSort' state true or false (business logic hidden for security purposes*/}
      {isSkillsSort ? (
        &lt;ABCComponent user={props.user} skillsSorts={props.skillsSorts} employeeList={props.directReportEmp} /&gt;
      ) : (
        &lt;XYZComponent
          user={props.user}
          importanceSorts={props.importanceSorts}
          employeeList={props.directReportEmp}
        /&gt;
      )}
    &lt;/div&gt;
  );
};

const SortDashboardTracker = withTracker((props) =&gt; {
  if (!props.user) return {};

  const abcSubscription = Meteor.subscribe(&quot;abcSubscription&quot;);

  if (abcSubscription.ready()) {
    const rawData = UserAssessments.find(
      { &quot;assessor._id&quot;: Meteor.user().profile._id },
      { sort: { updatedDate: -1 } }
    ).fetch();

    rawData.forEach((assessment) =&gt; {
        //Do Something (business logic hidden for security purposes)
    });
  }

  const xyzSubscription = Meteor.subscribe(&quot;xyzSubscription&quot;);

  let directReportEmp = [];

  if (xyzSubscription.ready()) {
    directReportEmp = Meteor.users.find({ &quot;profile.managerId&quot;: Meteor.user().username }).fetch();
  }

  return { importanceSorts, skillsSorts, directReportEmp };
})(SortDashboard);

export default withRouter(SortDashboardTracker);
</code></pre>
<p>My Test:</p>
<pre><code>import {Meteor} from 'meteor/meteor';
import React from 'react';
import chai from 'chai';
import sinon, { mock } from 'sinon'
import {mount, shallow, configure, render} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import {mockManager,mockEmp1,mockEmp2,mockEmp3,mockUser} from '../../mockUsers'
import SortDashboard from '../../../../imports/components/cllWizard/SortDashboard';
import { withRouter, BrowserRouter as Router } from &quot;react-router-dom&quot;;

configure({adapter: new Adapter()});
if (Meteor.isClient) {
    describe('WizardComponent', ()=&gt; {
        //let returnedText
         //importing the mock user we created for testing purposes
         const currentUser = mockUser
         let props = {user: currentUser}
         beforeEach(() =&gt; {
 
             // now Meteor.user() will return the user we just imported
             sinon.stub(Meteor, 'user');
             Meteor.user.returns(currentUser);
 
             // needed in methods
             sinon.stub(Meteor, 'userId');
             Meteor.userId.returns(currentUser._id); 
         });
 
         //afterEach specifies that we want to restore the user after running the test
         afterEach(() =&gt; {
             Meteor.user.restore();
             Meteor.userId.restore();
         });

        it('CLIENT: should render the Sort Dashboard', () =&gt; {
            const wrapper = mount(&lt;Router&gt;&lt;SortDashboard.WrappedComponent {...props}/&gt;&lt;/Router&gt;)
            console.log(wrapper.debug())
        });
    });
}
</code></pre>
<p>TLDR;</p>
<ul>
<li>Need to test a client side component that uses withTracker and withRouter</li>
<li>Need to be able to see the translated text from meteor:universe:i18n in the test</li>
<li>Pulling mock data from the db instead of manually creating it.</li>
</ul>
<p>The issue may very well be my approach and lack of understanding. Please correct me where-ever necessary. Thanks in advance!</p>
",https://stackoverflow.com/questions/64267755/client-side-unit-testing-meteor-react-w-enzyme,"['reactjs', 'meteor', 'jestjs', 'mocha.js', 'enzyme']",109,False,1,0
Catch2 - Populating singleton with different mock data for different test files,"<p>I am using Catch2 for unit testing in my C++ project. I have a singleton class and it is being used in different test files. For example one file might be testing the singleton itself, and another file testing the interaction between the singleton and another component. As such, I was wondering if there is a way that I can populate the singleton class with different sets of mock data for each test file.</p>
<p>To my knowledge, there seems to be two ways I can go about.</p>
<ol>
<li>Using Test Cases and Sections</li>
</ol>
<p>TestA.cpp</p>
<pre><code>TEST_CASE(&quot;A&quot;) {
    SingletonClass&amp; sc = SingletonClass::getInstance();
    sc.clear();
    sc.add(data1);
    sc.add(data2);
    // ... more methods to populate singletonClass
  
    SECTION(&quot;Check A1&quot;){
        // Perform test checks
    }

    SECTION(&quot;Check A2&quot;){
        // Perform test checks
    }
}
</code></pre>
<p>TestB.cpp</p>
<pre><code>TEST_CASE(&quot;B&quot;) {
    SingletonClass&amp; sc = SingletonClass::getInstance();
    sc.clear();
    sc.add(data3);    // Different data from TestA.cpp
    sc.add(data4);
    // ... more methods to populate singletonClass
  
    SECTION(&quot;Check B1&quot;){
        // Perform test checks
    }

    SECTION(&quot;Check B2&quot;){
        // Perform test checks
    }
}
</code></pre>
<p>However this means that the setup functions will be run twice in each test file, which is not necessary and it is something I hope to avoid. Neither do I want to lump all my tests under one SECTION/TEST_CASE.</p>
<ol start=""2"">
<li>Use of <code>Listeners</code></li>
</ol>
<p>I understand I can create and register my own <code>Listener</code> class and override the <code>testCaseStarting</code> and <code>testCaseEnded</code> methods and this seems to apply for all TEST_CASE, but I want to have different setups for TestA and TestB.</p>
<p>Hence is there a better way I can setup my singleton class differently in each test files such that it is similar to running a setup and teardown function at the beginning and at the end in each test file?</p>
",https://stackoverflow.com/questions/64002397/catch2-populating-singleton-with-different-mock-data-for-different-test-files,"['c++', 'catch-unit-test', 'catch2']",1135,True,1,1
How to create classes in another class properly,"<p>My question is poorly worded and I apologies for that. I was not to sure how to ask this question and as a result was unsure how to search for a duplicate.</p>

<p>I have been learning java for almost a year now and can do everything I want to at this point. However I am stuck on a few things in terms of how to correctly do them.</p>

<p>One of my classes named teacher has a method as below:</p>

<pre><code>public void chooseWhoDidIt(Player player) {


    Suspect suspectOne = GUI.databaseOps.retrieveSuspectByID(1);
    Suspect suspectTwo = GUI.databaseOps.retrieveSuspectByID(2);

    jTextArea1.append(DataOperations.obtainGameDialogue(0, 0, null, getGameDialogue()) + ""\n""); //prints out goodluck message
    jTextArea1.append(DataOperations.obtainGameDialogue(1, 1, null, getGameDialogue()) + ""\n""); //prints out ""here are the suspects again""
    jTextArea1.append(suspectOne.toString() + ""\n"");
    jTextArea1.append(suspectTwo.toString() + ""\n"");
    jTextArea1.append(DataOperations.obtainGameDialogue(18, 18, null, getGameDialogue()) + ""\n""); //printd out ""Who was it""

}
</code></pre>

<p>There is currently no need for the other methods as my question is about the way I code. I create two suspects and present them to the player.</p>

<p>Whilst doing my unit testing I noticed that testing the chooseWhoDidIt() method to test if the suspects information were correctly pulled from the database just felt wrong. I feel like I should have a separate method that deals with the creation of the suspects.</p>

<p>That brings me to my second question. If I do make a second method that creates suspects, would it make sense to even have that method in the Teacher class?</p>

<p>I am more then happy to receive any other input to help me better my practises. That is what I would like to focus on for the new few weeks/months.</p>

<p>Thank you all!</p>
",https://stackoverflow.com/questions/62441578/how-to-create-classes-in-another-class-properly,"['java', 'unit-testing', 'methods']",38,False,1,0
"Logger dependency injection, getting calling class name and source file path","<p>In a WinForms app, there is <code>Logger</code> class that is a form designed for logging, so that any class can call it.</p>
<p>There is a static <code>Configuration</code> class, inside which a <code>Logger</code> lives.</p>
<p><strong>Previous implementation</strong></p>
<p>Various classes would call the logger like so:</p>
<pre><code>public class ImportController
{
    public void import()
    {
        try
        {
            // do the work...
        }
        catch (Exception ex)
        {
            Configuration.logger.log(&quot;Something failed&quot;);
            Configuration.logger.log(ex);
        }
    }
}
</code></pre>
<p><strong>Current implementation</strong></p>
<p>The logger implements the following interface, which was extracted from it as part of refactoring to enable unit testing calling classes through dependency injection:</p>
<pre><code>public interface ILogger
{
    void (string message, [CallerMemberName] string member = &quot;&quot;, [CallerLineNumberAttribute] int lineNumber = -1, string fileName = &quot;&quot;);
    void (Exception ex, [CallerMemberName] string member = &quot;&quot;, [CallerLineNumberAttribute] int lineNumber = -1, string fileName = &quot;&quot;);
}
</code></pre>
<p>As can be seen, the idea is to have it automatically log the calling class name and source file path.</p>
<p>The following is an example of an attempt to inject a logger into all classes that use it, in this instance the <code>ImportController</code> from above:</p>
<pre><code>public class ImportControllerLogger
{
    public void log(string message, [CallerMemberName] string member = &quot;&quot;, [CallerLineNumber] int line_num = -1, string filename = &quot;&quot;)
    {
        Configuration.log.log(string message, &quot;ImportController&quot;, lineNumber, @&quot;Controllers\ImportController.cs&quot;);
    }

    public void log(Exception exception, [CallerMemberName] string member = &quot;&quot;, [CallerLineNumber] int line_num = -1, string filename = &quot;&quot;)
    {
        Configuration.log.log(exception, &quot;ImportController&quot;, lineNumber, @&quot;Controllers\ImportController.cs&quot;);
    }
}

public class ImportController
{
    ILogger _logger;

    public ImportController(ILogger logger)
    {
        this._logger = logger;
    }

    public void import()
    {
        try
        {
            // do the work...
        }
        catch (Exception ex)
        {
            _logger.log(&quot;Something failed&quot;);
            _logger.log(ex);
        }
    }
}
</code></pre>
<p><strong>Questions</strong></p>
<p>Is this the correct approach to decouple the logger from all classes that use it?</p>
<p>It seems it might be better to create a <em>single</em> &quot;LoggerHelper&quot; class, that abstracts away the logger so that any class can make a call to it, instead of creating such a class for every calling class. How can the <em>name of the calling class</em> and <em>source file path for the calling class</em> be logged, in a proper way, without resorting to manually specifying it for each class? It worked in the previous implementation with the attributes.</p>
",https://stackoverflow.com/questions/63610580/logger-dependency-injection-getting-calling-class-name-and-source-file-path,"['c#', 'unit-testing', 'logging', 'dependency-injection']",821,True,1,1
Importing &#39;render&#39; from @testing-library/react in a jsx file is erroring out,"<p>a little stuck on this one. I'm introducing react unit testing into my teams node/react project. We've had jest unit tests for our backend and utils in FE for a long time but no react testing.</p>
<p>I'm following the testing guide via <a href=""https://redux.js.org/recipes/writing-tests"" rel=""nofollow noreferrer"">https://redux.js.org/recipes/writing-tests</a></p>
<p>My issue is that, I've created the test file the exact same way all our other unit tests are created and running properly. I've put a fake test case in the file:</p>
<pre><code>import React from 'react';
//import { render } from '@testing-library/react';

describe('test', () =&gt; {
  it('tests', () =&gt; {
    expect(true).toEqual(true);
  });
});
</code></pre>
<p>And this test case executes as expected. However, as soon as I uncomment the <code>import { render }</code> line, it's breaking on the following error:</p>
<pre><code> FAIL  */__tests__/client/views/components/componentToTest.test.jsx
  ● Test suite failed to run

    */node_modules/@testing-library/dom/dist/helpers.js:44
        } catch {// not using Jest's modern fake timers
                ^
    
    SyntaxError: Unexpected token {
      
      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
      at Object.&lt;anonymous&gt; (node_modules/@testing-library/dom/dist/pretty-dom.js:13:16)
      at Object.&lt;anonymous&gt; (node_modules/@testing-library/dom/dist/config.js:11:18)
</code></pre>
<p>At a total loss for what's going on here, can't find anyone w/ a similar issue. My IDE even correctly shows me what the render method looks like, so I know its importing properly.</p>
<p>I've installed all of the packages suggested in the guide, and obviously have jest config'd to run jsx files (since the test works, but just breaks on the import)</p>
<p>An answer would be great, but really would love to just be pointed in the right direction of how to resolve this as well.</p>
<p>Thanks!</p>
<p>Also worth noting, I have <code>babel-jest</code> and <code>jest-dom</code> setup, as I know thats the answer to a lot of similar issues.</p>
",https://stackoverflow.com/questions/62762251/importing-render-from-testing-library-react-in-a-jsx-file-is-erroring-out,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",1558,True,1,2
Dependency Management in C with CMake,"<p>I have recently tried to make a few basic projects in C (using CMake), but one aspect I find very difficult is getting all the different things that I've been making to link together nicely. For example, I started off by making a data-structure library that has some of the basic data structures, along with functions to traverse them, etc., and a testing library that handles unit testing. In most new projects I make, I find that I need to include these two libraries, but I can't find an easy way to do it. I tried doing this using git submodule, and while that did work for the most part, whenever I updated any of the dependencies, updating the dependant seemed to be a nightmare. I've also had a look into the cmake package system; <code>find_package</code>, and related functions; but I can't seem to get that to work (at least when I want to install it in a custom directory, that is).</p>
<p>I was wondering if there is some sort of &quot;standard&quot; way that C programmers go about dealing with this, and what that may be. Is submodules the way to go? If so, is there a way I could do it cleanly, making sure that everything is always the right version?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/64329479/dependency-management-in-c-with-cmake,"['c', 'cmake']",92,False,1,0
Spring Boot Junit test injecting dao interface with constructor injection,"<p>Okay So I am trying to set up a springboot/junit test that tests a DAO that is injected to other classes via constructor injection.
Initially I tried constructor injection </p>

<pre><code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.portfolio.bork.webapp.services.db.ProjectDao;

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class ProjectDaoTest  {

    ProjectDao projectDao;

    @Test
    public void getProject() {
        assert projectDao.getProjectById(1L) != null;
    }

    public ProjectDaoTest() {}

    public ProjectDaoTest(ProjectDao projectDao) {
        this.projectDao = projectDao;
    }

    public void setProjectDao(ProjectDao projectDao) {
        this.projectDao = projectDao;
    }
}
</code></pre>

<p>but then get the error message </p>

<pre><code>java.lang.IllegalArgumentException: Test class can only have one constructor
</code></pre>

<p>So then looked around and saw some options which boiled down to either using Junit 5(allows multiple constructors) or using Mockito to . 
I would prefer to stick to whats in the spring-starter-test package. So I went with the mockito route. as such</p>

<pre><code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
// import org.springframework.test.context.junit4.SpringRunner;
import com.portfolio.bork.webapp.services.db.ProjectDao;

@RunWith(MockitoJUnitRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

public class ProjectDaoTest  {

    @InjectMocks ProjectDao projectDao;

    @Test
    public void getProject() {
        assert projectDao.getProjectById(1L) != null;

    }

    public ProjectDaoTest() {}

    public void setProjectDao(ProjectDao projectDao) {
        this.projectDao = projectDao;
    }
}
</code></pre>

<p>But came across this issue, </p>

<pre><code>org.mockito.exceptions.base.MockitoException: 

Cannot instantiate @InjectMocks field named 'projectDao'! Cause: the type 'ProjectDao' is an interface.
You haven't provided the instance at field declaration so I tried to construct the instance.
Examples of correct usage of @InjectMocks:
@InjectMocks Service service = new Service();
@InjectMocks Service service;
//and... don't forget about some @Mocks for injection :)
</code></pre>

<p>If I try to mock the DAO implementation (which I am trying to avoid), I get an error</p>

<pre><code>@InjectMocks ProjectDaoImpl projectDao;

// error
java.lang.NullPointerException at com.portfolio.bork.webapp.daotest.ProjectDaoTest.getProject(ProjectDaoTest.java:23)
</code></pre>

<p>Here is my DAO interface</p>

<pre><code>public interface ProjectDao {
    public Project getProjectById(Long projectId);
}
</code></pre>

<p>its implementation</p>

<pre><code>package com.portfolio.bork.webapp.services.db;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.portfolio.bork.webapp.model.Project;

@Repository
public class ProjectDaoImpl implements ProjectDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    public ProjectDaoImpl() {}

    public Project getProjectById(Long projectId) {
        return entityManager.find(Project.class, projectId);
    }
}
</code></pre>

<p>I utilize them as such in my Rest Controller</p>

<pre><code>@RestController
public class ProjectRestController {

    private ProjectDao projectDao;

    ...

    // for constructor injection
    public ProjectRestController(ProjectDao projectDao) {
        this.projectDao = projectDao;
    }

    public void setProjectDao(ProjectDao projectDao) {
        this.projectDao = projectDao;
    }

}
</code></pre>

<p>Here is my pom.xml</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;2.2.5.RELEASE&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.portfolio.bork&lt;/groupId&gt;
    &lt;artifactId&gt;webapp&lt;/artifactId&gt;
    &lt;version&gt;01&lt;/version&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;
    &lt;name&gt;webapp&lt;/name&gt;
    &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;

    &lt;properties&gt;
        &lt;java.version&gt;1.8&lt;/java.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;


        &lt;dependency&gt;
            &lt;groupId&gt;mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
            &lt;!-- &lt;scope&gt;runtime&lt;/scope&gt; --&gt;
        &lt;/dependency&gt;


    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

&lt;/project&gt;
</code></pre>

<p>Im somewhat new to different forms of dependency injection(other than autowiring fields) in Spring Boot, and new to unit testing as well.
And am using this application to poke with how Test code interacts with dependency injection, the source code and the test applicationContext.
I also would like to be able to not refer to the Dao Implementation code in the Test code. </p>

<p>Update: 
If I try to autowire the setter, I get this error. I think my test is not picking up the source code application context?</p>

<pre><code>package com.portfolio.bork.webapp;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

// import org.springframework.test.context.junit4.SpringRunner;
import com.portfolio.bork.webapp.services.db.ProjectDao;
import com.portfolio.bork.webapp.services.db.ProjectDaoImpl;

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

public class ProjectDaoTest  {

    ProjectDao projectDao;

    @Test
    public void getProject() {
        assert projectDao.getProjectById(1L) != null;

    }

    public ProjectDaoTest() {}

    @Autowired
    public void setProjectDao(ProjectDao projectDao) {
        this.projectDao = projectDao;
    }
}



2020-04-20 19:16:12.256 ERROR 21124 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@68567e20] to prepare test instance [com.portfolio.bork.webapp.ProjectDaoTest@593aaf41]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.portfolio.bork.webapp.ProjectDaoTest': Unsatisfied dependency expressed through 
method 'setProjectDao' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.portfolio.bork.webapp.services.db.ProjectDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:723) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119) ~[spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43) ~[spring-boot-test-autoconfigure-2.2.5.RELEASE.jar:2.2.5.RELEASE]
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244) ~[spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115) [junit-4.12.jar:4.12]
        at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40) [junit-vintage-engine-5.5.2.jar:5.5.2]
        at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) ~[na:1.8.0_161]
        at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_161]
        at java.util.Iterator.forEachRemaining(Iterator.java:116) ~[na:1.8.0_161]
        at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:1.8.0_161]
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_161]
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_161]
        at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) ~[na:1.8.0_161]
        at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) ~[na:1.8.0_161]
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_161]
        at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) ~[na:1.8.0_161]
        at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80) ~[junit-vintage-engine-5.5.2.jar:5.5.2]
        at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71) ~[junit-vintage-engine-5.5.2.jar:5.5.2]
        at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220) ~[junit-platform-launcher-1.3.1.jar:1.3.1]
        at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188) ~[junit-platform-launcher-1.3.1.jar:1.3.1]
        at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202) ~[junit-platform-launcher-1.3.1.jar:1.3.1]
        at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181) ~[junit-platform-launcher-1.3.1.jar:1.3.1]
        at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128) ~[junit-platform-launcher-1.3.1.jar:1.3.1]
        at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:150) ~[surefire-junit-platform-2.22.2.jar:2.22.2]
        at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:124) ~[surefire-junit-platform-2.22.2.jar:2.22.2]
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384) ~[surefire-booter-2.22.2.jar:2.22.2]
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345) ~[surefire-booter-2.22.2.jar:2.22.2]
        at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126) ~[surefire-booter-2.22.2.jar:2.22.2]
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418) ~[surefire-booter-2.22.2.jar:2.22.2]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.portfolio.bork.webapp.services.db.ProjectDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:715) ~[spring-beans-5.2.4.RELEASE.jar:5.2.4.RELEASE]
        ... 49 common frames omitted
</code></pre>
",https://stackoverflow.com/questions/61315073/spring-boot-junit-test-injecting-dao-interface-with-constructor-injection,"['java', 'spring', 'spring-boot', 'junit', 'mockito']",1737,True,0,1
How to configure Kotlin Androidx dependencies for unit testing as well as succesfully writing the unit test,"<p>Up and running with android, and at the same time trying to understand what I am doing.</p>

<p>I have tried all sorts, read as much resources as I can related to unit testing android. One way or another I still come short and error after error when I run the unit tests. </p>

<p>Instrumented testing was straight forward and I actually managed to satisfactory getting it working.</p>

<p>Now onto unit test and I have gotten tired of changing one dependency to another because one is not compatible with the version of android. Finding these dependencies is a bit of sweat, I have relied more on this forum than the docs to figure out how to piece things together.</p>

<p>Here is my dependency configuration:
<a href=""https://i.stack.imgur.com/VgKBa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VgKBa.png"" alt=""enter image description here""></a></p>

<p>Here is my MainActivity class</p>

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

<p>And here is my test class set up against the activity. It is fairly simple for practical purposes:</p>

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

<p>I get this error now, after resolving a bunch of other errors:</p>

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

<p>I am basically spending an awful lot of time on configuration than doing what I need to do - write the unit test. </p>

<p>How can I go about successfully configuring the dependencies to enable me to write a successful unit test. If my tests are also wrong, how can I correctly change them?</p>
",https://stackoverflow.com/questions/61801671/how-to-configure-kotlin-androidx-dependencies-for-unit-testing-as-well-as-succes,"['android', 'kotlin', 'androidx', 'android-testing']",22,False,0,0
Unit Testing for the Controllor SpringBoot Java,"<p>Need to do Unit Testing for the Controller part of the project but have got the error. Believe ModelAndVIew part cause the issue, even though I have mocked it and returned ModelAndView as it is return type of method. However, it does not work. Do not have any issue with Pom.xml, therefore, did not add it. 
    ProjectController:</p>

<pre><code>package com.bsptech.itcommunity.controller;

import com.bsptech.itcommunity.entity.Itproject;
import com.bsptech.itcommunity.service.inter.EmployeeProfileServiceInter;
import com.bsptech.itcommunity.service.inter.ItProjectServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(value = ""/projects"")
public class ProjectController {

    @Autowired
    private ItProjectServiceInter itProjectServiceInter;

    @Autowired
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @RequestMapping(method = RequestMethod.GET, path = ""/{projectId}"")
    public ModelAndView detail(@PathVariable(""projectId"") Integer projectId, ModelAndView modelAndView) {
        Itproject itproject = itProjectServiceInter.findById(projectId);
       modelAndView.addObject(""itproject"", itproject);
        modelAndView.setViewName(""project/details"");
        return modelAndView;
    }

    @GetMapping
    public ModelAndView index(ModelAndView modelAndView) {
        List&lt;Itproject&gt; projectList = itProjectServiceInter.findAll();
        modelAndView.addObject(""projectList"", projectList);
        modelAndView.setViewName(""project/index"");
        return modelAndView;
    }

    @RequestMapping(value = ""/join"", method = RequestMethod.POST)
    public String joinTeam(@RequestParam(""projectId"") Integer projectId){

        int result= employeeProfileServiceInter.joinProject(projectId);
        if(result==2)
            return ""redirect:/projects/""+projectId+""?alreadyjoined"";
        else if(result==1)
            return ""redirect:/projects/""+projectId+""?joinsuccess"";
        else if(result==3)
            return ""redirect:/projects/""+projectId+""?alreadysent"";
        else
            return ""redirect:/projects?error"";
    }
}
</code></pre>

<p>ProjectControllerTest</p>

<pre><code>@WebMvcTest(ProjectController.class)
@SpringBootTest
public class ProjectControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private ItProjectServiceInter itProjectServiceInter;

    @MockBean
    private EmployeeProfileServiceInter employeeProfileServiceInter;

    @Mock
    ModelAndView modelAndView;

    @Test
    public void detail() throws Exception {
      OngoingStubbing resultItProject =  when(itProjectServiceInter.findById(1)).thenReturn(new Itproject(1));
        when(modelAndView.addObject(resultItProject)).thenReturn(new ModelAndView(""project/details""));
        RequestBuilder request = MockMvcRequestBuilders.get(""/{projectId}"").accept(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc
                .perform(request)
                .andExpect(status().isOk())
                .andExpect(content().json(""project/details""))
                .andReturn();
    }


}
</code></pre>

<blockquote>
<pre><code>Error Which I have found it: 
java.lang.NullPointerException
  at com.bsp.tech.it.community.controller.ProjectControllerTest.detail(ProjectControllerTest.java:44)
  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.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
  at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
  at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
</blockquote>

<p>When I am using </p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(ProjectController.class)
public class ProjectControllerTest {
</code></pre>

<p><strong>Getting an initialization error:</strong></p>

<blockquote>
  <p>java.lang.IllegalStateException: Unable to find a
  @SpringBootConfiguration, you need to use @ContextConfiguration or
  @SpringBootTest(classes=...) with your test</p>
  
  <p>at org.springframework.util.Assert.state(Assert.java:73)    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:233)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:149)
    at
  org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper.processMergedContextConfiguration(WebMvcTestContextBootstrapper.java:36)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:395)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265)
    at
  org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
    at
  org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:98)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:139)
    at
  org.springframework.test.context.TestContextManager.(TestContextManager.java:124)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:142)
    at
  org.springframework.test.context.junit4.SpringRunner.(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at
  org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at
  org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at
  org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at
  org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at
  org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
    at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at
  com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at
  com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)</p>
</blockquote>

<p><strong>And In the pom.xml Using this dependency:</strong></p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>
",https://stackoverflow.com/questions/60259848/unit-testing-for-the-controllor-springboot-java,"['java', 'spring-boot', 'unit-testing', 'junit']",193,False,0,1
I&#39;m using verify(mockito) here. Is it the correct way of testing my service?,"<p>I have a question related to Unit Testing in Spring boot. I have a simple application of user management that does basic crud operations about User. I use a service that gets called inside the controller depending upon the end point. So for example :</p>
<p>for url =   &quot;/createUser&quot; - <em><strong>service.createUser</strong></em> gets called and takes care of all the activity (checking user already exists or not, and other exception handling) and eventually adds the user in database.</p>
<p>Now I'm to Unit test this service in case of creating the user, following is my code:</p>
<pre><code>@Test
    void testRegisterUser() {       
        Set&lt;String&gt; roles = new HashSet&lt;&gt;();        
        signUpRequest.setCustomername(&quot;s&quot;);
        signUpRequest.setCustomerid(&quot;1s&quot;);
        signUpRequest.setCustomername(&quot;custsomername&quot;);
        signUpRequest.setDescription(&quot;customser description&quot;);
        signUpRequest.setEmail(&quot;customser@mail.com&quot;);   
        signUpRequest.setPassword(&quot;12s3&quot;);
        signUpRequest.setRole(roles);  
        service.createUser(signUpRequest);
        verify(repository, times(1)).save(any(UserModel.class));
    }
</code></pre>
<p>In the end all I'm doing is calling the service's method to create the user. I have mocked this service and repository. And at the last line, I'm verifying that the repository has been called at once or not.</p>
<p>What I want to understand am I doing it the right way? Is it the right way to test it? My Senior wants assert over here, but what's the point of assertEquals if <em><strong>createUser</strong></em> doesnt return any value since I'm not doing Integration Testing, There is no db in here. All I'm testing here is my logic and mimicking the behavior. I would appreciate a thorough answer. Thanks in advance.</p>
",https://stackoverflow.com/questions/64931155/im-using-verifymockito-here-is-it-the-correct-way-of-testing-my-service,"['spring-boot', 'junit', 'mockito']",339,True,0,3
"Can not compile xUnit test classes (via mono) to exe file, using mcs command","<p>I am using <a href=""https://www.msys2.org/"" rel=""nofollow noreferrer"">MSYS2</a> and <a href=""https://www.mono-project.com/docs/getting-started/mono-basics/"" rel=""nofollow noreferrer"">mono</a> in order to run C# project (in <code>.NET Framework</code>) in <code>Linux</code> environment on <code>Windows</code> machine.</p>
<p>My projects are placed in the path: <code>D:\MyRootPath</code> and there I have two separate solutions:</p>
<ul>
<li><code>D:\MyRootPath\MainProject</code> - this is my main project;</li>
<li><code>D:\MyRootPath\xUnitProject</code>- this is a separate solution that contains project that I use for unit testing with <a href=""https://xunit.net/docs/getting-started/netfx/visual-studio"" rel=""nofollow noreferrer"">xUnit.net</a> framework (for <code>.NET Framework</code>);</li>
</ul>
<p><strong>Building main project (working sample)</strong></p>
<p>Inside of <code>D:\MyRootPath\MainProject</code> I have a sample class <code>D:\MyRootPath\MainProject\HelloWorld.cs</code>:</p>
<pre><code>public class HelloWorld
{
    public static void Main(string[] args)
    {
        Console.WriteLine (&quot;Hello Mono World&quot;);
    }
}
</code></pre>
<p>When I want to build this via <code>mono</code>, to create an <code>.exe</code> file and run it, I am using the following commands inside of the <code>MSYS2</code> console (this approach is working well):</p>
<pre><code>mcs /d/MyRootPath/MainProject/HelloWorld.cs
mono /d/MyRootPath/MainProject/HelloWorld.exe
</code></pre>
<p><strong>Building xunit project (need help here)</strong></p>
<p>Inside of the xUnitProject, I have many classes, where each class represent a test case (and each test case have reference to the main project - <code>MainProject.dll</code>). One example of test case is <code>D:\MyRootPath\xUnitProject\SampleRectangle.cs</code>:</p>
<pre><code>using MainProject;
using System;
using Xunit;

namespace xUnitProject
{
    public class SimpleRectangle
    {
        [Fact]
        public void simpleRectangle()
        {
            //this content is irrelevant to the question, I have a few Assert checks
            Assert.Equal(&quot;someVariable&quot;, someVariable);
            Assert.Equal(&quot;someOtherVarialble&quot;, someOtherVarialble);
        }
    }
}
</code></pre>
<p>Here I need to build this via <code>mono</code>, to create an <code>.exe</code> file and run it. Since I have many classes like  <code>SimpleRectangle</code>, I need to run them all and to have separate <code>.exe</code> files for each.</p>
<p>So I am trying to build the test classes with the following (similar as above working example):</p>
<pre><code>mcs /d/MyRootPath/xUnitProject/SampleRectangle.cs -r:/d/MyRootPath/xUnitProject/bin/Debug/MainProject.dll:/d/MyRootPath/xUnitProject/bin/Debug/xunit.core.dll
</code></pre>
<p>where I had to add <code>-r</code> flag, since it points to the <code>.dll</code> files that are used.</p>
<p>The output that I got is:</p>
<pre><code>D:/MyRootPath/xUnitProject/SimpleRectangle.cs: error CS0012: The type `System.Attribute' is defined in an assembly that is not referenced. Consider adding a reference to assembly `System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
D:\MyRootPath\xUnitProject\bin\Debug\xunit.core.dll (Location of the symbol related to previous error)
D:/MyRootPath/xUnitProject/SimpleRectangle.cs: error CS0103: The name `Assert' does not exist in the current context
D:/MyRootPath/xUnitProject/SimpleRectangle.cs: error CS0103: The name `Assert' does not exist in the current context
error CS5001: Program `SimpleRectangle.exe' does not contain a static `Main' method suitable for an entry point
Compilation failed: 4 error(s), 0 warnings
</code></pre>
",https://stackoverflow.com/questions/63182125/can-not-compile-xunit-test-classes-via-mono-to-exe-file-using-mcs-command,"['mono', 'xunit.net', '.net-framework-version', 'msys2']",308,False,0,0
Unit testing asynchronous code including setInterval in Angular,"<p>I am using Angular 7+.</p>
<p><strong><code>Summary of the problem :</code></strong></p>
<p>I have a code inside which there is a <code>setInterval</code> method which calls a url method of a service to retrieve data every <code>1000 milliseconds</code>. Also note that i do not want my program to first wait for 1000 ms and then call the url method, i.e why i have <em>pre called</em> the method <em><strong>only once</strong></em> before setInterval. Do let me know how to <code>test</code> this exact same behaviour. Also please do not bother much about the implementation as it is done according to <strong>business requirement which i cannot disclose</strong>.</p>
<p><strong><code>Problem Statement:</code></strong></p>
<p>Suppose i have a url to which i check every 1 second whether i am getting data or not. The call to this url is made inside a function <code>getDataFromUrl</code> , inside a <code>service</code> injected into the component.</p>
<p>Please refer the code below.</p>
<pre><code>someStorage = {};

constructor(private service: someService){}
ngOnDestroy(){
   clearInterval(this.clearPeriodicRefresh);
}

ngOnChanges(){
    let context = this;
    this.periodicRefresh(context);
    this.clearPeriodicRefresh = setInterval(function(){
        this.periodicRefresh(context);
    },1000);
}

periodicRefresh(self){
    self.service.getDataFromUrl(url).subscribe(res =&gt; {
        someStorage[res] = true;
    },
    err =&gt;{
       console.log(&quot; Error Occured &quot;); 
    });
}

</code></pre>
<p>Now i am unit testing the code like this:</p>
<pre><code>it('should check for async data from url', fakeAsync()=&gt;{
    someServiceStub.getDataFromUrl.and.returnValue(of(&quot;chandni chowk&quot;));
    fixture.detectChanges();
    expect(component.someStorage[&quot;chandni chowk&quot;]).toBe(true); // executes successfully
    
    setInterval(()=&gt;{
        someServiceStub.getDataFromUrl.and.returnValue(of(&quot;delhi&quot;));    
    },1000);
    
    tick(1000); // in milliseconds
    discardPeriodicTasks();
    
    expect(component.someStorage[&quot;delhi&quot;]).toBe(true);          // throws error
    
}));
</code></pre>
<p>The second expect statement shows :</p>
<pre><code>ERROR : expected undefined to be true
</code></pre>
<p>I do not know the reason why . However, if i do a <strong><code>tick(2000)</code></strong> instead of <strong><code>tick(1000)</code></strong>, then it works. Again i am not sure why it gets skipped earlier.</p>
<p><strong><code>NOTE</code></strong> : Any timer between 1000 and 2000 i.e for example till <code>tick(1900)</code> throws the same error, and anytime after 2000 milliseconds works fine.</p>
<p><strong>Also please tell me how to write better tests if there is any other way for this.</strong></p>
",https://stackoverflow.com/questions/62394625/unit-testing-asynchronous-code-including-setinterval-in-angular,"['angular', 'unit-testing', 'asynchronous']",250,False,0,0
(Solved User error) c++11 make_shared&lt;t&gt;(new class) memory leak,"<p>I've been looking into smart pointers, unit testing how they manage memory and am finding and unexpected issue that all the examples recommend doing, but it creates a huge memory leak for me.</p>

<p>This seems to occur when I use a class that has a constructor that builds from another copy of the same class. I'll give an example. </p>

<p>If I have a class like:</p>

<pre><code>Class foo{
public:
    //Ignore unsafe practices here
    HeavyInMemory* variable;

    foo(){
        variable = new HeavyInMemory();
    }

    foo(foo* copyThis){
        variable  = nullptr;
        if(copyThis){
            variable = new HeavyInMemory(copyThis-&gt;variable);
        }
    }

    ~foo(){
        delete variable;
    }
}
</code></pre>

<p>I find that I will get a huge memory leak because std::make_shared has no way to tell the difference between make_shared(args) and make_shared(new T)</p>

<pre><code>Main(){
    for(int i =0; i &lt; 100; i++{
        //Should not leak, if I follow examples of how to use make_shared
        auto test = make_shared&lt;foo&gt;(new foo());
    }

    //Checking memory addresses these do not match, checking total program memory use, leaks like a 
    //sieve.
}
</code></pre>

<ul>
<li>Am I misunderstanding something? </li>
<li>Do the examples just not consider this as most use primitive types as examples rather than classes.</li>
<li>Does c++11 just not support the make_shared(new T) format even though I see old books like scott meyers books from 1992. It just doesn't make sense.</li>
</ul>

<p>Also why would you use make_shared(new T) over make_shared(args)? I've seen a couple threads where people have asked this on here, but neither seemed to actually answer the question with a code example.</p>

<pre><code>//As they mainly say code compiler order causes the leak but in my example this would still leak:
auto originalObject = new foo();
auto expectedDestructorWhenOutofScope = make_shared&lt;foo&gt;(originalObject);

//I have found if I give if the object instead it doesn't leak, but this is getting into the realms of
//hacks that may sometimes work
auto originalObject = new foo();
auto expectedDestructorWhenOutofScope = make_shared&lt;foo&gt;(*originalObject);
</code></pre>

<p>EDIT:
Thanks to  Igor Tandetnik I now see I am using make_shared entirely wrong. It should be used as a constructor. Thanks again Igor I appreciate it.</p>

<pre><code>//Create new
auto expectedDestructorWhenOutofScope = make_shared&lt;foo&gt;();

//Use object already created
std::shared_ptr&lt;Object&gt; p2(new foo())
</code></pre>
",https://stackoverflow.com/questions/61573491/solved-user-error-c11-make-sharedtnew-class-memory-leak,"['c++11', 'memory-leaks', 'smart-pointers', 'make-shared']",116,False,0,0
Moq setup returns reference to object,"<p>Let's say I have a simple class called MyRequestHandler, and it has a method called ProcessRequest that simply takes a request object, maps it to a return object and returns that object.  (This is obviously a very simple example of a much more complex method/test that I'm working on).</p>

<pre><code>public class MyRequestHandler
{
  private IMapper _mapper;

  public MyRequestHandler(IMapper maper)
  {
    _mapper = mapper;
  }

  public MyReturnObject ProcessRequest(MyRequestObject requestObject)
  {
    MyReturnObject returnObject = _mapper.Map&lt;MyReturnObject&gt;(requestObject);
    return returnObject;
  }
}
</code></pre>

<p>Now for unit testing (using Xunit), I want to test the ProcessRequest method, but obviously want to Moq the Map method, as such:</p>

<pre><code>MyRequestObject requestObject = new RequestObject()
{
  RequestInt = 1,
  RequestString = ""Hello""
};

MyReturnObject returnObject = new MyReturnObject()
{
  MyInt = 1,
  MyString = ""Hello""
};

Mock&lt;IMapper&gt; mockMapper = new Mock&lt;IMapper&gt;();
mockMapper.Setup(m =&gt; m.Map&lt;MyRequestObject&gt;(requestObject)).Returns(returnObject);

MyRequestHandler requestHandler = new MyRequestHandler(mockMapper.Object);
MyReturnObject response = requestHandler.ProcessRequest(requestObject);

Assert.Equal(returnObject.MyInt, response.MyInt);
Assert.Equal(returnObject.MyString, response.MyString);
</code></pre>

<p>The problem here is that Moq returns (and I guess it should be obvious that it is) a reference to returnObject, so my Asserts will always pass, even if my method were to change a value prior to returning the object.  Now I could instantiate a new MyReturnObject in the Moq Setup/Return and compare the MyInt and MyString by the values I give to the new one, but what if it's a really complex object with 20 properties and lists of objects?  Maybe I want to use AutoFixture to create the object being returned and use DeepEqual to compare them?  Is this even possible?  Am I looking at this wrong, or do I have to do some type of cloning in the Setup/Return to make this work?</p>
",https://stackoverflow.com/questions/61492760/moq-setup-returns-reference-to-object,"['c#', 'unit-testing', 'moq']",893,True,0,2
"NullPointerException while trying to test a Spring MVC controller method with JUnit, Mockito","<p>I am trying to unit test a Spring MVC controller method, but my unit test keeps failing.</p>
<p>I have a Spring MVC controller method:</p>
<pre><code>// MyController.java
@RequestMapping(value = &quot;/end-point&quot;, method = RequestMethod.GET)
public ModelAndView getData(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    ModelAndView mv = new ModelAndView();
    DataManager dataManager = DataManager.getInstance();
    DataUser currentUser = (DataUser) request.getSession().getAttribute(&quot;currentUser&quot;);
    List&lt;DataItem&gt; dataList = dataManager.getDataForUser(currentUser.getId());
    mv.addObject(&quot;dataList&quot;, dataList);
    mv.setViewName(&quot;home-page&quot;);
    return mv;
}
</code></pre>
<p>I am trying to test this controller method with JUnit. I have very little experience unit testing and am trying to learn. Seems like this is near-impossible or does not make sense to do without a mocking library, and the project I'm working on already has Mockito as a dependency so I'm trying to use that. My test class is below:</p>
<pre><code>//MyControllerTest.java
public class MyControllerTest {
    @InjectMocks
    private MyController myController;

    @Mock
    HttpServletRequest request;

    @Mock
    HttpServletResponse response;

    @Mock
    ModelAndView mockModelAndView;

    @Mock
    DataManager mockDataManager;

    @Mock
    DataUser mockDataUser;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void getDataTest() throws Exception {
        //I guess I have to somehow mock mockDataUser here even more than @Mock???
        Mockito.when(request.getSession().getAttribute(&quot;currentUser&quot;)).thenReturn(mockVendorUser); // &lt;-- this is where the null pointer exception is coming from
        Mockito.when(myController.getData(request, response)).thenReturn(mockModelAndView); 
        ModelAndView testing = profileControllerWH.getMySkus(request, response);
        assertEquals(1, 1);
    }
}
</code></pre>
<p>When I run my test, it fails and I get a <code>java.lang.NullPointerException</code> exception in the console, specifying the line above with the null pointer exception comment.</p>
<p>I have tried looking up how to mock classes with Mockito, and I keep seeing the <code>@Mock</code> annotation, which I already have as <code>@Mock DataUser</code> (as well as other classes I am using in the controller method that I guess I need to mock).</p>
<p>How do I get this to work? It seems like I have to create a whole new <code>DataUser</code> object with fake data, but then that seems to defeat the purpose of the mocking library. What would the point of using Mockito be if I have to create my own objects with fake data? Or, I might be misunderstanding this because of lack of experience.</p>
",https://stackoverflow.com/questions/65039308/nullpointerexception-while-trying-to-test-a-spring-mvc-controller-method-with-ju,"['java', 'spring-mvc', 'junit', 'mockito']",205,True,0,1
Qt QML Unit test setup using Cmake,"<p>I am trying to do unit testing with QtQuickTest and i am receiving some errors and also hitting some walls in including them with the other tests.</p>
<p>Basicly my tst_mytest.cpp file looks like this, taken from: <a href=""https://doc.qt.io/qt-5/qtquicktest-index.html"" rel=""nofollow noreferrer"">https://doc.qt.io/qt-5/qtquicktest-index.html</a></p>
<pre><code>// tst_mytest.cpp
#include &lt;QtQuickTest&gt;
#include &lt;QQmlEngine&gt;
#include &lt;QQmlContext&gt;

class Setup : public QObject
{
Q_OBJECT

public:
    Setup() {}

public slots:
    void qmlEngineAvailable(QQmlEngine *engine)
    {
        engine-&gt;rootContext()-&gt;setContextProperty(&quot;myContextProperty&quot;, QVariant(true));
    }
};

QUICK_TEST_MAIN_WITH_SETUP(mytest, Setup)

#include &quot;tst_mytest.moc&quot;
</code></pre>
<p>Now this macro QUICK_TEST_MAIN_WITH_SETUP runs the main function, which means that i cannot run it myself in this .exe file (at least i tried and failed), and then i cannot do more than set the context for the engine.</p>
<p>My cmake for this looks like this:</p>
<pre><code>set(TEST_QML_EXE &quot;${PROJECT_NAME}_QML_TEST&quot;)

add_executable(${TEST_QML_EXE})

target_sources(${TEST_QML_EXE}
PRIVATE
    qml/tst_TestMain.cpp
)

set_property(TARGET ${TEST_QML_EXE} PROPERTY ${PROJECT_NAME}_PRIVATE 1)

target_link_libraries(${TEST_QML_EXE}
PRIVATE
    Qt5::Core
    Qt5::Quick
    Qt5::QuickControls2
    Qt5::QuickTest  
    Qt5::Qml
)
</code></pre>
<p>And when i run it, i get</p>
<pre><code>onecore\com\combase\objact\objact.cxx(836)\combase.dll!00007FFA0677B2D7: (caller: 00007FFA0677A15C) ReturnHr(399) tid(1498) 800401F0 CoInitialize has not been called.
onecore\com\combase\objact\objact.cxx(836)\combase.dll!00007FFA0677B2D7: (caller: 00007FFA0677A15C) ReturnHr(400) tid(1498) 800401F0 CoInitialize has not been called.
onecore\com\combase\objact\objact.cxx(836)\combase.dll!00007FFA0677B2D7: (caller: 00007FFA0677A15C) ReturnHr(401) tid(1498) 800401F0 CoInitialize has not been called.
onecore\com\combase\objact\objact.cxx(836)\combase.dll!00007FFA0677B2D7: (caller: 00007FFA0677A15C) ReturnHr(402) tid(1498) 800401F0 CoInitialize has not been called.
onecore\com\combase\objact\objact.cxx(836)\combase.dll!00007FFA0677B2D7: (caller: 00007FFA0677A15C) ReturnHr(403) tid(1498) 800401F0 CoInitialize has not been called.
onecore\com\combase\objact\objact.cxx(836)\combase.dll!00007FFA0677B2D7: (caller: 00007FFA0677A15C) ReturnHr(404) tid(1498) 800401F0 CoInitialize has not been called.
</code></pre>
<p>...Repeating errors.</p>
<p>As i found so far this seems to be something to do with not opening an Application instance for running the tests, altho the QML tests i create in the same folder as my tst_*.cpp file does RUN, I just get all these repeating errors on every single file.</p>
<p>Now if only i found out how to run the QUICK_TEST_MAIN_WITH_SETUP macro WITHOUT the MAIN part of it inside, so that i could start a QCoreApplication before in a custom main, i think the repeating errors might disappear, and perhaps i could run all the backend tests in the same executable, which would be perfect.</p>
<p>Any help is appreciated</p>
",https://stackoverflow.com/questions/63741769/qt-qml-unit-test-setup-using-cmake,"['c++', 'qt', 'unit-testing', 'cmake', 'qml']",671,False,0,1
Autofac Multiple Regsistrations to Single service. Simple Injector -&gt; Autofac translation,"<p>I've developed a CQRS style database access framework based on Tripod and other inspirations but targeting .NET Standard and simplifying for easier use. I want to split the IoC into separate integration packages so consumers can get the type registration I'm currently doing internally easily without being locked into a specific IoC container. My issue is I've only really worked closely with SimpleInjector so not familiar with other systems and their nuances around how they handle specific scenarios. I have an iminent need to support Autofac so thought I'd try here to see if anyone can translate.</p>
<p>I have the following Simple Injector CompositionRoot static class:</p>
<pre><code>public static void RegisterDatabase(this Container container, DbContextOptions&lt;EntityDbContext&gt; dbContextOptions, params Assembly[] assemblies)
{
    var scopedLifeStyle = container.Options.DefaultScopedLifestyle;

    //container.Register&lt;ICreateDbModel, DefaultDbModelCreator&gt;(scopedLifeStyle); // lifestyle c
    container.RegisterInitializer&lt;EntityDbContext&gt;( //(container.InjectProperties);
        handlerToInitialise =&gt; handlerToInitialise.ModelCreator = new DefaultDbModelCreator()
    );

    // Setup DbContext
    var ctxReg = scopedLifeStyle.CreateRegistration(
        () =&gt; new EntityDbContext(dbContextOptions),
        container);

    container.AddRegistration&lt;IUnitOfWork&gt;(ctxReg);
    container.AddRegistration&lt;IReadEntities&gt;(ctxReg);
    container.AddRegistration&lt;IWriteEntities&gt;(ctxReg);
}
</code></pre>
<p>In ASP.NET Core solutions I invoke the above from Startup.Configure(...) with:</p>
<pre><code>var optionsBuilder = new DbContextOptionsBuilder&lt;EntityDbContext&gt;()
    //.UseInMemoryDatabase(&quot;Snoogans&quot;);
    .UseSqlServer(_config.GetConnectionString(&quot;DefaultConnection&quot;));
container.RegisterDatabase(optionsBuilder.Options);
</code></pre>
<p>which allows me to switch out to an in memory database for unit testing if needed. EntityDbContext contains all my unit of work methods for calling onto the context without having to specify explicit DbSet for each table. The IUnitOfWork, IReadEntities and IWriteEntities interfaces all define methods on the EntityDbContext.</p>
<p>So I'm not sure how I'd go about making an Autofac module that allows scoped registration of the dbcontext with passed in DbContextOptions followed by multiple registrations of interfaces to this registration.</p>
<p>Does anyone know how this can be achieved?</p>
",https://stackoverflow.com/questions/62509135/autofac-multiple-regsistrations-to-single-service-simple-injector-autofac-tr,"['.net-core', 'entity-framework-core', 'autofac', 'cqrs', 'autofac-module']",121,True,0,1
Error when testing HttpInterceptor Angular 10,"<p>I'm working on an Angular 10 application that uses an <code>HttpInterceptor</code> for adding a specific header to all responses.  Unfortunately, when trying to test this interceptor, I keep getting the following error:</p>
<pre><code>Error: Expected one matching request for criteria &quot;Match by function: &quot;, found none.
</code></pre>
<p>Or a similar variant:</p>
<pre><code>Error: Expected one matching request for criteria &quot;Match URL: /endpoint&quot;, found none.
</code></pre>
<p>My expectation is that this test would pass but I'm, now, at a loss as to figuring out why it's not working.</p>
<p>Here is my interceptor:</p>
<pre class=""lang-js prettyprint-override""><code>@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private kc: KeycloakService) { }

    intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
        return Observable.fromPromise(this.kc.getToken()).mergeMap(auth =&gt; {
            if (auth) {
                req = req.clone({
                    setHeaders: {
                        Token: auth
                    }
                });
            }

            return next.handle(req);
        })
    }
}
</code></pre>
<p>Here is my test:</p>
<pre class=""lang-js prettyprint-override""><code>// imports removed for clarity

describe('Interceptor', () =&gt; {
    let http: HttpClient;
    let httpController: HttpTestingController;
    let mockKeycloakService: KeycloakService;
    let interceptor: AuthInterceptor;

    const TEST_TOKEN = 'test-token';

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                KeycloakService,
                {
                    provide: HTTP_INTERCEPTORS,
                    useClass: AuthInterceptor,
                    multi: true
                }
            ],
        });

        http = TestBed.inject(HttpClient);
        httpController = TestBed.inject(HttpTestingController);
        mockKeycloakService = TestBed.inject(KeycloakService);

        spyOn(mockKeycloakService, 'getToken').and.returnValue(new Promise&lt;string&gt;(() =&gt; TEST_TOKEN));

        interceptor = new AuthInterceptor(mockService);
    });

    // removed for clarity

    it('adds token to all responses', done =&gt; {
        let endpoint = '/endpoint';
        http.get&lt;HttpResponse&lt;any&gt;&gt;(endpoint).subscribe(res =&gt; {
            expect(res).toBeTruthy();
            expect(res.headers).toBeTruthy();
            expect(res.headers.get('Token')).toBe(TEST_TOKEN);
        });
        let req = httpController.expectOne(endpoint);

        // The first error occurred when I tried this:
        // let req = httpController.expectOne(res =&gt; res.headers.has('Token') &amp;&amp; res.headers.get('Token') === TEST_TOKEN);

        let body = { test: 'test-value' };
        console.log(`The URL is: ${req.request.url}`);
        expect(req.request.body).toEqual(body);

        req.flush(body);
        httpController.verify();
    });

    // removed for clarity
});
</code></pre>
<p>That said, it's probably worth pointing out that I've tried applying solutions from the following resources to no avail (most seem to be similar to what I already have anyways and many seem to be for older versions of Angular):</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/46225164/unit-testing-httpinterceptor-from-angular-4"">Unit testing HttpInterceptor from Angular 4</a>:
Here, I found a useful <a href=""https://dev.to/alisaduncan/intercepting-http-requests---using-and-testing-angulars-httpclient"" rel=""noreferrer"">article</a> that does almost exactly what I need but it doesn't actually work for my case (I'm getting the above errors).  I say <em>almost</em> exactly because the Service I'm using to get the token doesn't actually use <code>HttpClient</code> from what I can tell.</li>
<li><a href=""https://github.com/angular/angular/issues/19974"" rel=""noreferrer"">This</a> isn't exactly like my issue but it was similar enough to try it out.  I tried using the workaround described by <strong>textbook</strong> but apparently that wasn't close enough to the issue I was having.</li>
<li>I also tried to <code>spyOn</code> the <code>http.get(...)</code> function in my test which caused the above error to be eliminated but it didn't call my <code>intercept</code> function when I did that.</li>
</ul>
<p>Any help is much appreciated - thank you!</p>
",https://stackoverflow.com/questions/64436045/error-when-testing-httpinterceptor-angular-10,"['angular', 'typescript', 'testing', 'angular-httpclient', 'angular-httpclient-interceptors']",444,False,5,0
How to test the existence of a Lazy Loaded route in Angular?,"<p>My question is similar to <a href=""https://stackoverflow.com/questions/59535910/how-to-test-the-existence-of-a-route-in-angular-using-jasmine"">this question</a>. I'm trying to write a test that checks the existence of a route in Angular. The main difference to the linked question, as that I'm using lazy loading modules instead of components.</p>

<p>I have a file <em>app.routes.ts</em> that contains the routes:</p>

<pre><code>import { Routes } from '@angular/router';

export const routes: Routes = [
    {
        path: '',
        loadChildren: () =&gt; import('./main/main.module').then(m =&gt; m.MainModule)
    }
];
</code></pre>

<p>In the test file <em>app.routes.spec.ts</em>, I expect that this route exists:</p>

<pre><code>import { routes } from './app.routes';

describe('app.routes', () =&gt; {
    it('should contain a route for /', () =&gt; {
        expect(routes).toContain({
            path: '',
            loadChildren: () =&gt; import('./main/main.module').then(m =&gt; m.MainModule)
        });
    });
});
</code></pre>

<p>When I run this, the test is not passing.</p>

<blockquote>
  <p>Expected [ Object({ path: '', loadChildren: Function }) ] to contain
  Object({ path: '', loadChildren: Function }). Error: Expected [
  Object({ path: '', loadChildren: Function }) ] to contain Object({
  path: '', loadChildren: Function }).
      at 
      at UserContext. (<a href=""http://localhost:9876/_karma_webpack_/src/app/app.routes.spec.ts:5:24"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/src/app/app.routes.spec.ts:5:24</a>)
      at ZoneDelegate.invoke (<a href=""http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:365:1"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:365:1</a>)
      at ProxyZoneSpec.onInvoke (<a href=""http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:305:1"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:305:1</a>)</p>
</blockquote>

<p>How can I fix this unit test, and make sure that the existence of lazy loaded routes can be tested? Thank you!</p>

<p><em>DISCLAIMER: I know that some people don't think this should be part of unit testing, and that routing should be tested in e2e testing. Personally I like the idea to check if all my routes exist, and there are no typos. The idea that if somebody would comment out a route for whatever reason and forgets to undo it, and automated testing catches this, makes me feel a bit safer.</em></p>
",https://stackoverflow.com/questions/62466379/how-to-test-the-existence-of-a-lazy-loaded-route-in-angular,"['angular', 'unit-testing']",3155,True,4,2
Unit Test in Rust Web Application,"<p>The most popular rust web frameworks, like actix_web, rocket, all seem to inject the database pool to the handler functions. That made me wonder how to do unit testing in those frameworks.</p>
<p>If you pass down the pool from the top to bottom, the only chance you'd have is to wrap the pool in a trait object and implement a mock sql pool yourself, returning the right objects when required. I assume most people won't write a sql engine to mock it.</p>
<p>Lazy static is the same story, if you access a global variable you cannot mock it for a specific method.</p>
<p>So what's left? Dyn Trait objects injected into the handler (service) which reference repositories (trait objects again). So when testing your service you can implement a mock repository returning the user you'd except in registration and it fails with &quot;UsernameAlreadyExists&quot; as expected.
Problem: Only repositories have a reference to the DB Pool. How to start a transaction? How to share the transaction down to other service methods? Always have two methods? Create_user and create_user_in_transaction?</p>
<p>You could also inject DAO dyn Traits, but there's the same problems as above.</p>
<p>I'm sure I'm missing something. Is pool in request handler really the way to go? How do you handle transactions? And unit tests WITHOUT hitting the DB but only your mock repository?</p>
<p>It really feels like it's untestable.</p>
",https://stackoverflow.com/questions/64117938/unit-test-in-rust-web-application,"['unit-testing', 'rust']",441,False,4,0
Linking library from Xcode Workspace causes &quot;File is already being linked&quot; dialog to appear,"<p>I have an Xcode (11.4.1- though this happened in 11.4 and 11.3) workspace. That workspace is composed of multiple iOS Swift static libraries. One of the libs: <em>lib(A)</em> needs to use another lib <em>lib(B)</em> located in the same workspace.</p>

<p>If I just try to <code>import</code> the module from some source file in <em>lib(A)</em> the compiler won't be able to find the symbols. Fair enough for ""Find Implicit Dependencies"" to work as I understand it, I have to <code>Link Binary With Libraries</code>; I can accept that, so I explicitly link it:</p>

<p>For <em>lib(A)</em> I go to its target and select <code>Link Binary With Libraries</code> under its <code>Build Phases</code> and select <em>lib(B)</em> from the workspace browser. When I do that I receive a warning dialog:</p>

<p><strong>File is already being linked</strong></p>

<p><a href=""https://i.stack.imgur.com/iuBt2.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/iuBt2.png"" alt=""warning dialog""></a></p>

<p>If I press <strong>Cancel</strong> it still adds the selected item under <code>Link Binary With Libraries</code>, but now things build. Why the warning?</p>

<p>The same applies if I were to also add a Unit Testing target to the project for <em>lib(A)</em>. If I explicitly link the required static libs, I get that warning. Pressing cancel adds the item, and things work.</p>

<p>Now, ""things working"" with Xcode is tempting just to back away slowly and take that for what it's worth. However, I'm curious what does that warning mean then/why is it there?  Clearly, according to the compiler, the linking is necessary since it does not compile without it. When adding the linking though it seemingly complains about it.</p>
",https://stackoverflow.com/questions/61599575/linking-library-from-xcode-workspace-causes-file-is-already-being-linked-dialo,"['swift', 'xcode']",377,False,10,0
Jest Unit test cant determine Vuetify components visibility,"<p>I have a Vue2 project with Vuetify, and i am using Jest for unit testing my code. I am starting out testing some sample code and i simple cannot get Jest to determine if a Vuetify <code>v-alert</code> component is visible or not. I have tried the built in Jest methods as well as adding Jest-dom and using the <code>toBeVisible()</code> method and nothing is working so far.</p>
<p>If you look at the Test.vue component, the <code>v-alert</code> component is hidden by default.(Its style is set to display: none;)</p>
<p>The unit test says <code>expect(alert).not.toBeVisible()</code> which should pass, but it always fails regardless of what the <code>v-alert</code> model is set to. If i change the test to <code>expect(alert).toBeVisible()</code> it passes regardless of the <code>v-alert</code> model is set to true/false.</p>
<p>If i change the test to be <code>expect(alert).toHaveStyle({ display: 'none' });</code> it fails regardless of if i have the model set to true/false.</p>
<p>So as far as i can tell the Jest unit test CANNOT determine the visibility of the <code>v-alert</code> component at all. These same test work fine on the <code>v-btn</code> component just fine so why does the <code>v-alert</code> break? This is just my first unit test sample that ive been trying to get working for 2 days now. I have an entire application to write tests for and so far Jest is not working very well with Vuetify...any suggestions?</p>
<p>// Test.vue component</p>
<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;v-btn ref=&quot;btn&quot; depressed tile @click=&quot;showAlert&quot;&gt;Show Alert&lt;/v-btn&gt;
    &lt;v-alert
      v-model=&quot;showError&quot;
      ref=&quot;error-msg&quot;
      type=&quot;error&quot;
      transition=&quot;scale-transition&quot;
      width=&quot;410&quot;
      tile
      dense
      dismissible
      @input=&quot;clearError&quot;
    &gt;
      {{ errorText }}
    &lt;/v-alert&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  data() {
    return {
      showError: false,
      errorText: ''
    };
  },
  methods: {
    showAlert() {
      this.errorText = 'Test Error message';
      this.showError = true;
    },
    clearError() {
      this.errorText = '';
    }
  }
};
&lt;/script&gt;
</code></pre>
<p>// Jest Unit test</p>
<pre><code>// Libraries
import Vue from 'vue';
import Vuetify from 'vuetify';

// Components
import Test from '@/components/Login/Test.vue';

// Utilities
import { createLocalVue, shallowMount } from '@vue/test-utils';

// Import Jest Dom test utils.
import '@testing-library/jest-dom';

const localVue = createLocalVue();

Vue.use(Vuetify);

describe('Test Page', () =&gt; {
  let vuetify;

  beforeEach(() =&gt; {
    vuetify = new Vuetify();
  });

  it('Check visibility of button', () =&gt; {
    const wrapper = shallowMount(Test, {
      localVue,
      vuetify
    });

    const btn = wrapper.findComponent({ ref: 'btn' }).element;

    expect(btn).toBeVisible();
  });

  it('Error Message hidden on page load', () =&gt; {
    const wrapper = shallowMount(Test, {
      localVue,
      vuetify
    });

    const alert = wrapper.findComponent({ ref: 'error-msg' }).element;

    expect(alert).not.toBeVisible();
  });
});
</code></pre>
<p>// Package.json</p>
<pre><code>&quot;dependencies&quot;: {
    &quot;vue&quot;: &quot;^2.6.11&quot;,
    &quot;vue-click-outside&quot;: &quot;^1.1.0&quot;,
    &quot;vue-debounce&quot;: &quot;^2.5.7&quot;,
    &quot;vue-router&quot;: &quot;^3.3.4&quot;,
    &quot;vuetify&quot;: &quot;^2.2.11&quot;,
    &quot;vuex&quot;: &quot;^3.4.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/plugin-transform-runtime&quot;: &quot;^7.10.3&quot;,
    &quot;@babel/polyfill&quot;: &quot;^7.10.1&quot;,
    &quot;@fortawesome/fontawesome-free&quot;: &quot;^5.13.1&quot;,
    &quot;@testing-library/jest-dom&quot;: &quot;^5.10.1&quot;,
    &quot;@vue/cli-plugin-babel&quot;: &quot;^4.4.5&quot;,
    &quot;@vue/cli-plugin-e2e-nightwatch&quot;: &quot;^4.4.5&quot;,
    &quot;@vue/cli-plugin-eslint&quot;: &quot;^4.4.5&quot;,
    &quot;@vue/cli-plugin-unit-jest&quot;: &quot;^4.4.5&quot;,
    &quot;@vue/cli-service&quot;: &quot;^4.4.5&quot;,
    &quot;@vue/eslint-config-prettier&quot;: &quot;^4.0.1&quot;,
    &quot;@vue/test-utils&quot;: &quot;^1.0.3&quot;,
    &quot;babel-eslint&quot;: &quot;^10.0.3&quot;,
    &quot;babel-jest&quot;: &quot;^26.1.0&quot;,
    &quot;eslint&quot;: &quot;^5.16.0&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^6.2.2&quot;,
    &quot;node-sass&quot;: &quot;^4.14.1&quot;,
    &quot;sass&quot;: &quot;^1.26.9&quot;,
    &quot;sass-loader&quot;: &quot;^8.0.2&quot;,
    &quot;vue-cli-plugin-vuetify&quot;: &quot;^2.0.6&quot;,
    &quot;vue-template-compiler&quot;: &quot;^2.6.11&quot;,
    &quot;vuetify-loader&quot;: &quot;^1.5.0&quot;
  }
</code></pre>
",https://stackoverflow.com/questions/62561410/jest-unit-test-cant-determine-vuetify-components-visibility,"['vuejs2', 'jestjs', 'vuetify.js', 'jest-dom']",4721,True,2,1
How to enforce queue to NOT run on main thread in Swift unit tests,"<p>There are many examples on how to enforce code to run on main thread. I have an opposite need for unit testing purposes. I want to exclude main thread from taking on some work. </p>

<p>Why do I need this: I would like to test that a particular function runs correctly, specifically when it's simultaneously called from 2 or more <strong>background</strong> threads (while main thread is free and available). This is because function itself makes use of main thread, while it is a typical use case that it will be called from background threads, possibly concurrently. </p>

<p>I already have one test case where one of the calling threads is the main thread. But I also want to test the case when main thread is not busy, when 2 or more other threads call the function.</p>

<p>The problem is that there's seems no way to leave main thread free. For instance even if queue is defined with <code>qoc: .background</code>, main thread was still taken:</p>

<pre><code>private let queue = DispatchQueue(label: ""bgqueue"", qos: .background, attributes: .concurrent)
let iterations = 10
DispatchQueue.concurrentPerform(iterations: iterations) { _ in

    queue.async { 
        callMyFunction() // still may run on main thread, even with 1-2 iterations
    }
}
</code></pre>

<p>The only approach I can think of is blocking all threads at the same spot (using <a href=""https://github.com/uber/swift-concurrency/blob/master/Sources/Concurrency/CountDownLatch.swift"" rel=""nofollow noreferrer"">CountDownLatch</a> for example), and then proceed to function from all threads, but main:</p>

<pre><code>let latch = CountDownLatch(count: iterations)

DispatchQueue.concurrentPerform(iterations: iterations) { _ in

    latch.countdown()
    latch.await()
    if !Thread.isMainThread {
        callMyFunction()
    }
}
</code></pre>

<p>The problems here are 1 - have to make sure <code>iterations &lt; available threads</code>; 2 - feels wrong to block main thread.</p>

<p>So is there any better solution? <strong>How to exclude main thread from picking up <code>DispatchQueue</code> work within unit tests?</strong> </p>
",https://stackoverflow.com/questions/62435831/how-to-enforce-queue-to-not-run-on-main-thread-in-swift-unit-tests,"['swift', 'multithreading']",934,False,1,1
Python: can I unpack arguments without calling a function?,"<p>I have <code>dict</code> that I want to convert to several different objects.  For instance:</p>
<h3>Currently Have</h3>
<pre class=""lang-py prettyprint-override""><code>kwargs = {'this': 7, 'that': 'butterfly'}
</code></pre>
<hr />
<p>And I want to convert it, maybe using something similar to function argument unpacking, but without actually calling a function, so that I end up with something like:</p>
<h3>Desired</h3>
<pre class=""lang-py prettyprint-override""><code>**kwargs
print(this) # Will print out `7`
print(that) # Will print out `'butterfly'`
</code></pre>
<p>I know that I cannot use the double-star [<code>**</code>] bare like I have shown.  But is there something similar I can do?</p>
<hr />
<h1>Edit: More Specifics</h1>
<p>Since folks were asking for details and warning that what I am trying to do is dangerous, I will give more context for my need.</p>
<p>I have a <em>property</em> in a class that I want to set using keyword arguments.  Something like what is <a href=""https://stackoverflow.com/a/18714518/534238"">shown here</a>, but unpacking <code>kwargs</code> instead of <code>args</code>.</p>
<p>As a functioning toy example, it looks like this:</p>
<pre class=""lang-py prettyprint-override""><code>
class A(object):
    def __init__(self):
        self._idx = None
    @property
    def idx(self):
        return self._idx
    @idx.setter
    def idx(self, kwargs):
        print(kwargs)
        self._idx = {}
        for kw, val in kwargs.items():
            self._idx[kw] = val

</code></pre>
<p>This works. But now I am unit testing the function, and in the unit test, I would like to be able to provide the specific key-value pairs as normal objects, so that I can effectively use <code>hypothesis</code> and <code>pytest</code>'s <code>@mark.parametrize</code> effectively.</p>
<p>In order to do this, it looks like I will need the &quot;bare unpacking&quot; like I described above.</p>
<p>Since these are all actually local variables within a method, I feel like @g.d.d.c's concerns are probably not significant.  It sounds like his worries were if I created new global variables without knowing what they were.</p>
",https://stackoverflow.com/questions/64246258/python-can-i-unpack-arguments-without-calling-a-function,"['python', 'iterable-unpacking', 'argument-unpacking']",507,True,1,2
How to tell git to preserve CRLF specifically for a single set of files? Mark a text file as binary?,"<p>I want to set some of the text files in a repo to be cloned/downloaded as binary. Ie: Bypass the CRLF settings in git and just clone byte per byte.</p>
<h1>Context</h1>
<p>There are myriads of posts about CRLF in git. But normally they are about the general settings of whole projects, mainly depending on if you use Linux or Windows.</p>
<p>But I face a situation that never found before. I am willing to set a folder in my project with sample emails as defined by the <a href=""https://www.rfc-editor.org/rfc/rfc5322"" rel=""nofollow noreferrer"">RFC 5322</a> which define that the end-of-line of the emails are exactly <code>CRLF</code>. It's a project related to emailing and those are going to be used for unit-testing.</p>
<p>If I leave the system to treat the text files as it wants, those files will download as <code>LF</code> in many cases.</p>
<p>I want those few files to be &quot;forced&quot; to be downloaded in &quot;binary mode&quot;, so whatever the platform or settings where you are doing the <code>git clone</code>, those files will not have lost a single byte; otherwise they would break the standard.</p>
<h1>Question</h1>
<ul>
<li>Is this possible?</li>
<li>How can I signal <strong>only</strong> those those files as &quot;binary&quot; at the add or commit time so anyone willing to clone will have them properly cloned?</li>
<li>Is there any switch for the <code>add</code> or <code>commit</code> I should use?</li>
</ul>
",https://stackoverflow.com/questions/61845148/how-to-tell-git-to-preserve-crlf-specifically-for-a-single-set-of-files-mark-a,"['git', 'email', 'newline', 'binaryfiles']",141,True,1,1
How to assert true and false in single parameterized test method,"<p>I am new to Unit Testing and quite confusing about testing true or false result returned from method rely on parameter. I am currently using NUnit and MoQ, below is my code. Test will run three times with value A, B, C for each time respectively.</p>

<pre><code>[Test]
    public void IFoo_Return_True_With_A_As_Input([Values(""A"", ""B"", ""C"")]string value){
        var mock = new Mock&lt;IFoo&gt;();
        // setup
        mock.Setup(foo =&gt; foo.DoSomething(""A"")).Returns(true);

        // Arrage
        Func&lt;string, bool&gt; action = (_) =&gt; mock.Object.DoSomething(_);

        // Act
        bool result = action(value);

        // Assert
        Assert.That(result, /* ??? */);
    }
</code></pre>

<p>I have a method which receives a value through parameter <em>IFoo.DoSomething</em> and it will return <strong>true</strong> if the value of parameter is <em>A</em>, otherwise it will return <strong>false</strong>. I do not know how to present this kind of test in single test. </p>

<p>I thought I can not use multiple assertions(I mean one assert for true and other for false) because result will be evaluated to true or false per test. I thought I could use <em>TestCase</em> with <em>ExpectedResult</em> OR <em>Assume</em> before Assert OR write two test(one for A value and other for other values) but I would like to know whether we have any sophisticated ways to achieve kind this test.</p>

<p>My expectation would be three test will passed with true or false evaluated rely on supplied value in single test. Please advise me if I am not going on the right track about Unit Test.</p>

<p>The setup of mock is the way I present the implementation of <em>IFoo.DoSomething</em> method. Its logic is return true if value is A and false if otherwise.</p>
",https://stackoverflow.com/questions/61152038/how-to-assert-true-and-false-in-single-parameterized-test-method,"['unit-testing', 'nunit']",1933,True,1,1
How to pass a variable from properties file when testing my SpringBoot app with Mockito?,"<p><strong>SOLUTION</strong></p>
<p>Instead of annotating the field &quot;path&quot; in DiceRollerService class with @Value(&quot;${path.to.randomizer}&quot;), I passed the annotation to class constructor:</p>
<pre><code>@Service
public class DiceRollerService {
private String path;
private final CustomHttpClient client;

@Autowired
public DiceRollerService(CustomHttpClient client, @Value(&quot;${path.to.randomizer}&quot;) String path) {
    this.client = client;
    this.path = path;
}
</code></pre>
<p>In this case, if I use the default constructor, the path field will be linked to the corresponding value from application properties, otherwise, if I use this specific constructor, I can pass the specific path value through it. Here is how my unit-test looks now:</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class DiceRollerTest {
private static final String PATH_FOR_TEST = &quot;Some URL path&quot;;
private static final int DICE_NUMBER_ONE = 2;
private static final int DICE_NUMBER_TWO = 2;

@Mock
private CustomHttpClient client;

private DiceRollerService diceRollerService;

@Before
public void init() {
    diceRollerService = new DiceRollerService(client, PATH_FOR_TEST);
}

@Test
public void testDiceRollerServiceWithCorrectPathAndBody() {
    Dices expected = new Dices(DICE_NUMBER_ONE, DICE_NUMBER_TWO);
 when(client.getResponseBodyFromClient(PATH_FOR_TEST)).thenReturn(BODY_TEST);
    Dices actual = diceRollerService.roll();
    Assert.assertEquals(expected, actual);
    verify(client).getResponseBodyFromClient(anyString());
}
</code></pre>
<p><strong>INITIAL PROBLEM</strong></p>
<p>I need some assistance with unit- and/or integration-testing of my small project. I have a class that has only one important method to return a Dice model:</p>
<pre><code>@Service
public class DiceRollerService {
    @Value(&quot;${path.to.randomizer}&quot;)
    private String path;
    private final static int FIRST_DICE_NUMBER_POS = 0;
    private final static int SECOND_DICE_NUMBER_POS = 2;
    private final CustomHttpClient client;

public DiceRollerService(CustomHttpClient client) {
    this.client = client;
}

public Dices roll() {
    String results = client.sendGetRequest(path).body();
    int firstNumber = Integer.parseInt(String.valueOf(results.charAt(FIRST_DICE_NUMBER_POS)));
    int secondNumber = Integer.parseInt(String.valueOf(results.charAt(SECOND_DICE_NUMBER_POS)));
    return new Dices(firstNumber, secondNumber);
}

public void setPath(String path) {
    this.path = path;
}
}
</code></pre>
<p>As you can see, in method roll() I invoke client.sendGetRequest(path) to get a HttpResponse' body and to fetch some data from it in order to build and return a Dice model. Nothing complicated except that the actual path is located at my properties file at src/main/resources/application.properties.
Later on, i decided to add some tests for my project to check the logic:</p>
<pre><code>public class DiceRollerTest {
@Mock
private CustomHttpClient client;

@InjectMocks
private DiceRollerService diceRollerService;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void test() {
    Dices expected = new Dices(2, 2);
    when(client.sendGetRequest(anyString()).body()).thenReturn(&quot;2 2 &quot;);
    Dices actual = diceRollerService.roll();
    Assert.assertEquals(expected, actual);
    verify(client, times(1)).sendGetRequest(anyString()).body();
}
}
</code></pre>
<p>Unfortunately, as a result a got a nullpointer at this line:         when(client.sendGetRequest(anyString()).body()).thenReturn(&quot;2 2 &quot;);
Seems that my mock doesn't work as I expected. Here are all my dependencies :</p>
<pre><code>&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
        &lt;exclusions&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
            &lt;/exclusion&gt;
        &lt;/exclusions&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;
        &lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;version&gt;4.13&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.mockito&lt;/groupId&gt;
        &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
        &lt;version&gt;3.3.3&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.mockito&lt;/groupId&gt;
        &lt;artifactId&gt;mockito-inline&lt;/artifactId&gt;
        &lt;version&gt;3.3.3&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
</code></pre>
<p>Is there any way I can use my properties in unit-testing? How can I properly fix that? Will appreciate any piece of advice. Thanks in advance.</p>
",https://stackoverflow.com/questions/63995379/how-to-pass-a-variable-from-properties-file-when-testing-my-springboot-app-with,"['java', 'spring-boot', 'unit-testing', 'mockito', 'integration-testing']",1140,True,1,2
Unit testing MVC controller - need path to the application,"<p>I've inherited a legacy ASP.net MVC application and I'm trying to backfit unit test and running into an error.  Here's my unit test:</p>

<pre><code>public void DashboardController_Index_ReturnsIndex()
     {
         var dashboardController = _mocker.Resolve&lt;DashboardController&gt;();
         var controllerContextMock = new Mock&lt;ControllerContext&gt;();
         var userMock = new Mock&lt;IUserContext&gt;();

         userMock
             .SetupGet(u =&gt; u.Identity.IsAuthenticated)
             .Returns(true);
         userMock
             .Setup(u =&gt; u.Type)
             .Returns(EUserType.Normal);
         controllerContextMock
             .SetupGet(c =&gt; c.HttpContext.User)
             .Returns(userMock.Object);
         controllerContextMock
             .SetupGet(p =&gt; p.HttpContext.Request.Url)
             .Returns(new Uri(""http://localhost/Dashboard/Index""));

         dashboardController.ControllerContext = controllerContextMock.Object;

         var result = dashboardController.Index() as ViewResult;

         Assert.Equal(""Index"", result.ViewName);
     }
</code></pre>

<p>When the Index action is called, it calls a static method in another class that returns a string expression used for configuration purposes.  After that config string gets returned, another static method in another (referenced) static class (different namespace) gets called which attempts to parse that string expression but throws an exception.  Here's that method:</p>

<pre><code>private static string GetResourceString(HttpContextBase httpContext, string sxExpression, string sxVirtualPath)
        {
            var context = new ExpressionBuilderContext(sxVirtualPath);
            var builder = new ResourceExpressionBuilder();
            var fields = (ResourceExpressionFields)builder.ParseExpression(sxExpression, 
                typeof(string), context);

            if (string.IsNullOrEmpty(fields.ClassKey) == false)
                return (string)httpContext.GetGlobalResourceObject(fields.ClassKey, fields.ResourceKey, 
                    Thread.CurrentThread.CurrentCulture);
            return (string)httpContext.GetLocalResourceObject(sxVirtualPath, fields.ResourceKey, 
                Thread.CurrentThread.CurrentCulture);
        }
</code></pre>

<p>The exception occurs in the third line of this method where the code attempts to break the string into fields.  Specifically, here's the exception:</p>

<blockquote>
  <p>System.Web.HttpException (0x80004005): The application relative virtual path '~/' cannot be made absolute, because the path to the application is not known.</p>
</blockquote>

<p>I've seen <a href=""https://stackoverflow.com/questions/6428372/how-to-mock-application-path-when-unit-testing-web-app/6528979"">this post</a> that describes how to inject a fake into this call but since the Controller itself isn't trying to parse the string, but rather handing it off to a helper method in another class, it seems that DI won't work.  Any idea how I can fake the application path while unit testing?  In production, this code works just fine.  I'm thinking I can refactor the controller to use this helper class as a dependency instead of just calling static methods but I'm hoping for a solution that doesn't require code changes to production code.</p>
",https://stackoverflow.com/questions/60292193/unit-testing-mvc-controller-need-path-to-the-application,"['c#', 'asp.net-mvc', 'unit-testing']",134,True,1,1
What is the intended purpose of @JobScope in Spring Batch? What&#39;s the intended way to share in-memory data between steps?,"<p>I'm using it today to cache objects between steps so that I don't have to build the entire job in a single step. At first, since my Steps were not annotated with any scope (though it's hard to make sense of them not implicitly being <code>@JobScope</code>) I ran into some gnarly unit testing issues claiming:</p>

<p><strong>Scope 'job' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for job scope</strong></p>

<p>I read (on the since abandoned Gitter thread (which was very informative)) that this may not be the right use case for @JobScope. Indeed I'm concerned now that the job scope is per thread somehow.  </p>

<p>This leads me to the question of what is the purpose of <code>@JobScope</code>, if I really am misusing it?  And if I'm misusing it what is the right way to share data between Steps in the same job without writing to a database table/temporary file only to turn around and read it at the start of the next step?<br>
As a side note: (and Spring Batch is no different than other frameworks in this regard) these questions stem from the available examples being too simplistic to have much bearing on real-world use. </p>
",https://stackoverflow.com/questions/60642390/what-is-the-intended-purpose-of-jobscope-in-spring-batch-whats-the-intended-w,['spring-batch'],474,True,1,1
Using Jenkins Docker Slaves on Amazon Linux 2 AMI,"<p>I'm running into a strange issue using the standard docker images provided by Jenkins - only when Jenkins is running on Amazon Linux 2 though. Jenkins on Ubuntu 18.04 works fine.</p>
<p>The problem is that Jenkins is not able to launch these slave containers.</p>
<p>Connect method - &quot;Attach Docker Container&quot;  since the docker engine is running locally on the Jenkins server.</p>
<p>Interestingly, I've been able to get these containers to successfully run for a build on Amazon Linux if I set <code>USER root</code> in a new DockerFile (not required on Ubuntu). However, I need these to be running as a non-root user (like jenkins user) in order to run unit testing for postgres.</p>
<p>Any thoughts on how I can achieve that for Amazon Linux 2? Could I be missing a docker setting or security setting on the OS?</p>
<h2><strong>Docker images I've tested:</strong></h2>
<ul>
<li><a href=""https://hub.docker.com/r/jenkins/agent/"" rel=""nofollow noreferrer"">https://hub.docker.com/r/jenkins/agent/</a></li>
<li><a href=""https://hub.docker.com/r/jenkins/jnlp-slave"" rel=""nofollow noreferrer"">https://hub.docker.com/r/jenkins/jnlp-slave</a></li>
<li><a href=""https://hub.docker.com/r/jenkins/inbound-agent"" rel=""nofollow noreferrer"">https://hub.docker.com/r/jenkins/inbound-agent</a></li>
</ul>
<h2><strong>The errors aren't super helpful:</strong></h2>
<p><a href=""https://i.stack.imgur.com/4W3zg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4W3zg.png"" alt=""enter image description here"" /></a></p>
<p>Connecting to docker container 4486c8f2696f40c7de32160d78d6e2438abb1ff92517c71cf66b93baf3d0877f, running command java -jar /home/jenkins/remoting-4.6.jar -noReconnect -noKeepAlive -slaveLog /home/jenkins/agent.log
HTTP/1.1 101 UPGRADED
Content-Type: application/vnd.docker.raw-stream
Connection: Upgrade
Upgrade: tcp
Api-Version: 1.40
Docker-Experimental: false
Ostype: linux
Server: Docker/19.03.13-ce (Linux)</p>
<p>ERROR: Unexpected error in launching an agent. This is probably a bug in Jenkins</p>
<h2><strong>A Basic Setup to Reproduce:</strong></h2>
<p><a href=""https://i.stack.imgur.com/Yo9Tg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Yo9Tg.png"" alt=""enter image description here"" /></a></p>
<h2><strong>Docker Template:</strong></h2>
<p><a href=""https://i.stack.imgur.com/zUezi.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/zUezi.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/64797740/using-jenkins-docker-slaves-on-amazon-linux-2-ami,"['linux', 'docker', 'jenkins', 'amazon-linux']",800,False,1,3
Testing what method is called based on branch conditions - everything tested except the controller is behind an interface,"<p>I'm pretty new to unit testing, and I have a method that returns a Func based on some branching logic. My issue is, the unit test can't see what method is actually called, perhaps because it is testing the interface. I have to explicitly write in the setup what method will be returned, however I think this defeats the purpose of the test for me since I want to test that the correct method is returned in the branch logic.</p>

<p>This is the method definition in the interface:</p>

<pre><code>Func&lt;Task&lt;IEnumerable&lt;T&gt;&gt;&gt; GetMethod(int param);
</code></pre>

<p>and it returns one of these three:</p>

<pre><code>Task&lt;IEnumerable&lt;T&gt;&gt; MethodOne();
Task&lt;IEnumerable&lt;T&gt;&gt; MethodTwo();
Task&lt;IEnumerable&lt;T&gt;&gt; MethodThree();
</code></pre>

<p>Here is how I set it up in the test, problem is even when I make the actual code return MethodTwo when it should return MethodOne, the test still passes because of this. However, if I don't set it up this way, the test will only see GetMethod being called :(</p>

<pre><code>var service = fixture.Freeze&lt;Mock&lt;IGetMethodInterface&gt;&gt;();
            service.Setup(i =&gt; i.GetMethod(It.IsAny&lt;int&gt;()))
            .Returns(() =&gt; service.Object.MethodOne());

var sut = fixture.Create&lt;MethodController&gt;();
await sut.CallGetMethod();

service.Verify(i =&gt; i.GetMethod(It.IsAny&lt;int&gt;()), Times.Once());
service.Verify(i =&gt; i.MethodOne(), Times.Once());

</code></pre>

<p>The sad part is, AutoMoq doesn't like concrete classes being used with Verify - so I can't go and use a concrete class implementation in the test:</p>

<p>Here is where its called in the controller:</p>

<pre><code>result = await methodInterface.GetMethod(5).Invoke();

return Ok(result);
</code></pre>

<p>Is there any way to test this correctly using an interface? Or I should definitely test a concrete class? If the concrete class is the only approach, how do we check that a class method is called? I dunno anything like the Verify() method in AutoMoq.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/61949417/testing-what-method-is-called-based-on-branch-conditions-everything-tested-exc,"['c#', 'moq']",35,True,1,1
C# Best method to create unique int32 identifier for complex object,"<p>I have a problem with getting unique int32 identifier with this properties:</p>

<ul>
<li>It has to be always the same for the same objects in current instance of a program</li>
<li>It has to always differ in current instance of a program for different objects, so no collisions at all.</li>
</ul>

<p>I need that unique identifier for comparing complex objects and working with classes like Dictionary&lt;> or HashSet&lt;> etc.</p>

<p>I would very much like to avoid using any kind of hash tables or precalculations of any kind but instead to have an algorithm that will do that on the fly in order to exclude external dependencies and make unit testing easier</p>

<p>Pseudocode of an object:</p>

<pre><code>    class ComplexObject
    {
        public readonly FirstEnum First; // ~50 different values
        public readonly IFirstModificator FirstModificator; // 4 implementations x 15 values (~60 values total)
        public readonly InternalObject[] Internal; //1-10 values in array 
    }

    class InternalObject
    {
        public readonly SecondEnum Second; // ~30 different values
        public readonly SecondModificator SecondModificator; //  ~15 different values
    }

</code></pre>

<p>In  case its important my domain model contains about 100 000 unique objects of type ComplexObject</p>

<p>I already tried:</p>

<ul>
<li>Serializing an object into json and getting a hash of that string(by using string.GetHashCode() method). It produces collisions even in current instance of a program.</li>
<li>Code like this produces  a lot of collisions too:</li>
</ul>

<pre><code>    unchecked
    {
        int hash = 17;
        hash = hash * 31 + firstField.GetHashCode();
        hash = hash * 31 + secondField.GetHashCode();
        return hash;
    }

    unchecked 
    {
        int hash = (int) 17;
        hash = (hash * 31) ^ field1.GetHashCode();
        hash = (hash * 31) ^ field2.GetHashCode();
        return hash;
    }

</code></pre>

<p><strong>UPDATED:</strong></p>

<p>IFirstModificator has different implementations, but in general it looks like that:</p>

<pre><code>    class FirstModificator : IFirstModificator
    {
        public int Value {get;set;} //~15 values
    }
</code></pre>

<p>Other parameters of implementation IFirstModificator affect \ apply to (not sure if my English is clear) only data processing.</p>

<pre><code>    class SecondModificator 
    {
        public int Value {get;set;} //~15 values
    }
</code></pre>

<p>External interface and data requred for creating instance of a class are similar to implementation IFirstModificator but they are in fact different classes.</p>
",https://stackoverflow.com/questions/62475446/c-best-method-to-create-unique-int32-identifier-for-complex-object,"['c#', 'hash', 'uid']",410,True,0,1
Should I unit test *what* or *how* for composite functions?,"<p>I have functions <code>f</code> and <code>g</code>, which already have a collection of unit tests ensuring that their behavior is correct for some known inputs-output pairs (plus exception handling, etc).</p>

<p>Now I'm creating the function <code>h()</code>, as follows:</p>

<pre><code>def h(x):
    return f(x) + g(2*x)
</code></pre>

<p>What's a good approach for unit testing this function? Would this change if <code>h()</code> was substantially more complex?</p>

<hr>

<p><em>My thoughts so far:</em> </p>

<p>I see two possibilities for testing <code>h()</code>.</p>

<h3>1. Testing if <code>h()</code> is doing the correct ""plumbing""</h3>

<p>Mock out <code>f()</code> so that it returns <code>y_0</code> when called with input <code>x_0</code>; mock <code>g()</code> so that it returns <code>z_0</code> when called with input <code>2*x_0</code>. Then check that calling <code>h(x_0)</code> returns <code>y_0+z_0</code>.</p>

<p><em>Advantages</em>:</p>

<ul>
<li>Very simple to implement the test.</li>
<li>Can quickly find bugs where I incorrectly connected the outputs of <code>f</code> and <code>g</code>, or where I called them with wrong arguments (say, calling <code>g(x)</code> instead of <code>g(2*x)</code> in <code>h()</code>).</li>
</ul>

<p><em>Disadvantages</em>:</p>

<ul>
<li>This is testing <em>how</em>, not <em>what</em> <code>h()</code> should do. If later I want to refactor <code>h()</code>, then I'll probably need to rewrite these types of tests.</li>
<li>If the plumbing specified by the test does not produce the intended high-level behavior for <code>h()</code>, then these tests won't catch this error. For example, maybe the correct plumbing was supposed to be <code>f(-x) + g(2*x)</code>, and I made it wrong both in the function definition and in the test definition.</li>
</ul>

<h3>2. Testing <strong>what</strong> <code>h()</code> should do</h3>

<p>Let's say that the purpose of <code>h()</code> is to compute the sum of primes below the given argument. In this case, a natural test suite for <code>h()</code> would involve testing it with known input-output pairs. Something that makes sure that, for instance, <code>h(1)=2</code>, <code>h(2)=5</code>, <code>h(5)=28</code>, etc, not caring about <strong>how</strong> <code>h()</code> is computing these numbers.</p>

<p><em>Advantages</em>: </p>

<ul>
<li>This type of test checks that <code>h()</code> is indeed following its intended high-level behavior. Any plumbing mistakes that alter this will be caught.</li>
<li>Refactoring <code>h()</code> will probably not necessitate changing the test suite, and will even be easier, since the tests help us guarantee that the behavior of the function doesn't change.</li>
</ul>

<p><em>Disadvantages</em>:</p>

<ul>
<li>In this simple example it's easy to produce such pairs because the mapping that <code>h()</code> performs is not very complicated (just sum the <code>n</code> first primes). However, for a very complicated <code>h()</code>, my only option for producing such pairs might be me to come up with an input <code>x</code> and compute the correct output by hand. This doesn't seem reasonable if <code>h</code> is very complicated.</li>
<li>Since coming up with known input-output pairs requires me to compute what <code>f()</code> and <code>g()</code> will produce given a certain input, there will probably be some duplication of effort, since I already spent some time doing that when creating the unit tests for these functions.</li>
</ul>

<hr>

<p><em>Related question</em>: <a href=""https://stackoverflow.com/questions/45654729/unit-testing-composite-functions"">Unit testing composite functions</a>.</p>

<p>This question is at first glance very similar to mine. However, the two most voted answers present completely different approaches to the problem (the two approaches I mentioned above). My question is an attempt in clarifying the pros/cons of each approach (and perhaps learn other approaches), and potentially establish which is best overall. If no approach is best in all cases, I would like to understand in which cases one should use each of them.</p>
",https://stackoverflow.com/questions/60410919/should-i-unit-test-what-or-how-for-composite-functions,"['unit-testing', 'testing']",184,True,1,2
"DeepSleepLock underflow error when doing pow(2, ((m - 69.0f) / 12.0f)) - MBed OS","<p>I'm using MBed OS on an NUCLEO_L432KC and the MBed CLI to compile, flash, and test. Using OpenOCD and gdb to debug. MBed has their own GreenTea test automation tool for unit testing on the embedded hardware and it used the utest and Unity testing frameworks.</p>

<p>When I use GreenTea to unit test this function:</p>

<pre><code>float Piano::midiNumToFrequency(uint8_t m)
{
    float exp = (m - 69.0f) / 12.0f;
    return pow(2, exp);
}
</code></pre>

<p>I get a DeepSleepLock underflow error:</p>

<blockquote>
  <p>[1589410046.26][CONN][RXD] ++ MbedOS Error Info ++
  [1589410046.30][CONN][RXD] Error Status: 0x80040124 Code: 292 Module:
  4 [1589410046.35][CONN][RXD] Error Message: DeepSleepLock underflow (&lt;
  0) [1589410046.37][CONN][RXD] Location: 0x8003B09
  [1589410046.40][CONN][RXD] File: mbed_power_mgmt.c+197
  [1589410046.43][CONN][RXD] Error Value: 0xFFFF
  [1589410046.53][CONN][RXD] Current Thread: main Id: 0x20001200 Entry:
  0x80044A7 StackSize: 0x1000 StackMem: 0x20001C18 SP: 0x2000FF04
  [1589410046.62][CONN][RXD] For more info, visit:
  <a href=""https://mbed.com/s/error?error=0x80040124&amp;tgt=NUCLEO_L432KC"" rel=""nofollow noreferrer"">https://mbed.com/s/error?error=0x80040124&amp;tgt=NUCLEO_L432KC</a>
  [1589410046.64][CONN][RXD] – MbedOS Error Info –</p>
</blockquote>

<p>Yet when I change the function to this:</p>

<pre><code>float Piano::midiNumToFrequency(uint8_t m)
{
    float exp = (m - 69.0f);
    return pow(2, exp);
}
</code></pre>

<p>it works and tests fine.</p>

<p>MBed has an error status decoder <a href=""https://armmbed.github.io/mbedos-error/?error=0x80040124&amp;tgt=NUCLEO_L432KC"" rel=""nofollow noreferrer"">here</a> which says</p>

<blockquote>
  <p>Use the ""Location"" reported to figure out the address of the location
  which caused the error or try building a non-release version with
  MBED_CONF_PLATFORM_ERROR_FILENAME_CAPTURE_ENABLED configuration
  enabled to capture the filename and line number where this error
  originates from.</p>
</blockquote>

<p>When I enable the MBED_CONF_PLATFORM_ERROR_FILENAME_CAPTURE_ENABLED, it says the location is in mbed_power_mgmt.c line 197 which is the functoin:</p>

<pre><code>/** Send the microcontroller to sleep
 *
 * @note This function can be a noop if not implemented by the platform.
 * @note This function will be a noop in debug mode (debug build profile when MBED_DEBUG is defined).
 * @note This function will be a noop if the following conditions are met:
 *   - The RTOS is present
 *   - The processor turn off the Systick clock during sleep
 *   - The target does not implement tickless mode
 *
 * The processor is setup ready for sleep, and sent to sleep using __WFI(). In this mode, the
 * system clock to the core is stopped until a reset or an interrupt occurs. This eliminates
 * dynamic power used by the processor, memory systems and buses. The processor, peripheral and
 * memory state are maintained, and the peripherals continue to work and can generate interrupts.
 *
 * The processor can be woken up by any internal peripheral interrupt or external pin interrupt.
 *
 * @note
 *  The mbed interface semihosting is disconnected as part of going to sleep, and can not be restored.
 * Flash re-programming and the USB serial port will remain active, but the mbed program will no longer be
 * able to access the LocalFileSystem
 */
static inline void sleep(void)
{
#if DEVICE_SLEEP
#if (MBED_CONF_RTOS_PRESENT == 0) || (DEVICE_SYSTICK_CLK_OFF_DURING_SLEEP == 0) || defined(MBED_TICKLESS)
    sleep_manager_sleep_auto();
#endif /* (MBED_CONF_RTOS_PRESENT == 0) || (DEVICE_SYSTICK_CLK_OFF_DURING_SLEEP == 0) || defined(MBED_TICKLESS) */
#endif /* DEVICE_SLEEP */
}
</code></pre>

<p>Any ideas why this is happening or how to troubleshoot further?</p>
",https://stackoverflow.com/questions/61822917/deepsleeplock-underflow-error-when-doing-pow2-m-69-0f-12-0f-mbed-os,"['embedded', 'mbed', 'utest', 'unity-test-framework']",268,True,0,1
When is the use of &quot;|| true&quot; needed in bash?,"<p>I use <a href=""https://travis-ci.com/"" rel=""nofollow noreferrer"">Travis CI</a> to do unit testing for my open source project.  While configuring my <code>.travis.yml</code> file I've seen examples on several other projects, and some inconsistent use of <code>|| true</code> following some conditionals in the script.  I have seen them in two formats.</p>

<p>When the statement is executed as a conditional, I understand the need for <code>|| true</code> to ensure the command returns ""success"" and allows the script to continue.  A non-match on the name would be false, omit execution of later commands after <code>&amp;&amp;</code>, but eventually return successful after <code>|| true</code>.</p>

<pre><code>- '[ ""${TRAVIS_OS_NAME}"" = ""osx"" ] &amp;&amp; brew install ant || true'
</code></pre>

<p>However, I have also seen the conditional applied after <code>if ... fi</code> conditionals, such as this example:</p>

<pre><code>- if [ ""${TRAVIS_CPU_ARCH}"" == ""arm64"" ]; then 
    sudo apt-get install openjdk-11-jdk libltdl-dev;
    export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-arm64;
    export PATH=$JAVA_HOME:$PATH; 
  fi || true
</code></pre>

<p>My own testing indicates it makes no difference whether that's included or not.  For example, this conditional does not stop the test, even when it evaluates to false.  For example:</p>

<pre><code>if [ ""${TRAVIS_BRANCH}"" == ""coverity_scan"" ]; then exit 0; fi
</code></pre>

<p>Travis produces this output, showing a ""true"" result: </p>

<blockquote>
  <p>The command ""if [ ""${TRAVIS_BRANCH}"" == ""coverity_scan"" ]; then exit 0; fi"" exited with 0.</p>
</blockquote>

<p>The script continues past this point without complaint, on the ""master"" branch.  My assessment is that an <code>if [ false ] then; ...; fi</code> conditional either returns true, or is effectively a no-operation, and it's not needed.</p>

<p>Is <code>|| true</code> necessary, or even useful, to add after a <code>if ... fi</code> conditional in the case where the conditional is false?  (Assume I want the script to fail if the conditional is true and a statement inside it fails.)</p>
",https://stackoverflow.com/questions/61879498/when-is-the-use-of-true-needed-in-bash,"['bash', 'conditional-statements', 'travis-ci']",89,True,0,1
